contentinternal

500InternalServerError  时间:2021-03-06  阅读:()
1HTTPHandlers115Feb20141HTTPHandlersHTTPHandlers1.
1DescriptionThischapterexplainshowtoimplementtheHTTPprotocolhandlersinmod_perl.
1.
2HTTPRequestHandlerSkeletonAllHTTPRequesthandlershavethefollowingstructure:packageMyApache2::MyHandlerName;#loadmodulesthataregoingtobeuseduse.
.
.
;#compile(orimport)constantsuseApache2::Const-compile=>qw(OK);subhandler{my$r=shift;#handlercodecomesherereturnApache2::Const::OK;#oranotherstatusconstant}1;First,thepackageisdeclared.
Next,themodulesthataregoingtobeusedareloadedandconstantscompiled.
Thehandleritselfcomingnextandusuallyitreceivestheonlyargument:theApache2::RequestRecobject.
Ifthehandlerisdeclaredasamethodhandler:subhandler:method{my($class,$r)=@_;thehandlerreceivestwoarguments:theclassnameandtheApache2::RequestRecobject.
Thehandlerendswithareturncodeandthefileisendedwith1;toreturntruewhenitgetsloaded.
1.
3HTTPRequestCyclePhasesThosefamiliarwithmod_perl1.
0willfindtheHTTPrequestcycleinmod_perl2.
0tobealmostidenticaltothemod_perl1.
0'smodel.
Thedifferentthingsare:anewdirectivePerlMapToStorageHandlerwasaddedtomatchthenewphasemap_to_storageaddedbyApache2.
0.
thePerlHandlerdirectivehasbeenrenamedtoPerlResponseHandlertobettermatchthecorrespondingApachephasename(response).
15Feb201421.
1Descriptiontheresponsephasenowincludesfiltering.
ThefollowingdiagramdepictstheHTTPrequestlifecycleandhighlightswhichhandlersareavailabletomod_perl2.
0:HTTPcycleFromthediagramitcanbeseenthatanHTTPrequestisprocessedby12phases,executedinthefollow-ingorder:1.
PerlPostReadRequestHandler(PerlInitHandler)2.
PerlTransHandler3.
PerlMapToStorageHandler4.
PerlHeaderParserHandler(PerlInitHandler)5.
PerlAccessHandler6.
PerlAuthenHandler7.
PerlAuthzHandler8.
PerlTypeHandler9.
PerlFixupHandler10.
PerlResponseHandler11.
PerlLogHandler12.
PerlCleanupHandlerIt'spossiblethatthecyclewillnotbecompletedifanyofthephasesterminatesit,usuallywhenanerrorhappens.
InthatcaseApacheskipstotheloggingphase(mod_perlexecutesallregisteredPerlLogHan-dlerhandlers)andfinallythecleanupphasehappens.
Noticethatwhentheresponsehandlerisreadingtheinputdataitcanbefilteredthroughrequestinputfilters,whichareprecededbyconnectioninputfiltersifany.
Similarlythegeneratedresponseisfirstrunthroughrequestoutputfiltersandeventuallythroughconnectionoutputfiltersbeforeit'ssenttotheclient.
Wewilltalkaboutfiltersindetaillaterinthededicatedtofilterschapter.
BeforediscussingeachhandlerindetailrememberthatifyouusethestackedhandlersfeatureallhandlersinthechainwillberunaslongastheyreturnApache2::Const::OKorApache2::Const::DECLINED.
Becausestackedhandlersisaspecialcase.
Sodon'tbesurprisedifyou'vereturnedApache2::Const::OKandthenexthandlerwasstillexecuted.
Thisisafeature,notabug.
Nowlet'sdiscusseachofthementionedhandlersindetail.
1.
3.
1PerlPostReadRequestHandlerThepost_read_requestphaseisthefirstrequestphaseandhappensimmediatelyaftertherequesthasbeenreadandHTTPheaderswereparsed.
315Feb20141.
3.
1PerlPostReadRequestHandlerHTTPHandlersThisphaseisusuallyusedtodoprocessingthatmusthappenonceperrequest.
ForexampleApache2::ReloadisusuallyinvokedatthisphasetoreloadmodifiedPerlmodules.
ThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisSRV,becauseatthisphasetherequesthasnotyetbeenassociatedwithaparticularfilenameordirectory.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesNow,let'slookatanexample.
Considerthefollowingregistryscript:#file:touch.
plusestrict;usewarnings;useApache2::ServerUtil();useApache2::RequestIO();useFile::Spec::Functionsqw(catfile);my$r=shift;$r->content_type('text/plain');my$conf_file=catfileApache2::ServerUtil::server_root,"conf","httpd.
conf";printf"$conf_fileis%0.
2fminutesold\n",60*24*(-M$conf_file);Thisregistryscriptissupposedtoprintwhenthelasttimehttpd.
confhasbeenmodified,comparedtothestartoftherequestprocesstime.
Ifyourunthisscriptseveraltimesyoumightbesurprisedthatitreportsthesamevalueallthetime.
Unlesstherequesthappenstobeservedbyarecentlystartedchildprocesswhichwillthenreportadifferentvalue.
Butmostofthetimethevaluewon'tbereportedcorrectly.
Thishappensbecausethe-Moperatorreportsthedifferencebetweenfile'smodificationtimeandthevalueofaspecialPerlvariable$^T.
Whenwerunscriptsfromthecommandline,thisvariableisalwayssettothetimewhenthescriptgetsinvoked.
Undermod_perlthisvariableisgettingpresetoncewhenthechildprocessstartsanddoesn'tchangesincethen,soallrequestsseethesametime,whenoperatorslike-M,-Cand-Aareused.
Armedwiththisknowledge,inordertomakeourcodebehavesimilarlytothecommandlineprogramsweneedtoreset$^Ttotherequest'sstarttime,before-Misused.
Wecanchangethescriptitself,butwhatifweneedtodothesamechangeforseveralotherscriptsandhandlersAsimplePerlPostRead-15Feb201441.
3.
1PerlPostReadRequestHandlerRequestHandlerhandler,whichwillbeexecutedastheveryfirstthingofeachrequests,comeshandyhere:#file:MyApache2/TimeReset.
pmpackageMyApache2::TimeReset;usestrict;usewarnings;useApache2::RequestRec();useApache2::Const-compile=>'OK';subhandler{my$r=shift;$^T=$r->request_time;returnApache2::Const::OK;}1;Wecoulddo:$^T=time();Buttomakethingsmoreefficientweuse$r->request_timesincetherequestobject$ralreadystorestherequest'sstarttime,sowegetitwithoutperforminganadditionalsystemcall.
Toenableitjustaddtohttpd.
conf:PerlPostReadRequestHandlerMyApache2::TimeReseteithertotheglobalsection,ortothesectionifyouwantthishandlertoberunonlyforaspecificvirtualhost.
1.
3.
2PerlTransHandlerThetranslatephaseisusedtoperformthemanipulationofarequest'sURI.
Ifnocustomhandlerisprovided,theserver'sstandardtranslationrules(e.
g.
,Aliasdirectives,mod_rewrite,etc.
)willbeused.
APerlTransHandlerhandlercanalterthedefaulttranslationmechanismorcompletelyoverrideit.
ThisisalsoagoodplacetoregisternewhandlersforthefollowingphasesbasedontheURI.
PerlMap-ToStorageHandleristobeusedtooverridetheURItofilenametranslation.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisSRV,becauseatthisphasetherequesthasnotyetbeenassociatedwithaparticularfilenameordirectory.
Arguments515Feb20141.
3.
2PerlTransHandlerHTTPHandlersSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesTherearemanyusefulthingsthatcanbeperformedatthisstage.
Let'slookattheexamplehandlerthatrewritesrequestURIs,similartowhatmod_rewritedoes.
Forexample,ifyourweb-sitewasoriginallymadeofstaticpages,andnowyouhavemovedtoadynamicpagegenerationchancesarethatyoudon'twanttochangetheoldURIs,becauseyoudon'twanttobreaklinksforthosewholinktoyoursite.
IftheURI:http://example.
com/news/20021031/09/index.
htmlisnowhandledby:http://example.
com/perl/news.
pldate=20021031;id=09;page=index.
htmlthefollowinghandlercandotherewritingworktransparenttonews.
pl,soyoucanstillusetheformerURImapping:#file:MyApache2/RewriteURI.
pmpackageMyApache2::RewriteURI;usestrict;usewarnings;useApache2::RequestRec();useApache2::Const-compile=>qw(DECLINED);subhandler{my$r=shift;my($date,$id,$page)=$r->uri=~m|^/news/(\d+)/(\d+$r->uri("/perl/news.
pl");$r->args("date=$date;id=$id;page=$page");returnApache2::Const::DECLINED;}1;ThehandlermatchestheURIandassignsanewURIvia$r->uri()andthequerystringvia$r->args().
ItthenreturnsApache2::Const::DECLINED,sothenexttranslationhandlerwillgetinvoked,ifmorerewritesandtranslationsareneeded.
Ofcourseifyouneedtodoamorecomplicatedrewriting,thishandlercanbeeasilyadjustedtodoso.
15Feb201461.
3.
2PerlTransHandlerToconfigurethismodulesimplyaddtohttpd.
conf:PerlTransHandler+MyApache2::RewriteURI1.
3.
3PerlMapToStorageHandlerThemap_to_storagephaseisusedtoperformthetranslationofarequest'sURIintoacorrespondingfile-name.
Ifnocustomhandlerisprovided,theserverwilltrytowalkthefilesystemtryingtofindwhatfileordirectorycorrespondstotherequest'sURI.
Sinceusuallymod_perlhandlerdon'thavecorrespondingfilesonthefilesystem,youwillwanttoshortcutthisphaseandsavequiteafewCPUcycles.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisSRV,becauseatthisphasetherequesthasnotyetbeenassociatedwithaparticularfilenameordirectory.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesForexampleifyoudon'twantApachetotrytoattempttotranslateURIintoafilename,justaddahandler:PerlMapToStorageHandlerMyApache2::NoTranslationusingthefollowingcode:#file:MyApache2/NoTranslation.
pmpackageMyApache2::NoTranslation;usestrict;usewarningsFATAL=>'all';useApache2::Const-compile=>qw(OK);subhandler{my$r=shift;#skipap_directory_walkstat()callsreturnApache2::Const::OK;}1;715Feb20141.
3.
3PerlMapToStorageHandlerHTTPHandlersButthiscanbedonefromhttpd.
conftoo!
PerlMapToStorageHandlerApache2::Const::OKIfyouhaven'talreadycompiledApache2::Const::OKelsewhere,youshouldadd:useApache2::Const-compile=>qw(OK);ApachealsousesthisphasetohandleTRACErequests.
Soifyoushortcutit,TRACEcallswillbenothandled.
Incaseyouneedtohandlesuch,youmayrewriteitas:#file:MyApache2/NoTranslation2.
pmpackageMyApache2::NoTranslation2;usestrict;usewarningsFATAL=>'all';useApache2::RequestRec();useApache2::Const-compile=>qw(DECLINEDOKM_TRACE);subhandler{my$r=shift;returnApache2::Const::DECLINEDif$r->method_number==Apache2::Const::M_TRACE;#skipap_directory_walkstat()callsreturnApache2::Const::OK;}1;BTW,theHTTPTRACEmethodasksawebservertoechothecontentsoftherequestbacktotheclientfordebuggingpurposes.
i.
e.
,thecompleterequest,includingHTTPheaders,isreturnedintheentity-bodyofaTRACEresponse.
AttackersmayabuseHTTPTRACEfunctionalitytogainaccesstoinformationinHTTPheaderssuchascookiesandauthenticationdata.
Inthepresenceofothercross-domainvulnerabili-tiesinwebbrowsers,sensitiveheaderinformationcouldbereadfromanydomainsthatsupporttheHTTPTRACEmethod.
Anotherwaytopreventthecoretranslationistoset$r->filename()tosomevalue,whichcanalsobedoneinthePerlTransHandler,ifyouarealreadyusingit.
1.
3.
4PerlHeaderParserHandlerTheheader_parserphaseisthefirstphasetohappenaftertherequesthasbeenmappedtoits(oranequivalentcontainer).
Atthisphasethehandlercanexaminetherequestheadersandtotakeaspecialactionbasedonthese.
Forexamplethisphasecanbeusedtoblockevilclientstargetingcertainresources,whilelittleresourceswerewastedsofar.
15Feb201481.
3.
4PerlHeaderParserHandlerThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesThisphaseisverysimilartoPerlPostReadRequestHandler,withtheonlydifferencethatit'srunaftertherequesthasbeenmappedtotheresource.
Bothphasesareusefulfordoingsomethingonceperrequest,asearlyaspossible.
AndusuallyyoucantakeanyPerlPostReadRequestHandlerandturnitintoPerlHeaderParserHandlerbysimplychangingthedirectivenameinhttpd.
confandmovingitinsidethecontainerwhereitshouldbeexecuted.
Moreover,becauseofthissimilaritymod_perlprovidesaspecialdirectivePerlInitHandlerwhichiffoundoutsideresourcecontainersbehavesasPerlPostReadRequestHandler,otherwiseasPerlHeaderParserHandler.
YoualreadyknowthatApachehandlestheHEAD,GET,POSTandseveralotherHTTPmethods.
ButdidyouknowthatyoucaninventyourownHTTPmethodaslongasthereisaclientthatsupportsit.
Ifyouthinkofemails,theyareverysimilartoHTTPmessages:theyhaveasetofheadersandabody,sometimesamulti-partbody.
ThereforewecandevelopahandlerthatextendsHTTPbyaddingasupportfortheEMAILmethod.
WecanenablethisprotocolextensionandpushtherealcontenthandlerduringthePerlHeaderParserHandlerphase:PerlHeaderParserHandlerMyApache2::SendEmailandhereistheMyApache2::SendEmailhandler:#file:MyApache2/SendEmail.
pmpackageMyApache2::SendEmail;usestrict;usewarnings;useApache2::RequestRec();useApache2::RequestIO();useApache2::RequestUtil();useApache2::ServerUtil();useApache2::ServerRec();useApache2::Process();useAPR::Table();useApache2::Const-compile=>qw(DECLINEDOK);915Feb20141.
3.
4PerlHeaderParserHandlerHTTPHandlersuseconstantMETHOD=>'EMAIL';useconstantSMTP_HOSTNAME=>"localhost";subhandler{my$r=shift;returnApache2::Const::DECLINEDunless$r->methodeqMETHOD;$r->server->method_register(METHOD);$r->handler("perl-script");$r->push_handlers(PerlResponseHandler=>\&send_email_handler);returnApache2::Const::OK;}subsend_email_handler{my$r=shift;my%headers=map{$_=>$r->headers_in->get($_)}qw(ToFromSubject);my$content=content($r);my$status=send_email(\%headers,\$content);$r->content_type('text/plain');$r->print($status"ACK":"NACK");returnApache2::Const::OK;}subsend_email{my($rh_headers,$r_body)=@_;requireMIME::Lite;MIME::Lite->send("smtp",SMTP_HOSTNAME,Timeout=>60);my$msg=MIME::Lite->new(%$rh_headers,Data=>$$r_body);#warn$msg->as_string;$msg->send;}useAPR::Brigade();useAPR::Bucket();useApache2::Const-compile=>qw(MODE_READBYTES);useAPR::Const-compile=>qw(SUCCESSBLOCK_READ);useconstantIOBUFSIZE=>8192;subcontent{my$r=shift;my$bb=APR::Brigade->new($r->pool,$r->connection->bucket_alloc);my$data='';my$seen_eos=0;do{15Feb2014101.
3.
4PerlHeaderParserHandler$r->input_filters->get_brigade($bb,Apache2::Const::MODE_READBYTES,APR::Const::BLOCK_READ,IOBUFSIZE);for(my$b=$bb->first;$b;$b=$bb->next($b)){if($b->is_eos){$seen_eos++;last;}if($b->read(my$buf)){$data.
=$buf;}$b->remove;#optimizationtoreusememory}}while(!
$seen_eos);$bb->destroy;return$data;}1;Let'sgetthelessinterestingcodeoutoftheway.
Thefunctioncontent()grabstherequestbody.
Thefunc-tionsend_email()sendstheemailoverSMTP.
YoushouldadjusttheconstantSMTP_HOSTNAMEtopointtoyouroutgoingSMTPserver.
Youcanreplacethisfunctionwithyourownifyouprefertouseadifferentmethodtosendemail.
Nowtothemoreinterestingfunctions.
Thefunctionhandler()returnsimmediatelyandpassesthecontroltothenexthandleriftherequestmethodisnotequaltoEMAIL(setintheMETHODconstant):returnApache2::Const::DECLINEDunless$r->methodeqMETHOD;NextittellsApachethatthisnewmethodisavalidoneandthattheperl-scripthandlerwilldotheprocessing.
$r->server->method_register(METHOD);$r->handler("perl-script");Finallyitpushesthefunctionsend_email_handler()tothePerlResponseHandlerlistofhandlers:$r->push_handlers(PerlResponseHandler=>\&send_email_handler);Thefunctionterminatestheheader_parserphaseby:returnApache2::Const::OK;1115Feb20141.
3.
4PerlHeaderParserHandlerHTTPHandlersAllotherphasesrunasusual,soyoucanreuseanyHTTPprotocolhooks,suchasauthenticationandfixupphases.
Whentheresponsephasestartssend_email_handler()isinvoked,assumingthatnootherresponsehandlerswereinsertedbeforeit.
Theresponsehandlerconsistsofthreeparts.
RetrievetheemailheadersTo,FromandSubject,andthebodyofthemessage:my%headers=map{$_=>$r->headers_in->get($_)}qw(ToFromSubject);my$content=$r->content;Thensendtheemail:my$status=send_email(\%headers,\$content);FinallyreturntotheclientasimpleresponseacknowledgingthatemailhasbeensentandfinishtheresponsephasebyreturningApache2::Const::OK:$r->content_type('text/plain');$r->print($status"ACK":"NACK");returnApache2::Const::OK;Ofcourseyouwillwanttoaddextravalidationsifyouwanttousethiscodeinproduction.
Thisisjustaproofofconceptimplementation.
AsalreadymentionedwhenyouextendanHTTPprotocolyouneedtohaveaclientthatknowshowtousetheextension.
SohereisasimpleclientthatusesLWP::UserAgenttoissueanEMAILmethodrequestoverHTTPprotocol:#file:send_http_email.
pl#!
/usr/bin/perlusestrict;usewarnings;requireLWP::UserAgent;my$url="http://localhost:8000/email/";my%headers=(From=>'example@example.
com',To=>'example@example.
com',Subject=>'3weeksinTibet',);my$content=new(%headers);my$req=HTTP::Request->new("EMAIL",$url,$headers,$content);my$res=LWP::UserAgent->new->request($req);print$res->is_success$res->content:"failed";mostofthecodeisjustacustomdata.
Thecodethatdoessomethingconsistsoffourlinesattheveryend.
CreateHTTP::HeadersandHTTP::Requestobject.
Issuetherequestandgettheresponse.
Finallyprinttheresponse'scontentifitwassuccessfulorjust"failed"ifnot.
Nowsavetheclientcodeinthefilesend_http_email.
pl,adjusttheTofield,makethefileexecutableandexecuteit,afteryouhaverestartedtheserver.
YoushouldreceiveanemailshortlytotheaddresssetintheTofield.
1.
3.
5PerlInitHandlerWhenconfiguredinsideanycontainerdirective,except,thishandlerisanaliasforPerlHeaderParserHandlerdescribedearlier.
OtherwiseitactsasanaliasforPerlPostRead-RequestHandlerdescribedearlier.
Itisthefirsthandlertobeinvokedwhenservingarequest.
ThisphaseisoftypeRUN_ALL.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesThebestexampleherewouldbetouseApache2::Reloadwhichtakesthebenefitofthisdirective.
UsuallyApache2::Reloadisconfiguredas:PerlInitHandlerApache2::ReloadPerlSetVarReloadAllOffPerlSetVarReloadModules"MyApache2::*"whichduringthecurrentHTTPrequestwillmonitorandreloadallMyApache2::*modulesthathavebeenmodifiedsincethelastHTTPrequest.
Howeverifwemovetheglobalconfigurationintoacontainer:1315Feb20141.
3.
5PerlInitHandlerHTTPHandlersPerlInitHandlerApache2::ReloadPerlSetVarReloadAllOffPerlSetVarReloadModules"MyApache2::*"SetHandlerperl-scriptPerlResponseHandlerModPerl::RegistryOptions+ExecCGIApache2::Reloadwillreloadthemodifiedmodules,onlywhenarequesttothe/develnamespaceisissued,becausePerlInitHandlerplaystheroleofPerlHeaderParserHandlerhere.
1.
3.
6PerlAccessHandlerTheaccess_checkerphaseisthefirstofthreehandlersthatareinvolvedinwhat'sknownasAAA:Authentication,Authorization,andAccesscontrol.
ThisphasecanbeusedtorestrictaccessfromacertainIPaddress,timeofthedayoranyotherrulenotconnectedtotheuser'sidentity.
ThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesTheconceptbehindaccesscheckerhandlerisverysimple,returnApache2::Const::FORBIDDENiftheaccessisnotallowed,otherwisereturnApache2::Const::OK.
ThefollowingexamplehandlerdeniesrequestsmadefromIPsontheblacklist.
#file:MyApache2/BlockByIP.
pmpackageMyApache2::BlockByIP;usestrict;usewarnings;useApache2::RequestRec();useApache2::Connection();useApache2::Const-compile=>qw(FORBIDDENOK);my%bad_ips=map{$_=>1}qw(127.
0.
0.
110.
0.
0.
4);15Feb2014141.
3.
6PerlAccessHandlersubhandler{my$r=shift;returnexists$bad_ips{$r->connection->remote_ip}Apache2::Const::FORBIDDEN:Apache2::Const::OK;}1;Thehandlerretrievestheconnection'sIPaddress,looksitupinthehashofblacklistedIPsandforbidstheaccessiffound.
IftheIPisnotblacklisted,thehandlerreturnscontroltothenextaccesscheckerhandler,whichmaystillblocktheaccessbasedonadifferentrule.
Toenablethehandlersimplyaddittothecontainerthatneedstobeprotected.
Forexampletoprotectanaccesstotheregistryscriptsexecutedfromthebaselocation/perladd:SetHandlerperl-scriptPerlResponseHandlerModPerl::RegistryPerlAccessHandlerMyApache2::BlockByIPOptions+ExecCGIIt'simportanttonoticethatPerlAccessHandlercanbeconfiguredforanysubsectionofthesite,nomatterwhetherit'sservedbyamod_perlresponsehandlerornot.
Forexampletorunthehandlerfromourexampleforallrequeststotheserversimplyaddtohttpd.
conf:PerlAccessHandlerMyApache2::BlockByIP1.
3.
7PerlAuthenHandlerThecheck_user_id(authen)phaseiscalledwhenevertherequestedfileordirectoryispasswordprotected.
This,inturn,requiresthatthedirectorybeassociatedwithAuthName,AuthTypeandatleastonerequiredirective.
Thisphaseisusuallyusedtoverifyauser'sidentificationcredentials.
Ifthecredentialsareverifiedtobecorrect,thehandlershouldreturnApache2::Const::OK.
OtherwisethehandlerreturnsApache2::Const::HTTP_UNAUTHORIZEDtoindicatethattheuserhasnotauthenticatedsuccess-fully.
WhenApachesendstheHTTPheaderwiththiscode,thebrowserwillnormallypopupadialogboxthatpromptstheuserforlogininformation.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisDIR.
1515Feb20141.
3.
7PerlAuthenHandlerHTTPHandlersArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesThefollowinghandlerauthenticatesusersbyaskingforausernameandapasswordandletstheminonlyifthelengthofastringmadefromthesuppliedusernameandpasswordandasinglespaceequalstothesecretlength,specifiedbytheconstantSECRET_LENGTH.
#file:MyApache2/SecretLengthAuth.
pmpackageMyApache2::SecretLengthAuth;usestrict;usewarnings;useApache2::Access();useApache2::RequestUtil();useApache2::Const-compile=>qw(OKDECLINEDHTTP_UNAUTHORIZED);useconstantSECRET_LENGTH=>14;subhandler{my$r=shift;my($status,$password)=$r->get_basic_auth_pw;return$statusunless$status==Apache2::Const::OK;returnApache2::Const::OKifSECRET_LENGTH==lengthjoin"",$r->user,$password;$r->note_basic_auth_failure;returnApache2::Const::HTTP_UNAUTHORIZED;}1;Firstthehandlerretrievesthestatusoftheauthenticationandthepasswordinplaintext.
ThestatuswillbesettoApache2::Const::OKonlywhentheuserhassuppliedtheusernameandthepasswordcreden-tials.
Ifthestatusisdifferent,wejustletApachehandlethissituationforus,whichwillusuallychallengetheclientsoit'llsupplythecredentials.
Notethatget_basic_auth_pw()doesafewthingsbehindthescenes,whichareimportanttounder-standifyouplanonimplementingyourownauthenticationmechanismthatdoesnotuseget_basic_auth_pw().
First,ischecksthevalueoftheconfiguredAuthTypefortherequest,makingsureitisBasic.
ThenitmakessurethattheAuthorization(orProxy-Authorization)headerisformattedforBasicauthentication.
Finally,afterisolatingtheuserandpasswordfromtheheader,it15Feb2014161.
3.
7PerlAuthenHandlerpopulatestheap_auth_typeslotintherequestrecordwithBasic.
Forthefirstandlastpartsofthisprocess,mod_perloffersanAPI.
$r->auth_typereturnstheconfiguredauthenticationtypeforthecurrentrequest-whateverwassetviatheAuthTypeconfigurationdirective.
$r->ap_auth_typepopulatestheap_auth_typeslotintherequestrecord,whichshouldbedoneafterithasbeenconfirmedthattherequestisindeedusingBasicauthentication.
(Note:$r->ap_auth_typewas$r->connection->auth_typeinthemod_perl1.
0API.
)Onceweknowthatwehavetheusernameandthepasswordsuppliedbytheclient,wecanproceedwiththeauthentication.
Ourauthenticationalgorithmisunusual.
Insteadofvalidatingtheusername/passwordpairagainstapasswordfile,wesimplycheckthatthestringbuiltfromthesetwoitemsplusasinglespaceisSECRET_LENGTHlong(14inourexample).
Soforexamplethepairmod_perl/rulesauthenticatescorrectly,whereassecret/passworddoesnot,becausethelatterpairwillmakeastringof15characters.
Ofcoursethisisnotastrongauthenticationschemeandyoushouldn'tuseitforseriousthings,butit'sfuntoplaywith.
Mostauthenticationvalidationssimplyverifytheusername/passwordagainstadatabaseofvalidpairs,usuallythisrequiresthepasswordtobeencryptedfirst,sincestoringpasswordsinclearisabadidea.
Finallyifourauthenticationfailsthehandlercallsnote_basic_auth_failure()andreturnsApache2::Const::HTTP_UNAUTHORIZED,whichsetstheproperHTTPresponseheadersthattelltheclientthatitsuserthattheauthenticationhasfailedandthecredentialsshouldbesuppliedagain.
It'snotenoughtoenablethishandlerfortheauthenticationtowork.
YouhavetotellApachewhatauthen-ticationschemetouse(BasicorDigest),whichisspecifiedbytheAuthTypedirective,andyoushouldalsosupplytheAuthName--theauthenticationrealm,whichisreallyjustastringthattheclientusuallyusesasatitleinthepop-upbox,wheretheusernameandthepasswordareinserted.
FinallytheRequiredirectiveisneededtospecifywhichusernamesareallowedtoauthenticate.
Ifyousetittovalid-useranyusernamewilldo.
Hereisthewholeconfigurationsectionthatrequiresuserstoauthenticatebeforetheyareallowedtoruntheregistryscriptsfrom/perl/:SetHandlerperl-scriptPerlResponseHandlerModPerl::RegistryPerlAuthenHandlerMyApache2::SecretLengthAuthOptions+ExecCGIAuthTypeBasicAuthName"TheGate"Requirevalid-userJustlikePerlAccessHandlerandothermod_perlhandlers,PerlAuthenHandlercanbeconfig-uredforanysubsectionofthesite,nomatterwhetherit'sservedbyamod_perlresponsehandlerornot.
Forexampletousetheauthenticationhandlerfromthelastexampleforanyrequeststothesite,simplyuse:1715Feb20141.
3.
7PerlAuthenHandlerHTTPHandlersPerlAuthenHandlerMyApache2::SecretLengthAuthAuthTypeBasicAuthName"TheGate"Requirevalid-user1.
3.
8PerlAuthzHandlerTheauth_checker(authz)phaseisusedforauthorizationcontrol.
Thisphaserequiresasuccessfulauthen-ticationfromthepreviousphase,becauseausernameisneededinordertodecidewhetherauserisautho-rizedtoaccesstherequestedresource.
Asthisphaseistightlyconnectedtotheauthenticationphase,thehandlersregisteredforthisphaseareonlycalledwhentherequestedresourceispasswordprotected,similartotheauthphase.
ThehandlerisexpectedtoreturnApache2::Const::DECLINEDtodeferthedecision,Apache2::Const::OKtoindicateitsacceptanceoftheuser'sauthorization,orApache2::Const::HTTP_UNAUTHORIZEDtoindicatethattheuserisnotauthorizedtoaccesstherequesteddocument.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesHereistheMyApache2::SecretResourceAuthzhandlerwhichgrantsaccesstocertainresourcesonlytocertainuserswhohavealreadyproperlyauthenticated:#file:MyApache2/SecretResourceAuthz.
pmpackageMyApache2::SecretResourceAuthz;usestrict;usewarnings;useApache2::Access();useApache2::RequestUtil();useApache2::Const-compile=>qw(OKHTTP_UNAUTHORIZED);my%protected=('admin'=>['stas'],'report'=>[qw(stasboss)],);15Feb2014181.
3.
8PerlAuthzHandlersubhandler{my$r=shift;my$user=$r->user;if($user){my($section)=$r->uri=~m|^/company/(\w+)/|;if(defined$section&&exists$protected{$section}){my$users=$protected{$section};returnApache2::Const::OKifgrep{$_eq$user}@$users;}else{returnApache2::Const::OK;}}$r->note_basic_auth_failure;returnApache2::Const::HTTP_UNAUTHORIZED;}1;Thisauthorizationhandlerisverysimilartotheauthenticationhandlerfromtheprevioussection.
Herewerelyonthepreviousphasetogetusersauthenticated,andnowaswehavetheusernamewecanmakedeci-sionswhethertolettheuseraccesstheresourceithasaskedforornot.
Inourexamplewehaveasimplehashwhichmapswhichusersareallowedtoaccesswhatresources.
Soforexampleanythingunder/company/admin/canbeaccessedonlybytheuserstas,/company/report/canbeaccessedbyusersstasandboss,whereasanyotherresourcesunder/company/canbeaccessedbyeverybodywhohasreachedsofar.
Ifforsomereasonwedon'tgettheusername,weortheuserisnotauthorizedtoaccesstheresourcethehandlerdoesthesamethingasitdoeswhentheauthenticationfails,i.
e,calls:$r->note_basic_auth_failure;returnApache2::Const::HTTP_UNAUTHORIZED;Theconfigurationissimilartotheoneintheprevioussection,thistimewejustaddthePerlAu-thzHandlersetting.
Therestdoesn'tchange.
Alias/company//home/httpd/httpd-2.
0/perl/SetHandlerperl-scriptPerlResponseHandlerModPerl::RegistryPerlAuthenHandlerMyApache2::SecretLengthAuthPerlAuthzHandlerMyApache2::SecretResourceAuthzOptions+ExecCGIAuthTypeBasicAuthName"TheSecretGate"Requirevalid-userAndifyouwanttoruntheauthenticationandauthorizationforthewholesite,simplyadd:1915Feb20141.
3.
8PerlAuthzHandlerHTTPHandlersPerlAuthenHandlerMyApache2::SecretLengthAuthPerlAuthzHandlerMyApache2::SecretResourceAuthzAuthTypeBasicAuthName"TheSecretGate"Requirevalid-user1.
3.
9PerlTypeHandlerThetype_checkerphaseisusedtosettheresponseMIMEtype(Content-type)andsometimesotherbitsofdocumenttypeinformationlikethedocumentlanguage.
Forexamplemod_autoindex,whichperformsautomaticdirectoryindexing,usesthisphasetomapthefilenameextensionstothecorrespondingiconswhichwillbelaterusedinthelistingoffiles.
Ofcourselaterphasesmayoverridethemimetypesetinthisphase.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesThemostimportantthingtorememberwhenoverridingthedefaulttype_checkerhandler,whichisusuallythemod_mimehandler,isthatyouhavetosetthehandlerthatwilltakecareoftheresponsephaseandtheresponsecallbackfunctionorthecodewon'twork.
mod_mimedoesthatbasedonSetHandlerandAddHandlerdirectives,andfileextensions.
Soifyouwantthecontenthandlertoberunbymod_perl,seteither:$r->handler('perl-script');$r->set_handlers(PerlResponseHandler=>\&handler);or:$r->handler('modperl');$r->set_handlers(PerlResponseHandler=>\&handler);dependingonwhichtypeofresponsehandleriswanted.
15Feb2014201.
3.
9PerlTypeHandlerWritingaPerlTypeHandlerhandlerwhichsetsthecontent-typevalueandreturnsApache2::Const::DECLINEDsothatthedefaulthandlerwilldotherestofthework,isnotagoodidea,becausemod_mimewillprobablyoverridethisandothersettings.
Thereforeit'stheeasiesttoleavethisstagealoneanddoanydesiredsettingsinthefixupsphase.
1.
3.
10PerlFixupHandlerThefixupsphaseishappeningjustbeforethecontenthandlingphase.
Itgivesthelastchancetodothingsbeforetheresponseisgenerated.
Forexampleinthisphasemod_envpopulatestheenvironmentwithvariablesconfiguredwithSetEnvandPassEnvdirectives.
ThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesThefollowingfixuphandlerexampletellsApacheatruntimewhichhandlerandcallbackshouldbeusedtoprocesstherequestbasedonthefileextensionoftherequest'sURI.
#file:MyApache2/FileExtDispatch.
pmpackageMyApache2::FileExtDispatch;usestrict;usewarnings;useApache2::RequestIO();useApache2::RequestRec();useApache2::RequestUtil();useApache2::Const-compile=>'OK';useconstantHANDLER=>0;useconstantCALLBACK=>1;my%exts=(cgi=>['perl-script',\&cgi_handler],pl=>['modperl',\&pl_handler],tt=>['perl-script',\&tt_handler],txt=>['default-handler',undef],);2115Feb20141.
3.
10PerlFixupHandlerHTTPHandlerssubhandler{my$r=shift;my($ext)=$r->uri=~/\.
(\w+)$/;$ext='txt'unlessdefined$extandexists$exts{$ext};$r->handler($exts{$ext}->[HANDLER]);if(defined$exts{$ext}->[CALLBACK]){$r->set_handlers(PerlResponseHandler=>$exts{$ext}->[CALLBACK]);}returnApache2::Const::OK;}subcgi_handler{content_handler($_[0],'cgi')}subpl_handler{content_handler($_[0],'pl')}subtt_handler{content_handler($_[0],'tt')}subcontent_handler{my($r,$type)=@_;$r->content_type('text/plain');$r->print("Ahandleroftype'$type'wascalled");returnApache2::Const::OK;}1;Intheexamplewehaveusedthefollowingmapping.
my%exts=(cgi=>['perl-script',\&cgi_handler],pl=>['modperl',\&pl_handler],tt=>['perl-script',\&tt_handler],txt=>['default-handler',undef],);Sothat.
cgirequestswillbehandledbytheperl-scripthandlerandthecgi_handler()callback,.
plrequestsbymodperlandpl_handler(),.
tt(templatetoolkit)byperl-scriptandthett_handler(),finally.
txtrequestbythedefault-handlerhandler,whichrequiresnocallback.
Moreoverthehandlerassumesthatiftherequest'sURIhasnofileextensionoritdoes,butit'snotinitsmapping,thedefault-handlerwillbeused,asifthetxtextensionwasused.
Afterdoingthemapping,thehandlerassignsthehandler:$r->handler($exts{$ext}->[HANDLER]);andthecallbackifneeded:15Feb2014221.
3.
10PerlFixupHandlerif(defined$exts{$ext}->[CALLBACK]){$r->set_handlers(PerlResponseHandler=>$exts{$ext}->[CALLBACK]);}Inthissimpleexamplethecallbackfunctionsdon'tdomuchbutcallingthesamecontenthandlerwhichsimplyprintsthenameoftheextensionifhandledbymod_perl,otherwiseApachewillservetheotherfilesusingthedefaulthandler.
Inrealworldyouwillusecallbackstorealcontenthandlersthatdorealthings.
Hereishowthishandlerisconfigured:Alias/dispatch//home/httpd/httpd-2.
0/htdocs/PerlFixupHandlerMyApache2::FileExtDispatchNoticethatthereisnoneedtospecifyanything,butthefixuphandler.
Itappliestherestofthesettingsdynamicallyatrun-time.
1.
3.
11PerlResponseHandlerThehandler(response)phaseisusedforgeneratingtheresponse.
ThisisarguablythemostimportantphaseandmostoftheexistingApachemodulesdomostoftheirworkatthisphase.
Thisistheonlyphasethatrequirestwodirectivesundermod_perl.
Forexample:SetHandlerperl-scriptPerlResponseHandlerMyApache2::WorldDominationSetHandlersettoperl-scriptormodperltellsApachethatmod_perlisgoingtohandletheresponsegeneration.
PerlResponseHandlertellsmod_perlwhichcallbackisgoingtodothejob.
ThisphaseisoftypeRUN_FIRST.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
Examples2315Feb20141.
3.
11PerlResponseHandlerHTTPHandlersMostoftheApache::modulesonCPANaredealingwiththisphase.
Infactmostofthedevelopersspendthemajorityoftheirtimeworkingonhandlersthatgenerateresponsecontent.
Let'swriteasimpleresponsehandler,thatjustgeneratessomecontent.
Thistimelet'sdosomethingmoreinterestingthanprinting"Helloworld".
Let'swriteahandlerthatprintsitself:#file:MyApache2/Deparse.
pmpackageMyApache2::Deparse;usestrict;usewarnings;useApache2::RequestRec();useApache2::RequestIO();useB::Deparse();useApache2::Const-compile=>'OK';subhandler{my$r=shift;$r->content_type('text/plain');$r->print('subhandler',B::Deparse->new->coderef2text(\&handler));returnApache2::Const::OK;}1;Toenablethishandleraddtohttpd.
conf:SetHandlermodperlPerlResponseHandlerMyApache2::DeparseNowwhentheserverisrestartedandweissuearequesttohttp://localhost/deparsewegetthefollowingresponse:subhandler{packageMyApache2::Deparse;usewarnings;usestrict'refs';my$r=shift@_;$r->content_type('text/plain');$r->print('subhandler','B::Deparse'->new->coderef2text(\&handler));return0;}Ifyoucompareittothesourcecode,it'sprettymuchthesamecode.
B::Deparseisfuntoplaywith!
15Feb2014241.
3.
11PerlResponseHandler1.
3.
12PerlLogHandlerThelog_transactionphasehappensnomatterhowthepreviousphaseshaveendedup.
Ifoneoftheearlierphaseshasabortedarequest,e.
g.
,failedauthenticationor404(filenotfound)errors,therestofthephasesuptoandincludingtheresponsephasesareskipped.
Butthisphaseisalwaysexecuted.
Bythisphasealltheinformationabouttherequestandtheresponseisknown,thereforethelogginghandlersusuallyrecordthisinformationinvariousways(e.
g.
,loggingtoaflatfileoradatabase).
ThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesImagineasituationwhereyouhavetologrequestsintoindividualfiles,oneperuser.
Assumingthatallrequestsstartwith/~username/,soit'seasytocategorizerequestsbytheusername.
Hereistheloghandlerthatdoesthat:#file:MyApache2/LogPerUser.
pmpackageMyApache2::LogPerUser;usestrict;usewarnings;useApache2::RequestRec();useApache2::Connection();useFcntlqw(:flock);useFile::Spec::Functionsqw(catfile);useApache2::Const-compile=>qw(OKDECLINED);subhandler{my$r=shift;my($username)=$r->uri=~m|returnApache2::Const::DECLINEDunlessdefined$username;my$entry=sprintfqq(%s[%s]"%s"%d%d\n),$r->connection->remote_ip,scalar(localtime),$r->uri,$r->status,$r->bytes_sent;my$log_path=catfileApache2::ServerUtil::server_root,2515Feb20141.
3.
12PerlLogHandlerHTTPHandlers"logs","$username.
log";openmy$fh,">>$log_path"ordie"can'topen$log_path:$!
";flock$fh,LOCK_EX;print$fh$entry;close$fh;returnApache2::Const::OK;}1;Firstthehandlertriestofigureoutwhatusernametherequestisissuedfor,ifitfailstomatchtheURI,itsimplyreturnsApache2::Const::DECLINED,lettingotherloghandlerstodothelogging.
ThoughitcouldreturnApache2::Const::OKsinceallotherloghandlerswillberunanyway.
Nextitbuildsthelogentry,similartothedefaultaccess_logentry.
It'scomprisedofremoteIP,thecurrenttime,theuri,thereturnstatusandhowmanybytesweresenttotheclientasaresponsebody.
Finallythehandlerappendsthisentrytothelogfilefortheusertherequestwasissuedfor.
Usuallyit'ssafetoappendshortstringstothefilewithoutbeingafraidofmessingupthefile,whentwofilesattempttowriteatthesametime,butjusttobeonthesafesidethehandlerexclusivelylocksthefilebeforeperformingthewriting.
ToconfigurethehandlersimplyenablethemodulewiththePerlLogHandlerdirective,forthedesiredURInamespace(startingwith:/~inourexample):SetHandlerperl-scriptPerlResponseHandlerModPerl::RegistryPerlLogHandlerMyApache2::LogPerUserOptions+ExecCGIAfterrestartingtheserverandissuingrequeststothefollowingURIs:http://localhost/~stas/test.
plhttp://localhost/~eric/test.
plhttp://localhost/~stas/date.
plTheMyApache2::LogPerUserhandlerwillappendtologs/stas.
log:127.
0.
0.
1[SatAug3101:50:382002]"/~stas/test.
pl"2008127.
0.
0.
1[SatAug3101:50:402002]"/~stas/date.
pl"20044andtologs/eric.
log:127.
0.
0.
1[SatAug3101:50:392002]"/~eric/test.
pl"2008It'simportanttonoticethatPerlLogHandlercanbeconfiguredforanysubsectionofthesite,nomatterwhetherit'sservedbyamod_perlresponsehandlerornot.
Forexampletorunthehandlerfromourexampleforallrequeststotheserver,simplyaddtohttpd.
conf:15Feb2014261.
3.
12PerlLogHandlerPerlLogHandlerMyApache2::LogPerUserSincethePerlLogHandlerphaseisoftypeRUN_ALL,allotherlogginghandlerswillbecalledaswell.
1.
3.
13PerlCleanupHandlerThereisnocleanupApachephase,itexistsonlyinsidemod_perl.
Itisusedtoexecutesomecodeimmedi-atelyaftertherequesthasbeenserved(theclientwentaway)andbeforetherequestobjectisdestroyed.
Thereareseveralusagesforthisusephase.
Theobviousoneistorunacleanupcode,forexampleremov-ingtemporarilycreatedfiles.
ThelessobviousistousethisphaseinsteadofPerlLogHandleriftheloggingoperationistimeconsuming.
Thisapproachallowstofreetheclientassoonastheresponseissent.
ThisphaseisoftypeRUN_ALL.
Thehandler'sconfigurationscopeisDIR.
ArgumentsSeetheHTTPRequestHandlerSkeletonforadescriptionofhandlerarguments.
ReturnSeeStackedHandlersforadescriptionofhandlerreturncodes.
ExamplesTherearetwowaystoregisterandruncleanuphandlers:1.
UsingthePerlCleanupHandlerphasePerlCleanupHandlerMyApache2::Cleanupor:$r->push_handlers(PerlCleanupHandler=>\&cleanup);Thismethodisidenticaltoallotherhandlers.
Inthistechniquethecleanup()callbackaccepts$rasitsonlyargument.
2.
Usingcleanup_register()actingontherequestobject'spoolSincearequestobjectpoolisdestroyedattheendofeachrequest,wecanusecleanup_regis-tertoregisteracleanupcallbackwhichwillbeexecutedjustbeforethepoolisdestroyed.
Forexample:2715Feb20141.
3.
13PerlCleanupHandlerHTTPHandlers$r->pool->cleanup_register(\&cleanup,$arg);TheimportantdifferencefromusingthePerlCleanupHandlerhandler,isthathereyoucanpassanoptionalarbitraryargumenttothecallbackfunction,andno$rargumentispassedbydefault.
Thereforeifyouneedtopassanydataotherthan$ryoumaywanttousethistechnique.
Hereisanexamplewherethecleanuphandlerisusedtodeleteatemporaryfile.
Theresponsehandlerisrunningls-landstorestheoutputintemporaryfile,whichisthenusedby$r->sendfiletosendthefile'scontents.
Weusepush_handlers()topushPerlCleanupHandlertounlinkthefileattheendoftherequest.
#file:MyApache2/Cleanup1.
pmpackageMyApache2::Cleanup1;usestrict;usewarningsFATAL=>'all';useFile::Spec::Functionsqw(catfile);useApache2::RequestRec();useApache2::RequestIO();useApache2::RequestUtil();useApache2::Const-compile=>qw(OKDECLINED);useAPR::Const-compile=>'SUCCESS';my$file=catfile"/tmp","data";subhandler{my$r=shift;$r->content_type('text/plain');local@ENV{qw(PATHBASH_ENV)};qx(/bin/ls-l>$file);my$status=$r->sendfile($file);die"sendfilehasfailed"unless$status==APR::Const::SUCCESS;$r->push_handlers(PerlCleanupHandler=>\&cleanup);returnApache2::Const::OK;}subcleanup{my$r=shift;die"Can'tfindfile:$file"unless-e$file;unlink$fileordie"failedtounlink$file";returnApache2::Const::OK;}1;15Feb2014281.
3.
13PerlCleanupHandlerNextweaddthefollowingconfiguration:SetHandlermodperlPerlResponseHandlerMyApache2::Cleanup1Nowwhenarequestto/cleanup1ismade,thecontentsofthecurrentdirectorywillbeprintedandoncetherequestisoverthetemporaryfileisdeleted.
Thisresponsehandlerhasaproblemofrunninginamulti-processenvironment,sinceitusesthesamefile,andseveralprocessesmaytrytoread/write/deletethatfileatthesametime,wreckinghavoc.
Wecouldhaveappendedtheprocessid$$tothefile'sname,butrememberthatmod_perl2.
0codemayruninthethreadedenvironment,meaningthattherewillbemanythreadsrunninginthesameprocessandthe$$trickwon'tworkanylonger.
Thereforeonereallyhastousethiscodetocreateunique,butpredictable,filenamesacrossthreadsandprocesses:subunique_id{requireApache2::MPM;requireAPR::OS;returnApache2::MPM->is_threadedAPR::OS::current_thread_id()}:$$;}InthethreadedenvironmentitwillreturnastringcontainingtheprocessID,followedbyathreadID.
Inthenon-threadedenvironmentonlytheprocessIDwillbereturned.
Howeversinceitgivesusapredictablestring,theymaystillbeanon-satisfactorysolution.
Thereforeweneedtousearandomstring.
WecaneithereitherPerl'srand,someCPANmoduleortheAPR'sAPR::UUID:subunique_id{requireAPR::UUID;returnAPR::UUID->new->format;}NowtheproblemishowdowetellthecleanuphandlerwhatfileshouldbecleanedupWecouldhavestoreditinthe$r->notestableintheresponsehandlerandthenretrieveitinthecleanuphandler.
Howeverthereisabetterway-asmentionedearlier,wecanregisteracallbackforrequestpoolcleanup,andwhenusingthismethodwecanpassanarbitraryargumenttoit.
Thereforeinourcasewechoosetopassthefilename,basedonrandomstring.
Hereisabetterversionoftheresponseandcleanuphandlers,thatusesthistechnique:#file:MyApache2/Cleanup2.
pmpackageMyApache2::Cleanup2;usestrict;usewarningsFATAL=>'all';useFile::Spec::Functionsqw(catfile);useApache2::RequestRec();useApache2::RequestIO();2915Feb20141.
3.
13PerlCleanupHandlerHTTPHandlersuseApache2::RequestUtil();useAPR::UUID();useAPR::Pool();useApache2::Const-compile=>qw(OKDECLINED);useAPR::Const-compile=>'SUCCESS';my$file_base=catfile"/tmp","data-";subhandler{my$r=shift;$r->content_type('text/plain');my$file=$file_base.
APR::UUID->new->format;local@ENV{qw(PATHBASH_ENV)};qx(/bin/ls-l>$file);my$status=$r->sendfile($file);die"sendfilehasfailed"unless$status==APR::Const::SUCCESS;$r->pool->cleanup_register(\&cleanup,$file);returnApache2::Const::OK;}subcleanup{my$file=shift;die"Can'tfindfile:$file"unless-e$file;unlink$fileordie"failedtounlink$file";returnApache2::Const::OK;}1;Similarlytothefirsthandler,weaddtheconfiguration:SetHandlermodperlPerlResponseHandlerMyApache2::Cleanup2Andnowwhenrequesting/cleanup2westillgetthesameoutput--thelistingofthecurrentdirectory--butthistimethiscodewillworkcorrectlyinthemulti-processes/multi-threadedenvironmentandtempo-raryfilesgetcleanedupaswell.
1.
3.
13.
1PossibleCaveatsPerlCleanupHandlermayfailtobecompletedonservershutdown/gracefulrestartsinceApachewillkilltheregisteredhandlersviaSIGTERM,beforetheyhadachancetorunoreveninthemiddleofitsexecution.
See:http://marc.
theaimsgroup.
com/t=106387845200003&r=1&w=2http://marc.
theaims-group.
com/l=apache-modperl-dev&m=106427616108596&w=215Feb2014301.
3.
13PerlCleanupHandler1.
4MiscellaneousIssues1.
4.
1HandlingHEADRequestsInordertoavoidtheoverheadofsendingthedatatotheclientwhentherequestisoftypeHEADinmod_perl1.
0weusedtoreturnearlyfromthehandler:returnApache2::Const::OKif$r->header_only;Thislogicshouldnotbeusedinmod_perl2.
0,becauseApache2.
0automaticallydiscardstheresponsebodyforHEADrequests.
Itexpectsthefullbodytogeneratethecorrectsetofresponseheaders,ifyoudon'tsendthebodyyoumayencounterproblems.
(Youcanalsoreadthecommentinforap_http_header_filter()inmodules/http/http_protocol.
cintheApache2.
0source.
)1.
4.
2Content-LengthResponseHeaderYoumayencountersomeissueswiththeC-L(Content-Length)header.
Someofthemarediscussedhere.
ThespecialcaseofContent-Length:0SinceApacheproclaimsitselfgovernoroftheC-LheaderviatheC-Lfilter(ap_content_length_filterathttpd-2.
0/server/protocol.
c),forthemostpartGETandHEADbehaveexactlythesame.
However,whenApacheseesaHEADrequestwithaC-LheaderofzeroittakesspecialactionandremovestheC-Lheader.
Thisisdonetoprotectagainsthandlersthatcalled$r->header_only(whichwasokin1.
3butisnotin2.
0).
Therefore,GETandHEADbehaveidentically,exceptwhenthecontenthandler(and/orfilters)endupsendingnocontent.
Formoredetailsrefertothelengthycommentsinap_http_header_filter()inhttpd-2.
0/modules/http/http_protocol.
c).
FormorediscussiononwhyitisimportanttogetHEADrequestsright,seethesethreadsfromthemod_perllist:http://marc.
theaimsgroup.
com/l=apache-modperl&m=108647669726915&w=2http://marc.
theaimsgroup.
com/t=109122984600001&r=1&w=2aswellasthisbugreportfrommozilla,whichshowshowHEADrequestsareusedinthewild:http://bugzilla.
mozilla.
org/show_bug.
cgiid=245447NotgettingContent-LengthheaderwithHEADrequestsEventhoughthespecsaysthatcontenthandlersshouldsendanidenticalresponseforGETandHEADrequests,somefolkstrytoavoidtheoverheadofgeneratingtheresponsebody,whichApacheisgoingtodiscardanywayforHEADrequests.
ThefollowingdiscussionassumesthatwedealwithaHEADrequest.
3115Feb20141.
4MiscellaneousIssuesHTTPHandlersWhenApacheseesEOSandnoheadersandnoresponsebodyweresent,ap_content_length_filter()(httpd-2.
0/server/protocol.
c)setsC-Lto0.
Lateronap_http_header_filter()(httpd-2.
0/modules/http/http_protocol.
c)removestheC-LheaderfortheHEADrequests.
Theworkaroundistoforcethesendingoftheresponseheaders,beforeEOSwassent(whichhappenswhentheresponsehandlerreturns).
Thesimplestsolutionistouserflush():if($r->header_only){#HEAD$body_len=calculate_body_len();$r->set_content_length($body_len);$r->rflush;}else{#GET#generateandsendthebody}nowifthehandlersetstheC-Lheaderit'llbedeliveredtotheclientunmodified.
1.
5MiscNotesTheseitemswillneedtobeextendedandintegratedinthisorotherHTTPrelateddocuments:front-endback-endsetup:mod_proxy+X-Forwarded-Forapache-1.
3:frontend:mod_proxy_add_forwardhttp://develooper.
com/code/mpaf/backend:mod_rpaf(reverseproxyaddforward):http://stderr.
net/apache/rpaf/apache-2.
x:frontend:mod_proxybackend:mod_rpaf:http://stderr.
net/apache/rpaf/1.
6ExtendingHTTPProtocolExtendingHTTPundermod_perlisatrivialtask.
LookattheexampleofaddinganewmethodEMAILfordetails.
1.
7HTTPStatusCodesTheHypertextTransferProtocol(HTTP)isanapplication-levelprotocolfordistributed,collaborative,hypermediainformationsystems.
Itisageneric,stateless,protocolwhichcanbeusedformanytasksbeyonditsuseforhypertext,suchasnameserversanddistributedobjectmanagementsystems,throughextensionofitsrequestmethods,errorcodesandheaders.
AfeatureofHTTPisthetypingandnegotiation15Feb2014321.
5MiscNotesofdatarepresentation,allowingsystemstobebuiltindependentlyofthedatabeingtransferred.
HTTP1.
0isdescribedinRequestsForComments(RFC)1945.
HTTP1.
1isthelatestversionofthespeci-ficationsandasofthiswritingHTTP1.
1iscoveredinRFC2616.
Whenwritingmod_perlapplications,usuallyonlyasmallsubsetofHTTPresponsecodesisused,butsometimesyouneedtoknowothersaswell.
WewillgiveashortdescriptionofeachcodeandyouwillfindtheextendedexplanationintheappropriateRFC.
(Section9inRFC1945andsection10inRFC2616).
YoucanalwaysfindthelatestlinktotheseRFCsattheWebConsortiumsite,http://www.
w3.
org/Protocols/.
WhileHTTP1.
1iswidelysupported,HTTP1.
0stillremainsthemainstreamstandard.
ThereforewewillsupplyasummaryofthebothversionsincludingthecorrespondingApacheconstants.
Inmod_perltheseconstantscanbeaccessedtheApache::Constantspackage(e.
g.
,toaccesstheHTTP_OKconstantuseApache::Constants::HTTP_OK).
SeetheApache::Constantsmanpageformoreinformation.
Inmod_perl2theseconstantscanbeaccessedtheApache2::Constpackage(e.
g.
,toaccesstheHTTP_OKconstantuseApache2::Const::HTTP_OK).
SeetheApache2::Constmanpageformoreinformation.
1.
7.
1HTTP1.
0StatusCodesSuccessful2xx:200HTTP_OKOK201HTTP_CREATEDCreated202HTTP_ACCEPTEDAccepted204HTTP_NO_CONTENTNoContentRedirection3xx:301HTTP_MOVED_PERMANENTLYMultipleChoices302HTTP_MOVED_TEMPORARILYMovedPermanently303HTTP_SEE_OTHERMovedTemporarily304HTTP_NOT_MODIFIEDNotModifiedClientError4xx:400HTTP_BAD_REQUESTBadRequest401HTTP_UNAUTHORIZEDUnauthorized403HTTP_FORBIDDENForbidden404HTTP_NOT_FOUNDNotFoundServerError5xx:500HTTP_INTERNAL_SERVER_ERRORInternalServerError501HTTP_NOT_IMPLEMENTEDNotImplemented502HTTP_BAD_GATEWAYBadGateway503HTTP_SERVICE_UNAVAILABLEServiceUnavailableStatusCodes3315Feb20141.
7.
1HTTP1.
0StatusCodesHTTPHandlers1.
7.
2HTTP1.
1StatusCodesInformational1xx:100HTTP_CONTINUEContinue101HTTP_SWITCHING_PROTOCOLSSwitchingProtocolsSuccessful2xx:200HTTP_OKOK201HTTP_CREATEDCreated202HTTP_ACCEPTEDAccepted203HTTP_NON_AUTHORITATIVENon-AuthoritativeInformation204HTTP_NO_CONTENTNoContent205HTTP_RESET_CONTENTResetContent206HTTP_PARTIAL_CONTENTPartialContentRedirection3xx:300HTTP_MULTIPLE_CHOICESMultipleChoices301HTTP_MOVED_PERMANENTLYMovedPermanently302HTTP_MOVED_TEMPORARILYFound303HTTP_SEE_OTHERSeeOther304HTTP_NOT_MODIFIEDNotModified305HTTP_USE_PROXYUseProxy306(Unused)307HTTP_TEMPORARY_REDIRECTTemporaryRedirectClientError4xx:400HTTP_BAD_REQUESTBadRequest401HTTP_UNAUTHORIZEDUnauthorized402HTTP_PAYMENT_REQUIREDPaymentRequired403HTTP_FORBIDDENForbidden404HTTP_NOT_FOUNDNotFound405HTTP_METHOD_NOT_ALLOWEDMethodNotAllowed406HTTP_NOT_ACCEPTABLENotAcceptable407HTTP_PROXY_AUTHENTICATION_REQUIREDProxyAuthenticationRequired408HTTP_REQUEST_TIMEOUTRequestTimeout409HTTP_CONFLICTConflict410HTTP_GONEGone411HTTP_LENGTHREQUIREDLengthRequired412HTTP_PRECONDITION_FAILEDPreconditionFailed413HTTP_REQUEST_ENTITY_TOO_LARGERequestEntityTooLarge414HTTP_REQUEST_URI_TOO_LARGERequest-URITooLong415HTTP_UNSUPPORTED_MEDIA_TYPEUnsupportedMediaType416HTTP_RANGE_NOT_SATISFIABLERequestedRangeNotSatisfiable417HTTP_EXPECTATION_FAILEDExpectationFailedServerError5xx:15Feb2014341.
7.
2HTTP1.
1StatusCodes500HTTP_INTERNAL_SERVER_ERRORInternalServerError501HTTP_NOTIMPLEMENTEDNotImplemented502HTTP_BAD_GATEWAYBadGateway503HTTP_SERVICE_UNAVAILABLEServiceUnavailable504HTTP_GATEWAY_TIME_OUTGatewayTimeout505HTTP_VERSION_NOT_SUPPORTEDHTTPVersionNotSupported1.
7.
3ReferencesAlltheinformationrelatedtowebprotocolscanbefoundattheWorldWideWebConsortiumsite,http://www.
w3.
org/Protocols/.
TherearemanymirrorsoftheRFCsallaroundtheworld.
Oneofthegoodstartingpointsmightbehttp://www.
rfc-editor.
org/.
TheEagleBookprovidedmuchoftheHTTPconstantsmaterialshownherehttp://www.
modperl.
com/book/chapters/ch9.
html#The_Apache_Constants_Class1.
8MaintainersMaintaineristheperson(s)youshouldcontactwithupdates,correctionsandpatches.
Themod_perldevelopmentteamandnumerouscontributors.
1.
9AuthorsStasBekman[http://stason.
org/]Onlythemajorauthorsarelistedabove.
ForcontributorsseetheChangesfile.
3515Feb20141.
8MaintainersHTTPHandlersTableofContents:.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
11HTTPHandlers.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21.
1Description.
.
.
.
.
.
.
.
.
.
.
.
.
.
21.
2HTTPRequestHandlerSkeleton.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21.
3HTTPRequestCyclePhases.
.
.
.
.
.
.
.
.
.
.
.
.
.
31.
3.
1PerlPostReadRequestHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
51.
3.
2PerlTransHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
71.
3.
3PerlMapToStorageHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
81.
3.
4PerlHeaderParserHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
131.
3.
5PerlInitHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
141.
3.
6PerlAccessHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
151.
3.
7PerlAuthenHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
181.
3.
8PerlAuthzHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
201.
3.
9PerlTypeHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
211.
3.
10PerlFixupHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
231.
3.
11PerlResponseHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
251.
3.
12PerlLogHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
271.
3.
13PerlCleanupHandler.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
301.
3.
13.
1PossibleCaveats.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
311.
4MiscellaneousIssues.
.
.
.
.
.
.
.
.
.
.
.
.
.
311.
4.
1HandlingHEADRequests.
.
.
.
.
.
.
.
.
.
.
311.
4.
2Content-LengthResponseHeader.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
321.
5MiscNotes.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
321.
6ExtendingHTTPProtocol.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
321.
7HTTPStatusCodes.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
331.
7.
1HTTP1.
0StatusCodes.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
341.
7.
2HTTP1.
1StatusCodes.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
351.
7.
3References.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
351.
8Maintainers.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
351.
9Authorsi15Feb2014TableofContents:HTTPHandlers

星梦云60元夏日促销,四川100G高防4H4G10M,西南高防月付特价

星梦云怎么样?星梦云好不好,资质齐全,IDC/ISP均有,从星梦云这边租的服务器均可以备案,属于一手资源,高防机柜、大带宽、高防IP业务,一手整C IP段,四川电信,星梦云专注四川高防服务器,成都服务器,雅安服务器 。官方网站:点击访问星梦云官网活动方案:1、成都电信年中活动机(封锁UDP,不可解封):机房CPU内存硬盘带宽IP防护流量原价活动价开通方式成都电信优化线路4vCPU4G40G+50...

CYUN(29元/月)美国、香港、台湾、日本、韩国CN2,续费原价

关于CYUN商家在之前有介绍过一次,CYUN是香港蓝米数据有限公司旗下的云计算服务品牌,和蓝米云、蓝米主机等同属该公司。商家主要是为个人开发者用户、中小型、大型企业用户提供一站式核心网络云端部署服务,促使用户云端部署化简为零,轻松快捷运用云计算。目前,CYUN主要运营美国、香港、台湾、日本、韩国CN2线路产品,包括云服务器、站群服务器和独立服务器等。这次看到CYUN夏季优惠活动发布了,依然是熟悉的...

华纳云CN2高防1810M带宽独享,三网直cn218元/月,2M带宽;独服/高防6折购

华纳云怎么样?华纳云是香港老牌的IDC服务商,成立于2015年,主要提供中国香港/美国节点的服务器及网络安全产品、比如,香港服务器、香港云服务器、香港高防服务器、香港高防IP、美国云服务器、机柜出租以及云虚拟主机等。以极速 BGP 冗余网络、CN2 GIA 回国专线以及多年技能经验,帮助全球数十万家企业实现业务转型攀升。华纳云针对618返场活动,华纳云推出一系列热销产品活动,香港云服务器低至3折,...

500InternalServerError为你推荐
combininggoogle支持ipad支持ipad支持ipad支持ipad支持ipad支持ipad联通版iphone4s怎么区分iphone4s电信版和联通版迅雷雷鸟迅雷会员每日免费抽奖,抽中迅雷的雷鸟披肩了,要钱吗google搜图google自定义搜索是什么?怎么用
我的世界服务器租用 cn域名个人注册 lunarpages pw域名 idc评测网 paypal认证 gomezpeer 空间打开慢 云主机51web ev证书 150邮箱 灵动鬼影 ca4249 godaddy域名证书 电子邮件服务器 怎样建立邮箱 流量计费 卡巴斯基免费试用版 闪讯官网 备案空间 更多