GEOFFREY YOUNG PAUL LINDNER RANDY KOBES " Reviews of the mod_perl Cookbook "Although the authors cautioned that this book is by no means comprehensive, I would say that this book is as close as a book can get to become the bible ofmod_perl. So ifyou are really serious about mod_perl, then get itby all means!" — Apache Week "This is the book that mod_perlprogrammers have been waiting for. The three authors are all well-known experts in the field and it's great that they have shared their knowledge through this book. Ifyou write mod_perl applications, then you really should read this book." — Slashdot.org "The best way to measure how goodone ofthese cookbooks is uses the amount of Post-it notes sticking outofthe top and the amountofcreases on the spine. By this benchmark, this is a pretty useful book." — Evolt.org "Bloodygood. — Nat Torkington, use.perl journal "The recipes are excellent, and the commentary on them well thoughtoutand thorough." —Matt Sergeant use.perl journal "The mod_perl Cookbook is excellent. I've been devouring it for the past week or so, and it so clearly illustrates the problems and their solutions that I'm running into as I implement mod_perl in favor ofPHP. The examples are realistic enough to be useful, and thorough enough to showexactly how to do it. This book is just the springboard I needed into mod_perl. Kudos all around." — Andy Lester "Stylistically, the code presented is impeccable. The authors are well-versed in both Perl and mod_perl idiom, and are not afraid to share this with the reader." — Simon Cozens, perl.com 1 GEOFFREY YOUNG PAUL LINDNER RANDY KOBES mo d_ perl COOKBOOK DEVELOPER'S 201 West 103rd Street, Indianapolis, Indiana 46290 mod_perl Developer's Cookbook AcquisitionsEditor Copyright©2002 bySamsPublishing PatriciaBarnes Allrightsreserved.Nopartofthisbookshallbereproduced,storedina DevelopmentEditor retrievalsystem,ortransmittedbyanymeans,electronic,mechanical, ScottD. Meyers photocopying,recording,orotherwise,withoutwrittenpermissionfromthe publisher.Nopatentliabilityisassumedwithrespecttotheuseofthe ManagingEditor CharlotteClapp informationcontainedherein.Althougheveryprecautionhasbeentakenin thepreparationofthisbook,thepublisherandauthorassumenoresponsi- ProjectEditor bilityforerrorsoromissions.Norisanyliabilityassumedfordamages LindaSeifert resultingfromtheuseoftheinformationcontainedherein. CopyEditor InternationalStandardBookNumber:0-672-32240-4 PaulaLowell LibraryofCongressCatalogCardNumber:2001089388 Proofreader PrintedintheUnitedStatesofAmerica BobLaRoche FirstPrinting:January2002 Indexer Secondprintingwithcorrections:November2002 EricSchroeder 04 03 02 4 3 2 Technical Editors MarkSenn Trademarks Ken Williams Alltermsmentionedinthisbookthatareknowntobetrademarksorservice TeamCoordinator markshavebeenappropriatelycapitalized.Samscannotattesttotheaccuracy Lynne Williams ofthisinformation.Useofaterminthisbookshouldnotberegardedas affectingthevalidityofanytrademarkorservicemark. InteriorDesigner GaryAdair Warning and Disclaimer CoverDesigner Everyefforthasbeenmadetomakethisbookascompleteandasaccurateas AlanClements possible,butnowarrantyorfitnessisimplied.Theinformationprovidedison an"asis"basis.Theauthorandthepublishershallhaveneitherliabilitynor Page Layout responsibilitytoanypersonorentitywithrespecttoanylossordamages Mark Walchle arisingfromtheinformationcontainedinthisbook. Contents at a Glance Introduction Part 1 Installation and Configuration 1 Installingmod_perl 9 2 Configuringmod_perl 45 Part II The mod_perl API 3 TheApache RequestObject 81 4 CommunicatingwiththeApache Server 127 5 URIManipulation 153 6 FileHandling 179 7 CreatingHandlers 209 8 InteractingwithHandlers 263 9 TuningApache and mod_perl 305 10 Object-Orientedmod_perl 349 Part III Programmingthe Apache Lifecycle 11 The PerllnitHandler 383 12 ThePerlTransHandler 391 13 ThePerlAccessHandler, PerlAuthenhandler, andPerlAuthzHandler 413 14 ThePerlTypeHandlerandPerlFixupHandler 449 15 ThePerlHandler 473 16 The PerlLogHandlerandPerlCleanupHandler 545 17 ThePerlChildlnitHandler,PerlChildExitHandler, PerlRestartHandler, and PerlDispatchHandler 567 Appendixes A Availablemod_perlHooksand Build Flags 587 B Available Constants 601 C mod_perl Resources 611 Index 617 Table of Contents Introduction 1 Part I Installation and Configuration 7 1 Installing mod_perl 9 Introduction 9 1.1.UnixBinaryInstallation 10 1.2. Windows BinaryInstallation 14 1.3.MacOSXBinaryInstallation 15 1.4. Buildingmod_perlonUnix 16 1.5. Buildingmod_perlonWindows 21 1.6. Buildingmod_perlonMacOSX 25 1.7. Buildingmod_perl asa SharedLibrary 27 1.8.TestingYourInstallation 28 1.9. ChangingApacheInstallationDirectories 29 1.10. Addingmod_perl toanExistingApache Server 30 1.11. ReusingConfigurationDirectives 31 1.12. Re-Creatingamod_perl Installation 32 1.13. Distributingmod_perltoManyMachines 32 1.14. InspectinganExistingServer 36 1.15. InstallingApacheModulesfromCPAN 37 1.16. Followingmod_perl Development 38 1.17. Beyond SimpleCVS 39 1.17. Buildingmod_perlwithDifferentperls 42 2 Configuring mod_perl 45 Introduction 45 2.1. MigratingLegacyCGIScripts 46 2.2. UsingApache::Registry 47 2.3.The startup.pl Script 51 2.4. SharingScriptNamespaceUnderApache::Registry 54 2.5. Pre-CachingApache::Registry Scripts 54 2.6. PopulatingCGIEnvironmentVariables 56 2.7. SettingOtherEnvironmentVariables 57 1 2.8. UsingPerl Switches 58 2.9. BEGINand END Blocksin startup.pl 59 2.10. MaintainingYourOwn Libraries 60 2.11. Persistent DatabaseConnections 62 2.12. Pre-SpawningDatabase Connections 63 2.13.NonpersistentDatabaseConnectionsin a PersistentEnvironment 65 2.14. Settingmod_perl-OnlyVariables 66 2.15. SettingComplexmod_perlVariables 68 2.16. ConfiguringApachewith <Perl> Sections 69 2.17.PreservingOrderin <Perl> Sections 71 2.18. UsingCommand-Line Switches 72 2.19. RunningDual Servers 73 2.20. Usingmod_proxytoDirectRequeststoamod_perl Server 74 2.21. Usingmod_proxy_add_fbrward 74 Part li The mod_perl API 77 3 The Apache Request Object 81 Introduction 81 3.1.TheApache RequestObject 82 3.2.TheHTTP RequestMessage 83 3.3.TheClientRequest 86 3.4.AccessingClientRequestHeaders 88 3.5.AccessingHTMLFormFields 90 3.6. ReadingPOSTed DataManually 92 3.7.ManipulatingCookies 94 3.8. HandlingFileUploads 97 3.9. SettingServerResponse Headers 99 3.10. ControllingCachingBehavior 102 3.11. SendingServerResponse Headers 103 3.12. Settingthe Response Status 105 3.13. SettingErrorHeaders 109 3.14.ManipulatingHeaderswithMultipleLike Fields 11 3.15. UsingSubrequests 114 3.16. SettingHeadersforSubrequests 116 3.17 Short-CircuitingSubrequests 117 3.18 GettingorSettingthe RequestMethod 117 3.19AccessingtheRequestObjectfromXS 119 mod perl Developer's Cookbook 4 Communicating with the Apache Server 127 Introduction 127 4.1. AccessingtheApache::ServerObject 128 4.2. Simulating<IfModule>and <IfDefine> Directives 131 4.3. AccessingServerRoot and DocumentRoot 133 4.4.WritingtotheApacheErrorLog 136 4.5.AccessingtheApache ErrorLog Directive 138 4.6. Controllingthe LogLevel 139 4.7.AccessingtheApache:Connection Object 142 4.8. RemoteIPAddressesandHosts 144 4.9. Detectinga BrokenConnection 145 4.10.TerminatinganApacheChildProcess 148 5 URI Manipulation 153 Introduction 153 5.1. CapturingtheRequestURI 155 5.2. DeterminingtheURI <Location> 157 5.3.Alteringthe RequestURI 160 5.4. ConstructingaNewURI 164 5.5. EscapingSpecial CharactersWithinaURI 166 5.6. UsingtheURItoForceaMIMEType 168 5.7. CapturingContentfroma Subrequest 169 5.8. UsingApache::Util Outsidemod_perl 174 6 File Handling 179 Introduction 179 6.1. CreatingFilehandles 180 6.2. CreatingTemporaryFiles 182 6.3. Sendingan EntireFile 184 6.4.ReadingFilesintoVariables 187 6.5. GettingInformationAboutthe RequestedFile 188 6.6.WorkingwithConditionalHeaders 192 6.7. Byteservingand RangeRequests 196 6.8.ManipulatingDate-BasedHeaders Directly 202 6.9. Flushingthe PrintBuffers 202 6.10. RedirectingOutputFilehandles 204 Contents 7 Creating Handlers 209 Introduction 209 7.1. Creatinga mocl_perl Handler 210 7.2. BasicHandlerConfiguration 214 7.3. AddingHandlersOn-the-Fly 216 7.4. Preparinga Module forRelease 218 7.5. Creatinga ReleaseTarball 219 7.6. Creatinga Binary PPM Distribution 222 7.7. Writinga Live ServerTestSuite 225 7.8. AddingCustom Configuration Directives 233 7.9. ExpandingCustom Directive Prototypes 244 7.10.MergingCustom Configuration Directives 246 7.11. OverridingCore Directives 253 7.12. AddingUnique ServerTokens 259 7.13. ReleasingaModuletoCPAN 260 8 Interacting with Handlers 263 Introduction 263 8.1. RecognizingHandlerChanges 263 8.2. SharingData Within a ChildProcess 266 8.3. Creatinga SharedMemoryCache 268 8.4. MaintainingState 272 8.5. UsingInternal Redirects 277 8.6.WritingCustom ErrorDocuments 281 8.7. ResettingDefaultErrorDocuments 284 8.8.ManipulatingStackedPerl Handlers 286 8.9.ManipulatingStackedCHandlers 288 8.10.Accessingthe Environment 291 8.11. SharingData Between DifferentPhases 293 8.12. Determiningthe CurrentRequestPhase 296 8.13. ReadingaPerlModule'sConfiguration Data 297 8.14. ReadingaCModule'sConfiguration Data 298 9 Tuning Apache and mod_perl 305 Introduction 305 9.1. GatheringBasicServerInformation 308 9.2. GatheringSystemwideMemoryUsage Data 312 9.3. GatheringBasicServerMemoryData 313 mod perl Developer's Cookbook 9.4. GatheringDetailed ServerMemoryData 315 9.5. GatheringMemoryDataforPerlModules 317 9.6. ReducingModuleOverhead 320 9.7. ReducingOverallMemoryConsumption 321 9.8. IncreasingSharedMemory 322 9.9. CoarseProcessTuningUsingApache Directives 325 9.10. LimitingProcessGrowth 326 9.11. StoppingRunawayProcesses 329 9.12. ProfilingHandlers 330 9.13. FindingPerformance Bottlenecks 332 9.14. ServerPerformanceTuning 333 9.15. UsingApache asa ReverseProxyServer 338 9.16. Usingthe Perl Debuggerwithmod_perl 341 9.17. DebuggingApache::Registry Scripts 343 9.18. ReducingDebugOverhead 344 9.19. DebuggingSegmentationFaults 346 10 Object-Oriented mod_perl 349 Introduction 349 10.1. Classand ObjectCreation 350 10.2.MethodInheritance 353 10.3. CreatingMethod Handlers 356 10.4. UsingMethodHandlers 359 10.5. SubclassingtheApache Class 362 10.6. SubclassingtheApache ClassUsingXS 364 10.7 SubclassingApache::Registry 366 10.8. SubclassingApache::Request 370 Part III Programmingthe Apache Lifecycle 377 11 The PerllnitHandler 383 Introduction 383 11.1. ProcessingEven-Request 384 11.2. ProcessingEveryRequesttoa <Location> 386 11.3.Timingthe Request 387 11.4. Interruptingthe RequestCycle 389