mod_rewrite.c 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932
  1. /* Licensed to the Apache Software Foundation (ASF) under one or more
  2. * contributor license agreements. See the NOTICE file distributed with
  3. * this work for additional information regarding copyright ownership.
  4. * The ASF licenses this file to You under the Apache License, Version 2.0
  5. * (the "License"); you may not use this file except in compliance with
  6. * the License. You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /* _ _ _
  17. * _ __ ___ ___ __| | _ __ _____ ___ __(_) |_ ___
  18. * | '_ ` _ \ / _ \ / _` | | '__/ _ \ \ /\ / / '__| | __/ _ \
  19. * | | | | | | (_) | (_| | | | | __/\ V V /| | | | || __/
  20. * |_| |_| |_|\___/ \__,_|___|_| \___| \_/\_/ |_| |_|\__\___|
  21. * |_____|
  22. *
  23. * URL Rewriting Module
  24. *
  25. * This module uses a rule-based rewriting engine (based on a
  26. * regular-expression parser) to rewrite requested URLs on the fly.
  27. *
  28. * It supports an unlimited number of additional rule conditions (which can
  29. * operate on a lot of variables, even on HTTP headers) for granular
  30. * matching and even external database lookups (either via plain text
  31. * tables, DBM hash files or even external processes) for advanced URL
  32. * substitution.
  33. *
  34. * It operates on the full URLs (including the PATH_INFO part) both in
  35. * per-server context (httpd.conf) and per-dir context (.htaccess) and even
  36. * can generate QUERY_STRING parts on result. The rewriting result finally
  37. * can lead to internal subprocessing, external request redirection or even
  38. * to internal proxy throughput.
  39. *
  40. * This module was originally written in April 1996 and
  41. * gifted exclusively to the The Apache Software Foundation in July 1997 by
  42. *
  43. * Ralf S. Engelschall
  44. * rse engelschall.com
  45. * www.engelschall.com
  46. */
  47. #include "apr.h"
  48. #include "apr_strings.h"
  49. #include "apr_hash.h"
  50. #include "apr_user.h"
  51. #include "apr_lib.h"
  52. #include "apr_signal.h"
  53. #include "apr_global_mutex.h"
  54. #include "apr_dbm.h"
  55. #if APR_HAS_THREADS
  56. #include "apr_thread_mutex.h"
  57. #endif
  58. #define APR_WANT_MEMFUNC
  59. #define APR_WANT_STRFUNC
  60. #define APR_WANT_IOVEC
  61. #include "apr_want.h"
  62. /* XXX: Do we really need these headers? */
  63. #if APR_HAVE_UNISTD_H
  64. #include <unistd.h>
  65. #endif
  66. #if APR_HAVE_SYS_TYPES_H
  67. #include <sys/types.h>
  68. #endif
  69. #if APR_HAVE_STDARG_H
  70. #include <stdarg.h>
  71. #endif
  72. #if APR_HAVE_STDLIB_H
  73. #include <stdlib.h>
  74. #endif
  75. #if APR_HAVE_CTYPE_H
  76. #include <ctype.h>
  77. #endif
  78. #include "ap_config.h"
  79. #include "httpd.h"
  80. #include "http_config.h"
  81. #include "http_request.h"
  82. #include "http_core.h"
  83. #include "http_log.h"
  84. #include "http_protocol.h"
  85. #include "http_vhost.h"
  86. #include "mod_ssl.h"
  87. #include "mod_rewrite.h"
  88. #ifdef AP_NEED_SET_MUTEX_PERMS
  89. #include "unixd.h"
  90. #endif
  91. /*
  92. * in order to improve performance on running production systems, you
  93. * may strip all rewritelog code entirely from mod_rewrite by using the
  94. * -DREWRITELOG_DISABLED compiler option.
  95. *
  96. * DO NOT USE THIS OPTION FOR PUBLIC BINARY RELEASES. Otherwise YOU are
  97. * responsible for answering all the mod_rewrite questions out there.
  98. */
  99. #ifndef REWRITELOG_DISABLED
  100. #define rewritelog(x) do_rewritelog x
  101. #define REWRITELOG_MODE ( APR_UREAD | APR_UWRITE | APR_GREAD | APR_WREAD )
  102. #define REWRITELOG_FLAGS ( APR_WRITE | APR_APPEND | APR_CREATE )
  103. #else /* !REWRITELOG_DISABLED */
  104. #define rewritelog(x)
  105. #endif /* REWRITELOG_DISABLED */
  106. /* remembered mime-type for [T=...] */
  107. #define REWRITE_FORCED_MIMETYPE_NOTEVAR "rewrite-forced-mimetype"
  108. #define REWRITE_FORCED_HANDLER_NOTEVAR "rewrite-forced-handler"
  109. #define ENVVAR_SCRIPT_URL "SCRIPT_URL"
  110. #define REDIRECT_ENVVAR_SCRIPT_URL "REDIRECT_" ENVVAR_SCRIPT_URL
  111. #define ENVVAR_SCRIPT_URI "SCRIPT_URI"
  112. #define CONDFLAG_NONE 1<<0
  113. #define CONDFLAG_NOCASE 1<<1
  114. #define CONDFLAG_NOTMATCH 1<<2
  115. #define CONDFLAG_ORNEXT 1<<3
  116. #define CONDFLAG_NOVARY 1<<4
  117. #define RULEFLAG_NONE 1<<0
  118. #define RULEFLAG_FORCEREDIRECT 1<<1
  119. #define RULEFLAG_LASTRULE 1<<2
  120. #define RULEFLAG_NEWROUND 1<<3
  121. #define RULEFLAG_CHAIN 1<<4
  122. #define RULEFLAG_IGNOREONSUBREQ 1<<5
  123. #define RULEFLAG_NOTMATCH 1<<6
  124. #define RULEFLAG_PROXY 1<<7
  125. #define RULEFLAG_PASSTHROUGH 1<<8
  126. #define RULEFLAG_QSAPPEND 1<<9
  127. #define RULEFLAG_NOCASE 1<<10
  128. #define RULEFLAG_NOESCAPE 1<<11
  129. #define RULEFLAG_NOSUB 1<<12
  130. #define RULEFLAG_STATUS 1<<13
  131. #define RULEFLAG_ESCAPEBACKREF 1<<14
  132. #define RULEFLAG_DISCARDPATHINFO 1<<15
  133. /* return code of the rewrite rule
  134. * the result may be escaped - or not
  135. */
  136. #define ACTION_NORMAL 1<<0
  137. #define ACTION_NOESCAPE 1<<1
  138. #define ACTION_STATUS 1<<2
  139. #define MAPTYPE_TXT 1<<0
  140. #define MAPTYPE_DBM 1<<1
  141. #define MAPTYPE_PRG 1<<2
  142. #define MAPTYPE_INT 1<<3
  143. #define MAPTYPE_RND 1<<4
  144. #define ENGINE_DISABLED 1<<0
  145. #define ENGINE_ENABLED 1<<1
  146. #define OPTION_NONE 1<<0
  147. #define OPTION_INHERIT 1<<1
  148. #ifndef RAND_MAX
  149. #define RAND_MAX 32767
  150. #endif
  151. /* max cookie size in rfc 2109 */
  152. /* XXX: not used at all. We should do a check somewhere and/or cut the cookie */
  153. #define MAX_COOKIE_LEN 4096
  154. /* max line length (incl.\n) in text rewrite maps */
  155. #ifndef REWRITE_MAX_TXT_MAP_LINE
  156. #define REWRITE_MAX_TXT_MAP_LINE 1024
  157. #endif
  158. /* buffer length for prg rewrite maps */
  159. #ifndef REWRITE_PRG_MAP_BUF
  160. #define REWRITE_PRG_MAP_BUF 1024
  161. #endif
  162. /* for better readbility */
  163. #define LEFT_CURLY '{'
  164. #define RIGHT_CURLY '}'
  165. /*
  166. * expansion result items on the stack to save some cycles
  167. *
  168. * (5 == about 2 variables like "foo%{var}bar%{var}baz")
  169. */
  170. #define SMALL_EXPANSION 5
  171. /*
  172. * check that a subrequest won't cause infinite recursion
  173. *
  174. * either not in a subrequest, or in a subrequest
  175. * and URIs aren't NULL and sub/main URIs differ
  176. */
  177. #define subreq_ok(r) (!r->main || \
  178. (r->main->uri && r->uri && strcmp(r->main->uri, r->uri)))
  179. /*
  180. * +-------------------------------------------------------+
  181. * | |
  182. * | Types and Structures
  183. * | |
  184. * +-------------------------------------------------------+
  185. */
  186. typedef struct {
  187. const char *datafile; /* filename for map data files */
  188. const char *dbmtype; /* dbm type for dbm map data files */
  189. const char *checkfile; /* filename to check for map existence */
  190. const char *cachename; /* for cached maps (txt/rnd/dbm) */
  191. int type; /* the type of the map */
  192. apr_file_t *fpin; /* in file pointer for program maps */
  193. apr_file_t *fpout; /* out file pointer for program maps */
  194. apr_file_t *fperr; /* err file pointer for program maps */
  195. char *(*func)(request_rec *, /* function pointer for internal maps */
  196. char *);
  197. char **argv; /* argv of the external rewrite map */
  198. const char *checkfile2; /* filename to check for map existence
  199. NULL if only one file */
  200. } rewritemap_entry;
  201. /* special pattern types for RewriteCond */
  202. typedef enum {
  203. CONDPAT_REGEX = 0,
  204. CONDPAT_FILE_EXISTS,
  205. CONDPAT_FILE_SIZE,
  206. CONDPAT_FILE_LINK,
  207. CONDPAT_FILE_DIR,
  208. CONDPAT_FILE_XBIT,
  209. CONDPAT_LU_URL,
  210. CONDPAT_LU_FILE,
  211. CONDPAT_STR_GT,
  212. CONDPAT_STR_LT,
  213. CONDPAT_STR_EQ
  214. } pattern_type;
  215. typedef struct {
  216. char *input; /* Input string of RewriteCond */
  217. char *pattern; /* the RegExp pattern string */
  218. ap_regex_t *regexp; /* the precompiled regexp */
  219. int flags; /* Flags which control the match */
  220. pattern_type ptype; /* pattern type */
  221. } rewritecond_entry;
  222. /* single linked list for env vars and cookies */
  223. typedef struct data_item {
  224. struct data_item *next;
  225. char *data;
  226. } data_item;
  227. typedef struct {
  228. apr_array_header_t *rewriteconds;/* the corresponding RewriteCond entries */
  229. char *pattern; /* the RegExp pattern string */
  230. ap_regex_t *regexp; /* the RegExp pattern compilation */
  231. char *output; /* the Substitution string */
  232. int flags; /* Flags which control the substitution */
  233. char *forced_mimetype; /* forced MIME type of substitution */
  234. char *forced_handler; /* forced content handler of subst. */
  235. int forced_responsecode; /* forced HTTP response status */
  236. data_item *env; /* added environment variables */
  237. data_item *cookie; /* added cookies */
  238. int skip; /* number of next rules to skip */
  239. } rewriterule_entry;
  240. typedef struct {
  241. int state; /* the RewriteEngine state */
  242. int options; /* the RewriteOption state */
  243. #ifndef REWRITELOG_DISABLED
  244. const char *rewritelogfile; /* the RewriteLog filename */
  245. apr_file_t *rewritelogfp; /* the RewriteLog open filepointer */
  246. int rewriteloglevel; /* the RewriteLog level of verbosity */
  247. #endif
  248. apr_hash_t *rewritemaps; /* the RewriteMap entries */
  249. apr_array_header_t *rewriteconds; /* the RewriteCond entries (temp.) */
  250. apr_array_header_t *rewriterules; /* the RewriteRule entries */
  251. server_rec *server; /* the corresponding server indicator */
  252. } rewrite_server_conf;
  253. typedef struct {
  254. int state; /* the RewriteEngine state */
  255. int options; /* the RewriteOption state */
  256. apr_array_header_t *rewriteconds; /* the RewriteCond entries (temp.) */
  257. apr_array_header_t *rewriterules; /* the RewriteRule entries */
  258. char *directory; /* the directory where it applies */
  259. const char *baseurl; /* the base-URL where it applies */
  260. } rewrite_perdir_conf;
  261. /* the (per-child) cache structures.
  262. */
  263. typedef struct cache {
  264. apr_pool_t *pool;
  265. apr_hash_t *maps;
  266. #if APR_HAS_THREADS
  267. apr_thread_mutex_t *lock;
  268. #endif
  269. } cache;
  270. /* cached maps contain an mtime for the whole map and live in a subpool
  271. * of the cachep->pool. That makes it easy to forget them if necessary.
  272. */
  273. typedef struct {
  274. apr_time_t mtime;
  275. apr_pool_t *pool;
  276. apr_hash_t *entries;
  277. } cachedmap;
  278. /* the regex structure for the
  279. * substitution of backreferences
  280. */
  281. typedef struct backrefinfo {
  282. char *source;
  283. int nsub;
  284. ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
  285. } backrefinfo;
  286. /* single linked list used for
  287. * variable expansion
  288. */
  289. typedef struct result_list {
  290. struct result_list *next;
  291. apr_size_t len;
  292. const char *string;
  293. } result_list;
  294. /* context structure for variable lookup and expansion
  295. */
  296. typedef struct {
  297. request_rec *r;
  298. const char *uri;
  299. const char *vary_this;
  300. const char *vary;
  301. char *perdir;
  302. backrefinfo briRR;
  303. backrefinfo briRC;
  304. } rewrite_ctx;
  305. /*
  306. * +-------------------------------------------------------+
  307. * | |
  308. * | static module data
  309. * | |
  310. * +-------------------------------------------------------+
  311. */
  312. /* the global module structure */
  313. module AP_MODULE_DECLARE_DATA rewrite_module;
  314. /* rewritemap int: handler function registry */
  315. static apr_hash_t *mapfunc_hash;
  316. /* the cache */
  317. static cache *cachep;
  318. /* whether proxy module is available or not */
  319. static int proxy_available;
  320. /* whether random seed can be reaped */
  321. static int rewrite_rand_init_done = 0;
  322. /* Locks/Mutexes */
  323. static const char *lockname;
  324. static apr_global_mutex_t *rewrite_mapr_lock_acquire = NULL;
  325. /* Optional functions imported from mod_ssl when loaded: */
  326. static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *rewrite_ssl_lookup = NULL;
  327. static APR_OPTIONAL_FN_TYPE(ssl_is_https) *rewrite_is_https = NULL;
  328. static char *escape_uri(apr_pool_t *p, const char *path);
  329. /*
  330. * +-------------------------------------------------------+
  331. * | |
  332. * | rewriting logfile support
  333. * | |
  334. * +-------------------------------------------------------+
  335. */
  336. #ifndef REWRITELOG_DISABLED
  337. static char *current_logtime(request_rec *r)
  338. {
  339. apr_time_exp_t t;
  340. char tstr[80];
  341. apr_size_t len;
  342. apr_time_exp_lt(&t, apr_time_now());
  343. apr_strftime(tstr, &len, sizeof(tstr), "[%d/%b/%Y:%H:%M:%S ", &t);
  344. apr_snprintf(tstr+len, sizeof(tstr)-len, "%c%.2d%.2d]",
  345. t.tm_gmtoff < 0 ? '-' : '+',
  346. t.tm_gmtoff / (60*60), t.tm_gmtoff % (60*60));
  347. return apr_pstrdup(r->pool, tstr);
  348. }
  349. static int open_rewritelog(server_rec *s, apr_pool_t *p)
  350. {
  351. rewrite_server_conf *conf;
  352. const char *fname;
  353. conf = ap_get_module_config(s->module_config, &rewrite_module);
  354. /* - no logfile configured
  355. * - logfilename empty
  356. * - virtual log shared w/ main server
  357. */
  358. if (!conf->rewritelogfile || !*conf->rewritelogfile || conf->rewritelogfp) {
  359. return 1;
  360. }
  361. if (*conf->rewritelogfile == '|') {
  362. piped_log *pl;
  363. fname = ap_server_root_relative(p, conf->rewritelogfile+1);
  364. if (!fname) {
  365. ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
  366. "mod_rewrite: Invalid RewriteLog "
  367. "path %s", conf->rewritelogfile+1);
  368. return 0;
  369. }
  370. if ((pl = ap_open_piped_log(p, fname)) == NULL) {
  371. ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
  372. "mod_rewrite: could not open reliable pipe "
  373. "to RewriteLog filter %s", fname);
  374. return 0;
  375. }
  376. conf->rewritelogfp = ap_piped_log_write_fd(pl);
  377. }
  378. else {
  379. apr_status_t rc;
  380. fname = ap_server_root_relative(p, conf->rewritelogfile);
  381. if (!fname) {
  382. ap_log_error(APLOG_MARK, APLOG_ERR, APR_EBADPATH, s,
  383. "mod_rewrite: Invalid RewriteLog "
  384. "path %s", conf->rewritelogfile);
  385. return 0;
  386. }
  387. if ((rc = apr_file_open(&conf->rewritelogfp, fname,
  388. REWRITELOG_FLAGS, REWRITELOG_MODE, p))
  389. != APR_SUCCESS) {
  390. ap_log_error(APLOG_MARK, APLOG_ERR, rc, s,
  391. "mod_rewrite: could not open RewriteLog "
  392. "file %s", fname);
  393. return 0;
  394. }
  395. }
  396. return 1;
  397. }
  398. static void do_rewritelog(request_rec *r, int level, char *perdir,
  399. const char *fmt, ...)
  400. {
  401. rewrite_server_conf *conf;
  402. char *logline, *text;
  403. const char *rhost, *rname;
  404. apr_size_t nbytes;
  405. int redir;
  406. request_rec *req;
  407. va_list ap;
  408. conf = ap_get_module_config(r->server->module_config, &rewrite_module);
  409. if (!conf->rewritelogfp || level > conf->rewriteloglevel) {
  410. return;
  411. }
  412. rhost = ap_get_remote_host(r->connection, r->per_dir_config,
  413. REMOTE_NOLOOKUP, NULL);
  414. rname = ap_get_remote_logname(r);
  415. for (redir=0, req=r; req->prev; req = req->prev) {
  416. ++redir;
  417. }
  418. va_start(ap, fmt);
  419. text = apr_pvsprintf(r->pool, fmt, ap);
  420. va_end(ap);
  421. logline = apr_psprintf(r->pool, "%s %s %s %s [%s/sid#%pp][rid#%pp/%s%s%s] "
  422. "(%d) %s%s%s%s" APR_EOL_STR,
  423. rhost ? ap_escape_logitem(r->pool, rhost) : "UNKNOWN-HOST",
  424. rname ? ap_escape_logitem(r->pool, rname) : "-",
  425. r->user ? (*r->user ? ap_escape_logitem(r->pool, r->user) : "\"\"") : "-",
  426. current_logtime(r),
  427. ap_escape_logitem(r->pool, ap_get_server_name(r)),
  428. (void *)(r->server),
  429. (void *)r,
  430. r->main ? "subreq" : "initial",
  431. redir ? "/redir#" : "",
  432. redir ? apr_itoa(r->pool, redir) : "",
  433. level,
  434. perdir ? "[perdir " : "",
  435. perdir ? perdir : "",
  436. perdir ? "] ": "",
  437. ap_escape_logitem(r->pool, text));
  438. nbytes = strlen(logline);
  439. apr_file_write(conf->rewritelogfp, logline, &nbytes);
  440. return;
  441. }
  442. #endif /* !REWRITELOG_DISABLED */
  443. /*
  444. * +-------------------------------------------------------+
  445. * | |
  446. * | URI and path functions
  447. * | |
  448. * +-------------------------------------------------------+
  449. */
  450. /* return number of chars of the scheme (incl. '://')
  451. * if the URI is absolute (includes a scheme etc.)
  452. * otherwise 0.
  453. *
  454. * NOTE: If you add new schemes here, please have a
  455. * look at escape_absolute_uri and splitout_queryargs.
  456. * Not every scheme takes query strings and some schemes
  457. * may be handled in a special way.
  458. *
  459. * XXX: we may consider a scheme registry, perhaps with
  460. * appropriate escape callbacks to allow other modules
  461. * to extend mod_rewrite at runtime.
  462. */
  463. static unsigned is_absolute_uri(char *uri)
  464. {
  465. /* fast exit */
  466. if (*uri == '/' || strlen(uri) <= 5) {
  467. return 0;
  468. }
  469. switch (*uri++) {
  470. case 'a':
  471. case 'A':
  472. if (!strncasecmp(uri, "jp://", 5)) { /* ajp:// */
  473. return 6;
  474. }
  475. case 'b':
  476. case 'B':
  477. if (!strncasecmp(uri, "alancer://", 10)) { /* balancer:// */
  478. return 11;
  479. }
  480. break;
  481. case 'f':
  482. case 'F':
  483. if (!strncasecmp(uri, "tp://", 5)) { /* ftp:// */
  484. return 6;
  485. }
  486. break;
  487. case 'g':
  488. case 'G':
  489. if (!strncasecmp(uri, "opher://", 8)) { /* gopher:// */
  490. return 9;
  491. }
  492. break;
  493. case 'h':
  494. case 'H':
  495. if (!strncasecmp(uri, "ttp://", 6)) { /* http:// */
  496. return 7;
  497. }
  498. else if (!strncasecmp(uri, "ttps://", 7)) { /* https:// */
  499. return 8;
  500. }
  501. break;
  502. case 'l':
  503. case 'L':
  504. if (!strncasecmp(uri, "dap://", 6)) { /* ldap:// */
  505. return 7;
  506. }
  507. break;
  508. case 'm':
  509. case 'M':
  510. if (!strncasecmp(uri, "ailto:", 6)) { /* mailto: */
  511. return 7;
  512. }
  513. break;
  514. case 'n':
  515. case 'N':
  516. if (!strncasecmp(uri, "ews:", 4)) { /* news: */
  517. return 5;
  518. }
  519. else if (!strncasecmp(uri, "ntp://", 6)) { /* nntp:// */
  520. return 7;
  521. }
  522. break;
  523. case 's':
  524. case 'S':
  525. if (!strncasecmp(uri, "cgi://", 6)) { /* scgi:// */
  526. return 7;
  527. }
  528. break;
  529. }
  530. return 0;
  531. }
  532. static const char c2x_table[] = "0123456789abcdef";
  533. static APR_INLINE unsigned char *c2x(unsigned what, unsigned char prefix,
  534. unsigned char *where)
  535. {
  536. #if APR_CHARSET_EBCDIC
  537. what = apr_xlate_conv_byte(ap_hdrs_to_ascii, (unsigned char)what);
  538. #endif /*APR_CHARSET_EBCDIC*/
  539. *where++ = prefix;
  540. *where++ = c2x_table[what >> 4];
  541. *where++ = c2x_table[what & 0xf];
  542. return where;
  543. }
  544. /*
  545. * Escapes a uri in a similar way as php's urlencode does.
  546. * Based on ap_os_escape_path in server/util.c
  547. */
  548. static char *escape_uri(apr_pool_t *p, const char *path) {
  549. char *copy = apr_palloc(p, 3 * strlen(path) + 3);
  550. const unsigned char *s = (const unsigned char *)path;
  551. unsigned char *d = (unsigned char *)copy;
  552. unsigned c;
  553. while ((c = *s)) {
  554. if (apr_isalnum(c) || c == '_') {
  555. *d++ = c;
  556. }
  557. else if (c == ' ') {
  558. *d++ = '+';
  559. }
  560. else {
  561. d = c2x(c, '%', d);
  562. }
  563. ++s;
  564. }
  565. *d = '\0';
  566. return copy;
  567. }
  568. /*
  569. * escape absolute uri, which may or may not be path oriented.
  570. * So let's handle them differently.
  571. */
  572. static char *escape_absolute_uri(apr_pool_t *p, char *uri, unsigned scheme)
  573. {
  574. char *cp;
  575. /* be safe.
  576. * NULL should indicate elsewhere, that something's wrong
  577. */
  578. if (!scheme || strlen(uri) < scheme) {
  579. return NULL;
  580. }
  581. cp = uri + scheme;
  582. /* scheme with authority part? */
  583. if (cp[-1] == '/') {
  584. /* skip host part */
  585. while (*cp && *cp != '/') {
  586. ++cp;
  587. }
  588. /* nothing after the hostpart. ready! */
  589. if (!*cp || !*++cp) {
  590. return apr_pstrdup(p, uri);
  591. }
  592. /* remember the hostname stuff */
  593. scheme = cp - uri;
  594. /* special thing for ldap.
  595. * The parts are separated by question marks. From RFC 2255:
  596. * ldapurl = scheme "://" [hostport] ["/"
  597. * [dn ["?" [attributes] ["?" [scope]
  598. * ["?" [filter] ["?" extensions]]]]]]
  599. */
  600. if (!strncasecmp(uri, "ldap", 4)) {
  601. char *token[5];
  602. int c = 0;
  603. token[0] = cp = apr_pstrdup(p, cp);
  604. while (*cp && c < 4) {
  605. if (*cp == '?') {
  606. token[++c] = cp + 1;
  607. *cp = '\0';
  608. }
  609. ++cp;
  610. }
  611. return apr_pstrcat(p, apr_pstrndup(p, uri, scheme),
  612. ap_escape_uri(p, token[0]),
  613. (c >= 1) ? "?" : NULL,
  614. (c >= 1) ? ap_escape_uri(p, token[1]) : NULL,
  615. (c >= 2) ? "?" : NULL,
  616. (c >= 2) ? ap_escape_uri(p, token[2]) : NULL,
  617. (c >= 3) ? "?" : NULL,
  618. (c >= 3) ? ap_escape_uri(p, token[3]) : NULL,
  619. (c >= 4) ? "?" : NULL,
  620. (c >= 4) ? ap_escape_uri(p, token[4]) : NULL,
  621. NULL);
  622. }
  623. }
  624. /* Nothing special here. Apply normal escaping. */
  625. return apr_pstrcat(p, apr_pstrndup(p, uri, scheme),
  626. ap_escape_uri(p, cp), NULL);
  627. }
  628. /*
  629. * split out a QUERY_STRING part from
  630. * the current URI string
  631. */
  632. static void splitout_queryargs(request_rec *r, int qsappend)
  633. {
  634. char *q;
  635. /* don't touch, unless it's an http or mailto URL.
  636. * See RFC 1738 and RFC 2368.
  637. */
  638. if (is_absolute_uri(r->filename)
  639. && strncasecmp(r->filename, "ajp", 3)
  640. && strncasecmp(r->filename, "balancer", 8)
  641. && strncasecmp(r->filename, "http", 4)
  642. && strncasecmp(r->filename, "mailto", 6)) {
  643. r->args = NULL; /* forget the query that's still flying around */
  644. return;
  645. }
  646. q = ap_strchr(r->filename, '?');
  647. if (q != NULL) {
  648. char *olduri;
  649. apr_size_t len;
  650. olduri = apr_pstrdup(r->pool, r->filename);
  651. *q++ = '\0';
  652. if (qsappend) {
  653. r->args = apr_pstrcat(r->pool, q, "&", r->args, NULL);
  654. }
  655. else {
  656. r->args = apr_pstrdup(r->pool, q);
  657. }
  658. len = strlen(r->args);
  659. if (!len) {
  660. r->args = NULL;
  661. }
  662. else if (r->args[len-1] == '&') {
  663. r->args[len-1] = '\0';
  664. }
  665. rewritelog((r, 3, NULL, "split uri=%s -> uri=%s, args=%s", olduri,
  666. r->filename, r->args ? r->args : "<none>"));
  667. }
  668. return;
  669. }
  670. /*
  671. * strip 'http[s]://ourhost/' from URI
  672. */
  673. static void reduce_uri(request_rec *r)
  674. {
  675. char *cp;
  676. apr_size_t l;
  677. cp = (char *)ap_http_scheme(r);
  678. l = strlen(cp);
  679. if ( strlen(r->filename) > l+3
  680. && strncasecmp(r->filename, cp, l) == 0
  681. && r->filename[l] == ':'
  682. && r->filename[l+1] == '/'
  683. && r->filename[l+2] == '/' ) {
  684. unsigned short port;
  685. char *portp, *host, *url, *scratch;
  686. scratch = apr_pstrdup(r->pool, r->filename); /* our scratchpad */
  687. /* cut the hostname and port out of the URI */
  688. cp = host = scratch + l + 3; /* 3 == strlen("://") */
  689. while (*cp && *cp != '/' && *cp != ':') {
  690. ++cp;
  691. }
  692. if (*cp == ':') { /* additional port given */
  693. *cp++ = '\0';
  694. portp = cp;
  695. while (*cp && *cp != '/') {
  696. ++cp;
  697. }
  698. *cp = '\0';
  699. port = atoi(portp);
  700. url = r->filename + (cp - scratch);
  701. if (!*url) {
  702. url = "/";
  703. }
  704. }
  705. else if (*cp == '/') { /* default port */
  706. *cp = '\0';
  707. port = ap_default_port(r);
  708. url = r->filename + (cp - scratch);
  709. }
  710. else {
  711. port = ap_default_port(r);
  712. url = "/";
  713. }
  714. /* now check whether we could reduce it to a local path... */
  715. if (ap_matches_request_vhost(r, host, port)) {
  716. rewritelog((r, 3, NULL, "reduce %s -> %s", r->filename, url));
  717. r->filename = apr_pstrdup(r->pool, url);
  718. }
  719. }
  720. return;
  721. }
  722. /*
  723. * add 'http[s]://ourhost[:ourport]/' to URI
  724. * if URI is still not fully qualified
  725. */
  726. static void fully_qualify_uri(request_rec *r)
  727. {
  728. if (r->method_number == M_CONNECT) {
  729. return;
  730. }
  731. else if (!is_absolute_uri(r->filename)) {
  732. const char *thisserver;
  733. char *thisport;
  734. int port;
  735. thisserver = ap_get_server_name(r);
  736. port = ap_get_server_port(r);
  737. thisport = ap_is_default_port(port, r)
  738. ? ""
  739. : apr_psprintf(r->pool, ":%u", port);
  740. r->filename = apr_psprintf(r->pool, "%s://%s%s%s%s",
  741. ap_http_scheme(r), thisserver, thisport,
  742. (*r->filename == '/') ? "" : "/",
  743. r->filename);
  744. }
  745. return;
  746. }
  747. /*
  748. * stat() only the first segment of a path
  749. */
  750. static int prefix_stat(const char *path, apr_pool_t *pool)
  751. {
  752. const char *curpath = path;
  753. const char *root;
  754. const char *slash;
  755. char *statpath;
  756. apr_status_t rv;
  757. rv = apr_filepath_root(&root, &curpath, APR_FILEPATH_TRUENAME, pool);
  758. if (rv != APR_SUCCESS) {
  759. return 0;
  760. }
  761. /* let's recognize slashes only, the mod_rewrite semantics are opaque
  762. * enough.
  763. */
  764. if ((slash = ap_strchr_c(curpath, '/')) != NULL) {
  765. rv = apr_filepath_merge(&statpath, root,
  766. apr_pstrndup(pool, curpath,
  767. (apr_size_t)(slash - curpath)),
  768. APR_FILEPATH_NOTABOVEROOT |
  769. APR_FILEPATH_NOTRELATIVE, pool);
  770. }
  771. else {
  772. rv = apr_filepath_merge(&statpath, root, curpath,
  773. APR_FILEPATH_NOTABOVEROOT |
  774. APR_FILEPATH_NOTRELATIVE, pool);
  775. }
  776. if (rv == APR_SUCCESS) {
  777. apr_finfo_t sb;
  778. if (apr_stat(&sb, statpath, APR_FINFO_MIN, pool) == APR_SUCCESS) {
  779. return 1;
  780. }
  781. }
  782. return 0;
  783. }
  784. /*
  785. * substitute the prefix path 'match' in 'input' with 'subst' (RewriteBase)
  786. */
  787. static char *subst_prefix_path(request_rec *r, char *input, char *match,
  788. const char *subst)
  789. {
  790. apr_size_t len = strlen(match);
  791. if (len && match[len - 1] == '/') {
  792. --len;
  793. }
  794. if (!strncmp(input, match, len) && input[len++] == '/') {
  795. apr_size_t slen, outlen;
  796. char *output;
  797. rewritelog((r, 5, NULL, "strip matching prefix: %s -> %s", input,
  798. input+len));
  799. slen = strlen(subst);
  800. if (slen && subst[slen - 1] != '/') {
  801. ++slen;
  802. }
  803. outlen = strlen(input) + slen - len;
  804. output = apr_palloc(r->pool, outlen + 1); /* don't forget the \0 */
  805. memcpy(output, subst, slen);
  806. if (slen && !output[slen-1]) {
  807. output[slen-1] = '/';
  808. }
  809. memcpy(output+slen, input+len, outlen - slen);
  810. output[outlen] = '\0';
  811. rewritelog((r, 4, NULL, "add subst prefix: %s -> %s", input+len,
  812. output));
  813. return output;
  814. }
  815. /* prefix didn't match */
  816. return input;
  817. }
  818. /*
  819. * +-------------------------------------------------------+
  820. * | |
  821. * | caching support
  822. * | |
  823. * +-------------------------------------------------------+
  824. */
  825. static void set_cache_value(const char *name, apr_time_t t, char *key,
  826. char *val)
  827. {
  828. cachedmap *map;
  829. if (cachep) {
  830. #if APR_HAS_THREADS
  831. apr_thread_mutex_lock(cachep->lock);
  832. #endif
  833. map = apr_hash_get(cachep->maps, name, APR_HASH_KEY_STRING);
  834. if (!map) {
  835. apr_pool_t *p;
  836. if (apr_pool_create(&p, cachep->pool) != APR_SUCCESS) {
  837. #if APR_HAS_THREADS
  838. apr_thread_mutex_unlock(cachep->lock);
  839. #endif
  840. return;
  841. }
  842. map = apr_palloc(cachep->pool, sizeof(cachedmap));
  843. map->pool = p;
  844. map->entries = apr_hash_make(map->pool);
  845. map->mtime = t;
  846. apr_hash_set(cachep->maps, name, APR_HASH_KEY_STRING, map);
  847. }
  848. else if (map->mtime != t) {
  849. apr_pool_clear(map->pool);
  850. map->entries = apr_hash_make(map->pool);
  851. map->mtime = t;
  852. }
  853. /* Now we should have a valid map->entries hash, where we
  854. * can store our value.
  855. *
  856. * We need to copy the key and the value into OUR pool,
  857. * so that we don't leave it during the r->pool cleanup.
  858. */
  859. apr_hash_set(map->entries,
  860. apr_pstrdup(map->pool, key), APR_HASH_KEY_STRING,
  861. apr_pstrdup(map->pool, val));
  862. #if APR_HAS_THREADS
  863. apr_thread_mutex_unlock(cachep->lock);
  864. #endif
  865. }
  866. return;
  867. }
  868. static char *get_cache_value(const char *name, apr_time_t t, char *key,
  869. apr_pool_t *p)
  870. {
  871. cachedmap *map;
  872. char *val = NULL;
  873. if (cachep) {
  874. #if APR_HAS_THREADS
  875. apr_thread_mutex_lock(cachep->lock);
  876. #endif
  877. map = apr_hash_get(cachep->maps, name, APR_HASH_KEY_STRING);
  878. if (map) {
  879. /* if this map is outdated, forget it. */
  880. if (map->mtime != t) {
  881. apr_pool_clear(map->pool);
  882. map->entries = apr_hash_make(map->pool);
  883. map->mtime = t;
  884. }
  885. else {
  886. val = apr_hash_get(map->entries, key, APR_HASH_KEY_STRING);
  887. if (val) {
  888. /* copy the cached value into the supplied pool,
  889. * where it belongs (r->pool usually)
  890. */
  891. val = apr_pstrdup(p, val);
  892. }
  893. }
  894. }
  895. #if APR_HAS_THREADS
  896. apr_thread_mutex_unlock(cachep->lock);
  897. #endif
  898. }
  899. return val;
  900. }
  901. static int init_cache(apr_pool_t *p)
  902. {
  903. cachep = apr_palloc(p, sizeof(cache));
  904. if (apr_pool_create(&cachep->pool, p) != APR_SUCCESS) {
  905. cachep = NULL; /* turns off cache */
  906. return 0;
  907. }
  908. cachep->maps = apr_hash_make(cachep->pool);
  909. #if APR_HAS_THREADS
  910. (void)apr_thread_mutex_create(&(cachep->lock), APR_THREAD_MUTEX_DEFAULT, p);
  911. #endif
  912. return 1;
  913. }
  914. /*
  915. * +-------------------------------------------------------+
  916. * | |
  917. * | Map Functions
  918. * | |
  919. * +-------------------------------------------------------+
  920. */
  921. /*
  922. * General Note: key is already a fresh string, created (expanded) just
  923. * for the purpose to be passed in here. So one can modify key itself.
  924. */
  925. static char *rewrite_mapfunc_toupper(request_rec *r, char *key)
  926. {
  927. char *p;
  928. for (p = key; *p; ++p) {
  929. *p = apr_toupper(*p);
  930. }
  931. return key;
  932. }
  933. static char *rewrite_mapfunc_tolower(request_rec *r, char *key)
  934. {
  935. ap_str_tolower(key);
  936. return key;
  937. }
  938. static char *rewrite_mapfunc_escape(request_rec *r, char *key)
  939. {
  940. return ap_escape_uri(r->pool, key);
  941. }
  942. static char *rewrite_mapfunc_unescape(request_rec *r, char *key)
  943. {
  944. ap_unescape_url(key);
  945. return key;
  946. }
  947. static char *select_random_value_part(request_rec *r, char *value)
  948. {
  949. char *p = value;
  950. unsigned n = 1;
  951. /* count number of distinct values */
  952. while ((p = ap_strchr(p, '|')) != NULL) {
  953. ++n;
  954. ++p;
  955. }
  956. if (n > 1) {
  957. /* initialize random generator
  958. *
  959. * XXX: Probably this should be wrapped into a thread mutex,
  960. * shouldn't it? Is it worth the effort?
  961. */
  962. if (!rewrite_rand_init_done) {
  963. srand((unsigned)(getpid()));
  964. rewrite_rand_init_done = 1;
  965. }
  966. /* select a random subvalue */
  967. n = (int)(((double)(rand() % RAND_MAX) / RAND_MAX) * n + 1);
  968. /* extract it from the whole string */
  969. while (--n && (value = ap_strchr(value, '|')) != NULL) {
  970. ++value;
  971. }
  972. if (value) { /* should not be NULL, but ... */
  973. p = ap_strchr(value, '|');
  974. if (p) {
  975. *p = '\0';
  976. }
  977. }
  978. }
  979. return value;
  980. }
  981. /* child process code */
  982. static void rewrite_child_errfn(apr_pool_t *p, apr_status_t err,
  983. const char *desc)
  984. {
  985. ap_log_error(APLOG_MARK, APLOG_ERR, err, NULL, "%s", desc);
  986. }
  987. static apr_status_t rewritemap_program_child(apr_pool_t *p,
  988. const char *progname, char **argv,
  989. apr_file_t **fpout,
  990. apr_file_t **fpin)
  991. {
  992. apr_status_t rc;
  993. apr_procattr_t *procattr;
  994. apr_proc_t *procnew;
  995. if ( APR_SUCCESS == (rc=apr_procattr_create(&procattr, p))
  996. && APR_SUCCESS == (rc=apr_procattr_io_set(procattr, APR_FULL_BLOCK,
  997. APR_FULL_BLOCK, APR_NO_PIPE))
  998. && APR_SUCCESS == (rc=apr_procattr_dir_set(procattr,
  999. ap_make_dirstr_parent(p, argv[0])))
  1000. && APR_SUCCESS == (rc=apr_procattr_cmdtype_set(procattr, APR_PROGRAM))
  1001. && APR_SUCCESS == (rc=apr_procattr_child_errfn_set(procattr,
  1002. rewrite_child_errfn))
  1003. && APR_SUCCESS == (rc=apr_procattr_error_check_set(procattr, 1))) {
  1004. procnew = apr_pcalloc(p, sizeof(*procnew));
  1005. rc = apr_proc_create(procnew, argv[0], (const char **)argv, NULL,
  1006. procattr, p);
  1007. if (rc == APR_SUCCESS) {
  1008. apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
  1009. if (fpin) {
  1010. (*fpin) = procnew->in;
  1011. }
  1012. if (fpout) {
  1013. (*fpout) = procnew->out;
  1014. }
  1015. }
  1016. }
  1017. return (rc);
  1018. }
  1019. static apr_status_t run_rewritemap_programs(server_rec *s, apr_pool_t *p)
  1020. {
  1021. rewrite_server_conf *conf;
  1022. apr_hash_index_t *hi;
  1023. apr_status_t rc;
  1024. int lock_warning_issued = 0;
  1025. conf = ap_get_module_config(s->module_config, &rewrite_module);
  1026. /* If the engine isn't turned on,
  1027. * don't even try to do anything.
  1028. */
  1029. if (conf->state == ENGINE_DISABLED) {
  1030. return APR_SUCCESS;
  1031. }
  1032. for (hi = apr_hash_first(p, conf->rewritemaps); hi; hi = apr_hash_next(hi)){
  1033. apr_file_t *fpin = NULL;
  1034. apr_file_t *fpout = NULL;
  1035. rewritemap_entry *map;
  1036. void *val;
  1037. apr_hash_this(hi, NULL, NULL, &val);
  1038. map = val;
  1039. if (map->type != MAPTYPE_PRG) {
  1040. continue;
  1041. }
  1042. if (!(map->argv[0]) || !*(map->argv[0]) || map->fpin || map->fpout) {
  1043. continue;
  1044. }
  1045. if (!lock_warning_issued && (!lockname || !*lockname)) {
  1046. ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
  1047. "mod_rewrite: Running external rewrite maps "
  1048. "without defining a RewriteLock is DANGEROUS!");
  1049. ++lock_warning_issued;
  1050. }
  1051. rc = rewritemap_program_child(p, map->argv[0], map->argv,
  1052. &fpout, &fpin);
  1053. if (rc != APR_SUCCESS || fpin == NULL || fpout == NULL) {
  1054. ap_log_error(APLOG_MARK, APLOG_ERR, rc, s,
  1055. "mod_rewrite: could not start RewriteMap "
  1056. "program %s", map->checkfile);
  1057. return rc;
  1058. }
  1059. map->fpin = fpin;
  1060. map->fpout = fpout;
  1061. }
  1062. return APR_SUCCESS;
  1063. }
  1064. /*
  1065. * +-------------------------------------------------------+
  1066. * | |
  1067. * | Lookup functions
  1068. * | |
  1069. * +-------------------------------------------------------+
  1070. */
  1071. static char *lookup_map_txtfile(request_rec *r, const char *file, char *key)
  1072. {
  1073. apr_file_t *fp = NULL;
  1074. char line[REWRITE_MAX_TXT_MAP_LINE + 1]; /* +1 for \0 */
  1075. char *value, *keylast;
  1076. if (apr_file_open(&fp, file, APR_READ|APR_BUFFERED, APR_OS_DEFAULT,
  1077. r->pool) != APR_SUCCESS) {
  1078. return NULL;
  1079. }
  1080. keylast = key + strlen(key);
  1081. value = NULL;
  1082. while (apr_file_gets(line, sizeof(line), fp) == APR_SUCCESS) {
  1083. char *p, *c;
  1084. /* ignore comments and lines starting with whitespaces */
  1085. if (*line == '#' || apr_isspace(*line)) {
  1086. continue;
  1087. }
  1088. p = line;
  1089. c = key;
  1090. while (c < keylast && *p == *c && !apr_isspace(*p)) {
  1091. ++p;
  1092. ++c;
  1093. }
  1094. /* key doesn't match - ignore. */
  1095. if (c != keylast || !apr_isspace(*p)) {
  1096. continue;
  1097. }
  1098. /* jump to the value */
  1099. while (*p && apr_isspace(*p)) {
  1100. ++p;
  1101. }
  1102. /* no value? ignore */
  1103. if (!*p) {
  1104. continue;
  1105. }
  1106. /* extract the value and return. */
  1107. c = p;
  1108. while (*p && !apr_isspace(*p)) {
  1109. ++p;
  1110. }
  1111. value = apr_pstrmemdup(r->pool, c, p - c);
  1112. break;
  1113. }
  1114. apr_file_close(fp);
  1115. return value;
  1116. }
  1117. static char *lookup_map_dbmfile(request_rec *r, const char *file,
  1118. const char *dbmtype, char *key)
  1119. {
  1120. apr_dbm_t *dbmfp = NULL;
  1121. apr_datum_t dbmkey;
  1122. apr_datum_t dbmval;
  1123. char *value;
  1124. if (apr_dbm_open_ex(&dbmfp, dbmtype, file, APR_DBM_READONLY, APR_OS_DEFAULT,
  1125. r->pool) != APR_SUCCESS) {
  1126. return NULL;
  1127. }
  1128. dbmkey.dptr = key;
  1129. dbmkey.dsize = strlen(key);
  1130. if (apr_dbm_fetch(dbmfp, dbmkey, &dbmval) == APR_SUCCESS && dbmval.dptr) {
  1131. value = apr_pstrmemdup(r->pool, dbmval.dptr, dbmval.dsize);
  1132. }
  1133. else {
  1134. value = NULL;
  1135. }
  1136. apr_dbm_close(dbmfp);
  1137. return value;
  1138. }
  1139. static char *lookup_map_program(request_rec *r, apr_file_t *fpin,
  1140. apr_file_t *fpout, char *key)
  1141. {
  1142. char *buf;
  1143. char c;
  1144. apr_size_t i, nbytes, combined_len = 0;
  1145. apr_status_t rv;
  1146. const char *eol = APR_EOL_STR;
  1147. apr_size_t eolc = 0;
  1148. int found_nl = 0;
  1149. result_list *buflist = NULL, *curbuf = NULL;
  1150. #ifndef NO_WRITEV
  1151. struct iovec iova[2];
  1152. apr_size_t niov;
  1153. #endif
  1154. /* when `RewriteEngine off' was used in the per-server
  1155. * context then the rewritemap-programs were not spawned.
  1156. * In this case using such a map (usually in per-dir context)
  1157. * is useless because it is not available.
  1158. *
  1159. * newlines in the key leave bytes in the pipe and cause
  1160. * bad things to happen (next map lookup will use the chars
  1161. * after the \n instead of the new key etc etc - in other words,
  1162. * the Rewritemap falls out of sync with the requests).
  1163. */
  1164. if (fpin == NULL || fpout == NULL || ap_strchr(key, '\n')) {
  1165. return NULL;
  1166. }
  1167. /* take the lock */
  1168. if (rewrite_mapr_lock_acquire) {
  1169. rv = apr_global_mutex_lock(rewrite_mapr_lock_acquire);
  1170. if (rv != APR_SUCCESS) {
  1171. ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
  1172. "apr_global_mutex_lock(rewrite_mapr_lock_acquire) "
  1173. "failed");
  1174. return NULL; /* Maybe this should be fatal? */
  1175. }
  1176. }
  1177. /* write out the request key */
  1178. #ifdef NO_WRITEV
  1179. nbytes = strlen(key);
  1180. apr_file_write(fpin, key, &nbytes);
  1181. nbytes = 1;
  1182. apr_file_write(fpin, "\n", &nbytes);
  1183. #else
  1184. iova[0].iov_base = key;
  1185. iova[0].iov_len = strlen(key);
  1186. iova[1].iov_base = "\n";
  1187. iova[1].iov_len = 1;
  1188. niov = 2;
  1189. apr_file_writev(fpin, iova, niov, &nbytes);
  1190. #endif
  1191. buf = apr_palloc(r->pool, REWRITE_PRG_MAP_BUF + 1);
  1192. /* read in the response value */
  1193. nbytes = 1;
  1194. apr_file_read(fpout, &c, &nbytes);
  1195. do {
  1196. i = 0;
  1197. while (nbytes == 1 && (i < REWRITE_PRG_MAP_BUF)) {
  1198. if (c == eol[eolc]) {
  1199. if (!eol[++eolc]) {
  1200. /* remove eol from the buffer */
  1201. --eolc;
  1202. if (i < eolc) {
  1203. curbuf->len -= eolc-i;
  1204. i = 0;
  1205. }
  1206. else {
  1207. i -= eolc;
  1208. }
  1209. ++found_nl;
  1210. break;
  1211. }
  1212. }
  1213. /* only partial (invalid) eol sequence -> reset the counter */
  1214. else if (eolc) {
  1215. eolc = 0;
  1216. }
  1217. /* catch binary mode, e.g. on Win32 */
  1218. else if (c == '\n') {
  1219. ++found_nl;
  1220. break;
  1221. }
  1222. buf[i++] = c;
  1223. apr_file_read(fpout, &c, &nbytes);
  1224. }
  1225. /* well, if there wasn't a newline yet, we need to read further */
  1226. if (buflist || (nbytes == 1 && !found_nl)) {
  1227. if (!buflist) {
  1228. curbuf = buflist = apr_palloc(r->pool, sizeof(*buflist));
  1229. }
  1230. else if (i) {
  1231. curbuf->next = apr_palloc(r->pool, sizeof(*buflist));
  1232. curbuf = curbuf->next;
  1233. }
  1234. curbuf->next = NULL;
  1235. if (i) {
  1236. curbuf->string = buf;
  1237. curbuf->len = i;
  1238. combined_len += i;
  1239. buf = apr_palloc(r->pool, REWRITE_PRG_MAP_BUF);
  1240. }
  1241. if (nbytes == 1 && !found_nl) {
  1242. i = 0;
  1243. continue;
  1244. }
  1245. }
  1246. break;
  1247. } while (1);
  1248. /* concat the stuff */
  1249. if (buflist) {
  1250. char *p;
  1251. p = buf = apr_palloc(r->pool, combined_len + 1); /* \0 */
  1252. while (buflist) {
  1253. if (buflist->len) {
  1254. memcpy(p, buflist->string, buflist->len);
  1255. p += buflist->len;
  1256. }
  1257. buflist = buflist->next;
  1258. }
  1259. *p = '\0';
  1260. i = combined_len;
  1261. }
  1262. else {
  1263. buf[i] = '\0';
  1264. }
  1265. /* give the lock back */
  1266. if (rewrite_mapr_lock_acquire) {
  1267. rv = apr_global_mutex_unlock(rewrite_mapr_lock_acquire);
  1268. if (rv != APR_SUCCESS) {
  1269. ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
  1270. "apr_global_mutex_unlock(rewrite_mapr_lock_acquire) "
  1271. "failed");
  1272. return NULL; /* Maybe this should be fatal? */
  1273. }
  1274. }
  1275. /* catch the "failed" case */
  1276. if (i == 4 && !strcasecmp(buf, "NULL")) {
  1277. return NULL;
  1278. }
  1279. return buf;
  1280. }
  1281. /*
  1282. * generic map lookup
  1283. */
  1284. static char *lookup_map(request_rec *r, char *name, char *key)
  1285. {
  1286. rewrite_server_conf *conf;
  1287. rewritemap_entry *s;
  1288. char *value;
  1289. apr_finfo_t st;
  1290. apr_status_t rv;
  1291. /* get map configuration */
  1292. conf = ap_get_module_config(r->server->module_config, &rewrite_module);
  1293. s = apr_hash_get(conf->rewritemaps, name, APR_HASH_KEY_STRING);
  1294. /* map doesn't exist */
  1295. if (!s) {
  1296. return NULL;
  1297. }
  1298. switch (s->type) {
  1299. /*
  1300. * Text file map (perhaps random)
  1301. */
  1302. case MAPTYPE_RND:
  1303. case MAPTYPE_TXT:
  1304. rv = apr_stat(&st, s->checkfile, APR_FINFO_MIN, r->pool);
  1305. if (rv != APR_SUCCESS) {
  1306. ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
  1307. "mod_rewrite: can't access text RewriteMap file %s",
  1308. s->checkfile);
  1309. rewritelog((r, 1, NULL,
  1310. "can't open RewriteMap file, see error log"));
  1311. return NULL;
  1312. }
  1313. value = get_cache_value(s->cachename, st.mtime, key, r->pool);
  1314. if (!value) {
  1315. rewritelog((r, 6, NULL,
  1316. "cache lookup FAILED, forcing new map lookup"));
  1317. value = lookup_map_txtfile(r, s->datafile, key);
  1318. if (!value) {
  1319. rewritelog((r, 5, NULL, "map lookup FAILED: map=%s[txt] key=%s",
  1320. name, key));
  1321. set_cache_value(s->cachename, st.mtime, key, "");
  1322. return NULL;
  1323. }
  1324. rewritelog((r, 5, NULL,"map lookup OK: map=%s[txt] key=%s -> val=%s",
  1325. name, key, value));
  1326. set_cache_value(s->cachename, st.mtime, key, value);
  1327. }
  1328. else {
  1329. rewritelog((r,5,NULL,"cache lookup OK: map=%s[txt] key=%s -> val=%s",
  1330. name, key, value));
  1331. }
  1332. if (s->type == MAPTYPE_RND && *value) {
  1333. value = select_random_value_part(r, value);
  1334. rewritelog((r, 5, NULL, "randomly chosen the subvalue `%s'",value));
  1335. }
  1336. return *value ? value : NULL;
  1337. /*
  1338. * DBM file map
  1339. */
  1340. case MAPTYPE_DBM:
  1341. rv = apr_stat(&st, s->checkfile, APR_FINFO_MIN, r->pool);
  1342. if (rv != APR_SUCCESS) {
  1343. ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
  1344. "mod_rewrite: can't access DBM RewriteMap file %s",
  1345. s->checkfile);
  1346. }
  1347. else if(s->checkfile2 != NULL) {
  1348. apr_finfo_t st2;
  1349. rv = apr_stat(&st2, s->checkfile2, APR_FINFO_MIN, r->pool);
  1350. if (rv != APR_SUCCESS) {
  1351. ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
  1352. "mod_rewrite: can't access DBM RewriteMap "
  1353. "file %s", s->checkfile2);
  1354. }
  1355. else if(st2.mtime > st.mtime) {
  1356. st.mtime = st2.mtime;
  1357. }
  1358. }
  1359. if(rv != APR_SUCCESS) {
  1360. rewritelog((r, 1, NULL,
  1361. "can't open DBM RewriteMap file, see error log"));
  1362. return NULL;
  1363. }
  1364. value = get_cache_value(s->cachename, st.mtime, key, r->pool);
  1365. if (!value) {
  1366. rewritelog((r, 6, NULL,
  1367. "cache lookup FAILED, forcing new map lookup"));
  1368. value = lookup_map_dbmfile(r, s->datafile, s->dbmtype, key);
  1369. if (!value) {
  1370. rewritelog((r, 5, NULL, "map lookup FAILED: map=%s[dbm] key=%s",
  1371. name, key));
  1372. set_cache_value(s->cachename, st.mtime, key, "");
  1373. return NULL;
  1374. }
  1375. rewritelog((r, 5, NULL, "map lookup OK: map=%s[dbm] key=%s -> "
  1376. "val=%s", name, key, value));
  1377. set_cache_value(s->cachename, st.mtime, key, value);
  1378. return value;
  1379. }
  1380. rewritelog((r, 5, NULL, "cache lookup OK: map=%s[dbm] key=%s -> val=%s",
  1381. name, key, value));
  1382. return *value ? value : NULL;
  1383. /*
  1384. * Program file map
  1385. */
  1386. case MAPTYPE_PRG:
  1387. value = lookup_map_program(r, s->fpin, s->fpout, key);
  1388. if (!value) {
  1389. rewritelog((r, 5,NULL,"map lookup FAILED: map=%s key=%s", name,
  1390. key));
  1391. return NULL;
  1392. }
  1393. rewritelog((r, 5, NULL, "map lookup OK: map=%s key=%s -> val=%s",
  1394. name, key, value));
  1395. return value;
  1396. /*
  1397. * Internal Map
  1398. */
  1399. case MAPTYPE_INT:
  1400. value = s->func(r, key);
  1401. if (!value) {
  1402. rewritelog((r, 5,NULL,"map lookup FAILED: map=%s key=%s", name,
  1403. key));
  1404. return NULL;
  1405. }
  1406. rewritelog((r, 5, NULL, "map lookup OK: map=%s key=%s -> val=%s",
  1407. name, key, value));
  1408. return value;
  1409. }
  1410. return NULL;
  1411. }
  1412. /*
  1413. * lookup a HTTP header and set VARY note
  1414. */
  1415. static const char *lookup_header(const char *name, rewrite_ctx *ctx)
  1416. {
  1417. const char *val = apr_table_get(ctx->r->headers_in, name);
  1418. if (val) {
  1419. ctx->vary_this = ctx->vary_this
  1420. ? apr_pstrcat(ctx->r->pool, ctx->vary_this, ", ",
  1421. name, NULL)
  1422. : apr_pstrdup(ctx->r->pool, name);
  1423. }
  1424. return val;
  1425. }
  1426. /*
  1427. * lookahead helper function
  1428. * Determine the correct URI path in perdir context
  1429. */
  1430. static APR_INLINE const char *la_u(rewrite_ctx *ctx)
  1431. {
  1432. rewrite_perdir_conf *conf;
  1433. if (*ctx->uri == '/') {
  1434. return ctx->uri;
  1435. }
  1436. conf = ap_get_module_config(ctx->r->per_dir_config, &rewrite_module);
  1437. return apr_pstrcat(ctx->r->pool, conf->baseurl
  1438. ? conf->baseurl : conf->directory,
  1439. ctx->uri, NULL);
  1440. }
  1441. /*
  1442. * generic variable lookup
  1443. */
  1444. static char *lookup_variable(char *var, rewrite_ctx *ctx)
  1445. {
  1446. const char *result;
  1447. request_rec *r = ctx->r;
  1448. apr_size_t varlen = strlen(var);
  1449. /* fast exit */
  1450. if (varlen < 4) {
  1451. return apr_pstrdup(r->pool, "");
  1452. }
  1453. result = NULL;
  1454. /* fast tests for variable length variables (sic) first */
  1455. if (var[3] == ':') {
  1456. if (var[4] && !strncasecmp(var, "ENV", 3)) {
  1457. var += 4;
  1458. result = apr_table_get(r->notes, var);
  1459. if (!result) {
  1460. result = apr_table_get(r->subprocess_env, var);
  1461. }
  1462. if (!result) {
  1463. result = getenv(var);
  1464. }
  1465. }
  1466. else if (var[4] && !strncasecmp(var, "SSL", 3) && rewrite_ssl_lookup) {
  1467. result = rewrite_ssl_lookup(r->pool, r->server, r->connection, r,
  1468. var + 4);
  1469. }
  1470. }
  1471. else if (var[4] == ':') {
  1472. if (var[5]) {
  1473. request_rec *rr;
  1474. const char *path;
  1475. if (!strncasecmp(var, "HTTP", 4)) {
  1476. result = lookup_header(var+5, ctx);
  1477. }
  1478. else if (!strncasecmp(var, "LA-U", 4)) {
  1479. if (ctx->uri && subreq_ok(r)) {
  1480. path = ctx->perdir ? la_u(ctx) : ctx->uri;
  1481. rr = ap_sub_req_lookup_uri(path, r, NULL);
  1482. ctx->r = rr;
  1483. result = apr_pstrdup(r->pool, lookup_variable(var+5, ctx));
  1484. ctx->r = r;
  1485. ap_destroy_sub_req(rr);
  1486. rewritelog((r, 5, ctx->perdir, "lookahead: path=%s var=%s "
  1487. "-> val=%s", path, var+5, result));
  1488. return (char *)result;
  1489. }
  1490. }
  1491. else if (!strncasecmp(var, "LA-F", 4)) {
  1492. if (ctx->uri && subreq_ok(r)) {
  1493. path = ctx->uri;
  1494. if (ctx->perdir && *path == '/') {
  1495. /* sigh, the user wants a file based subrequest, but
  1496. * we can't do one, since we don't know what the file
  1497. * path is! In this case behave like LA-U.
  1498. */
  1499. rr = ap_sub_req_lookup_uri(path, r, NULL);
  1500. }
  1501. else {
  1502. if (ctx->perdir) {
  1503. rewrite_perdir_conf *conf;
  1504. conf = ap_get_module_config(r->per_dir_config,
  1505. &rewrite_module);
  1506. path = apr_pstrcat(r->pool, conf->directory, path,
  1507. NULL);
  1508. }
  1509. rr = ap_sub_req_lookup_file(path, r, NULL);
  1510. }
  1511. ctx->r = rr;
  1512. result = apr_pstrdup(r->pool, lookup_variable(var+5, ctx));
  1513. ctx->r = r;
  1514. ap_destroy_sub_req(rr);
  1515. rewritelog((r, 5, ctx->perdir, "lookahead: path=%s var=%s "
  1516. "-> val=%s", path, var+5, result));
  1517. return (char *)result;
  1518. }
  1519. }
  1520. }
  1521. }
  1522. /* well, do it the hard way */
  1523. else {
  1524. char *p;
  1525. apr_time_exp_t tm;
  1526. /* can't do this above, because of the getenv call */
  1527. for (p = var; *p; ++p) {
  1528. *p = apr_toupper(*p);
  1529. }
  1530. switch (varlen) {
  1531. case 4:
  1532. if (!strcmp(var, "TIME")) {
  1533. apr_time_exp_lt(&tm, apr_time_now());
  1534. result = apr_psprintf(r->pool, "%04d%02d%02d%02d%02d%02d",
  1535. tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
  1536. tm.tm_hour, tm.tm_min, tm.tm_sec);
  1537. rewritelog((r, 1, ctx->perdir, "RESULT='%s'", result));
  1538. return (char *)result;
  1539. }
  1540. break;
  1541. case 5:
  1542. if (!strcmp(var, "HTTPS")) {
  1543. int flag = rewrite_is_https && rewrite_is_https(r->connection);
  1544. return apr_pstrdup(r->pool, flag ? "on" : "off");
  1545. }
  1546. break;
  1547. case 8:
  1548. switch (var[6]) {
  1549. case 'A':
  1550. if (!strcmp(var, "TIME_DAY")) {
  1551. apr_time_exp_lt(&tm, apr_time_now());
  1552. return apr_psprintf(r->pool, "%02d", tm.tm_mday);
  1553. }
  1554. break;
  1555. case 'E':
  1556. if (!strcmp(var, "TIME_SEC")) {
  1557. apr_time_exp_lt(&tm, apr_time_now());
  1558. return apr_psprintf(r->pool, "%02d", tm.tm_sec);
  1559. }
  1560. break;
  1561. case 'I':
  1562. if (!strcmp(var, "TIME_MIN")) {
  1563. apr_time_exp_lt(&tm, apr_time_now());
  1564. return apr_psprintf(r->pool, "%02d", tm.tm_min);
  1565. }
  1566. break;
  1567. case 'O':
  1568. if (!strcmp(var, "TIME_MON")) {
  1569. apr_time_exp_lt(&tm, apr_time_now());
  1570. return apr_psprintf(r->pool, "%02d", tm.tm_mon+1);
  1571. }
  1572. break;
  1573. }
  1574. break;
  1575. case 9:
  1576. switch (var[7]) {
  1577. case 'A':
  1578. if (var[8] == 'Y' && !strcmp(var, "TIME_WDAY")) {
  1579. apr_time_exp_lt(&tm, apr_time_now());
  1580. return apr_psprintf(r->pool, "%d", tm.tm_wday);
  1581. }
  1582. else if (!strcmp(var, "TIME_YEAR")) {
  1583. apr_time_exp_lt(&tm, apr_time_now());
  1584. return apr_psprintf(r->pool, "%04d", tm.tm_year+1900);
  1585. }
  1586. break;
  1587. case 'E':
  1588. if (!strcmp(var, "IS_SUBREQ")) {
  1589. result = (r->main ? "true" : "false");
  1590. }
  1591. break;
  1592. case 'F':
  1593. if (!strcmp(var, "PATH_INFO")) {
  1594. result = r->path_info;
  1595. }
  1596. break;
  1597. case 'P':
  1598. if (!strcmp(var, "AUTH_TYPE")) {
  1599. result = r->ap_auth_type;
  1600. }
  1601. break;
  1602. case 'S':
  1603. if (!strcmp(var, "HTTP_HOST")) {
  1604. result = lookup_header("Host", ctx);
  1605. }
  1606. break;
  1607. case 'U':
  1608. if (!strcmp(var, "TIME_HOUR")) {
  1609. apr_time_exp_lt(&tm, apr_time_now());
  1610. return apr_psprintf(r->pool, "%02d", tm.tm_hour);
  1611. }
  1612. break;
  1613. }
  1614. break;
  1615. case 11:
  1616. switch (var[8]) {
  1617. case 'A':
  1618. if (!strcmp(var, "SERVER_NAME")) {
  1619. result = ap_get_server_name(r);
  1620. }
  1621. break;
  1622. case 'D':
  1623. if (*var == 'R' && !strcmp(var, "REMOTE_ADDR")) {
  1624. result = r->connection->remote_ip;
  1625. }
  1626. else if (!strcmp(var, "SERVER_ADDR")) {
  1627. result = r->connection->local_ip;
  1628. }
  1629. break;
  1630. case 'E':
  1631. if (*var == 'H' && !strcmp(var, "HTTP_ACCEPT")) {
  1632. result = lookup_header("Accept", ctx);
  1633. }
  1634. else if (!strcmp(var, "THE_REQUEST")) {
  1635. result = r->the_request;
  1636. }
  1637. break;
  1638. case 'I':
  1639. if (!strcmp(var, "API_VERSION")) {
  1640. return apr_psprintf(r->pool, "%d:%d",
  1641. MODULE_MAGIC_NUMBER_MAJOR,
  1642. MODULE_MAGIC_NUMBER_MINOR);
  1643. }
  1644. break;
  1645. case 'K':
  1646. if (!strcmp(var, "HTTP_COOKIE")) {
  1647. result = lookup_header("Cookie", ctx);
  1648. }
  1649. break;
  1650. case 'O':
  1651. if (*var == 'S' && !strcmp(var, "SERVER_PORT")) {
  1652. return apr_psprintf(r->pool, "%u", ap_get_server_port(r));
  1653. }
  1654. else if (var[7] == 'H' && !strcmp(var, "REMOTE_HOST")) {
  1655. result = ap_get_remote_host(r->connection,r->per_dir_config,
  1656. REMOTE_NAME, NULL);
  1657. }
  1658. else if (!strcmp(var, "REMOTE_PORT")) {
  1659. return apr_itoa(r->pool, r->connection->remote_addr->port);
  1660. }
  1661. break;
  1662. case 'S':
  1663. if (*var == 'R' && !strcmp(var, "REMOTE_USER")) {
  1664. result = r->user;
  1665. }
  1666. else if (!strcmp(var, "SCRIPT_USER")) {
  1667. result = "<unknown>";
  1668. if (r->finfo.valid & APR_FINFO_USER) {
  1669. apr_uid_name_get((char **)&result, r->finfo.user,
  1670. r->pool);
  1671. }
  1672. }
  1673. break;
  1674. case 'U':
  1675. if (!strcmp(var, "REQUEST_URI")) {
  1676. result = r->uri;
  1677. }
  1678. break;
  1679. }
  1680. break;
  1681. case 12:
  1682. switch (var[3]) {
  1683. case 'I':
  1684. if (!strcmp(var, "SCRIPT_GROUP")) {
  1685. result = "<unknown>";
  1686. if (r->finfo.valid & APR_FINFO_GROUP) {
  1687. apr_gid_name_get((char **)&result, r->finfo.group,
  1688. r->pool);
  1689. }
  1690. }
  1691. break;
  1692. case 'O':
  1693. if (!strcmp(var, "REMOTE_IDENT")) {
  1694. result = ap_get_remote_logname(r);
  1695. }
  1696. break;
  1697. case 'P':
  1698. if (!strcmp(var, "HTTP_REFERER")) {
  1699. result = lookup_header("Referer", ctx);
  1700. }
  1701. break;
  1702. case 'R':
  1703. if (!strcmp(var, "QUERY_STRING")) {
  1704. result = r->args;
  1705. }
  1706. break;
  1707. case 'V':
  1708. if (!strcmp(var, "SERVER_ADMIN")) {
  1709. result = r->server->server_admin;
  1710. }
  1711. break;
  1712. }
  1713. break;
  1714. case 13:
  1715. if (!strcmp(var, "DOCUMENT_ROOT")) {
  1716. result = ap_document_root(r);
  1717. }
  1718. break;
  1719. case 14:
  1720. if (*var == 'H' && !strcmp(var, "HTTP_FORWARDED")) {
  1721. result = lookup_header("Forwarded", ctx);
  1722. }
  1723. else if (!strcmp(var, "REQUEST_METHOD")) {
  1724. result = r->method;
  1725. }
  1726. break;
  1727. case 15:
  1728. switch (var[7]) {
  1729. case 'E':
  1730. if (!strcmp(var, "HTTP_USER_AGENT")) {
  1731. result = lookup_header("User-Agent", ctx);
  1732. }
  1733. break;
  1734. case 'F':
  1735. if (!strcmp(var, "SCRIPT_FILENAME")) {
  1736. result = r->filename; /* same as request_filename (16) */
  1737. }
  1738. break;
  1739. case 'P':
  1740. if (!strcmp(var, "SERVER_PROTOCOL")) {
  1741. result = r->protocol;
  1742. }
  1743. break;
  1744. case 'S':
  1745. if (!strcmp(var, "SERVER_SOFTWARE")) {
  1746. result = ap_get_server_banner();
  1747. }
  1748. break;
  1749. }
  1750. break;
  1751. case 16:
  1752. if (!strcmp(var, "REQUEST_FILENAME")) {
  1753. result = r->filename; /* same as script_filename (15) */
  1754. }
  1755. break;
  1756. case 21:
  1757. if (!strcmp(var, "HTTP_PROXY_CONNECTION")) {
  1758. result = lookup_header("Proxy-Connection", ctx);
  1759. }
  1760. break;
  1761. }
  1762. }
  1763. return apr_pstrdup(r->pool, result ? result : "");
  1764. }
  1765. /*
  1766. * +-------------------------------------------------------+
  1767. * | |
  1768. * | Expansion functions
  1769. * | |
  1770. * +-------------------------------------------------------+
  1771. */
  1772. /*
  1773. * Bracketed expression handling
  1774. * s points after the opening bracket
  1775. */
  1776. static APR_INLINE char *find_closing_curly(char *s)
  1777. {
  1778. unsigned depth;
  1779. for (depth = 1; *s; ++s) {
  1780. if (*s == RIGHT_CURLY && --depth == 0) {
  1781. return s;
  1782. }
  1783. else if (*s == LEFT_CURLY) {
  1784. ++depth;
  1785. }
  1786. }
  1787. return NULL;
  1788. }
  1789. static APR_INLINE char *find_char_in_curlies(char *s, int c)
  1790. {
  1791. unsigned depth;
  1792. for (depth = 1; *s; ++s) {
  1793. if (*s == c && depth == 1) {
  1794. return s;
  1795. }
  1796. else if (*s == RIGHT_CURLY && --depth == 0) {
  1797. return NULL;
  1798. }
  1799. else if (*s == LEFT_CURLY) {
  1800. ++depth;
  1801. }
  1802. }
  1803. return NULL;
  1804. }
  1805. /* perform all the expansions on the input string
  1806. * putting the result into a new string
  1807. *
  1808. * for security reasons this expansion must be performed in a
  1809. * single pass, otherwise an attacker can arrange for the result
  1810. * of an earlier expansion to include expansion specifiers that
  1811. * are interpreted by a later expansion, producing results that
  1812. * were not intended by the administrator.
  1813. */
  1814. static char *do_expand(char *input, rewrite_ctx *ctx, rewriterule_entry *entry)
  1815. {
  1816. result_list *result, *current;
  1817. result_list sresult[SMALL_EXPANSION];
  1818. unsigned spc = 0;
  1819. apr_size_t span, inputlen, outlen;
  1820. char *p, *c;
  1821. apr_pool_t *pool = ctx->r->pool;
  1822. span = strcspn(input, "\\$%");
  1823. inputlen = strlen(input);
  1824. /* fast exit */
  1825. if (inputlen == span) {
  1826. return apr_pstrdup(pool, input);
  1827. }
  1828. /* well, actually something to do */
  1829. result = current = &(sresult[spc++]);
  1830. p = input + span;
  1831. current->next = NULL;
  1832. current->string = input;
  1833. current->len = span;
  1834. outlen = span;
  1835. /* loop for specials */
  1836. do {
  1837. /* prepare next entry */
  1838. if (current->len) {
  1839. current->next = (spc < SMALL_EXPANSION)
  1840. ? &(sresult[spc++])
  1841. : (result_list *)apr_palloc(pool,
  1842. sizeof(result_list));
  1843. current = current->next;
  1844. current->next = NULL;
  1845. current->len = 0;
  1846. }
  1847. /* escaped character */
  1848. if (*p == '\\') {
  1849. current->len = 1;
  1850. ++outlen;
  1851. if (!p[1]) {
  1852. current->string = p;
  1853. break;
  1854. }
  1855. else {
  1856. current->string = ++p;
  1857. ++p;
  1858. }
  1859. }
  1860. /* variable or map lookup */
  1861. else if (p[1] == '{') {
  1862. char *endp;
  1863. endp = find_closing_curly(p+2);
  1864. if (!endp) {
  1865. current->len = 2;
  1866. current->string = p;
  1867. outlen += 2;
  1868. p += 2;
  1869. }
  1870. /* variable lookup */
  1871. else if (*p == '%') {
  1872. p = lookup_variable(apr_pstrmemdup(pool, p+2, endp-p-2), ctx);
  1873. span = strlen(p);
  1874. current->len = span;
  1875. current->string = p;
  1876. outlen += span;
  1877. p = endp + 1;
  1878. }
  1879. /* map lookup */
  1880. else { /* *p == '$' */
  1881. char *key;
  1882. /*
  1883. * To make rewrite maps useful, the lookup key and
  1884. * default values must be expanded, so we make
  1885. * recursive calls to do the work. For security
  1886. * reasons we must never expand a string that includes
  1887. * verbatim data from the network. The recursion here
  1888. * isn't a problem because the result of expansion is
  1889. * only passed to lookup_map() so it cannot be
  1890. * re-expanded, only re-looked-up. Another way of
  1891. * looking at it is that the recursion is entirely
  1892. * driven by the syntax of the nested curly brackets.
  1893. */
  1894. key = find_char_in_curlies(p+2, ':');
  1895. if (!key) {
  1896. current->len = 2;
  1897. current->string = p;
  1898. outlen += 2;
  1899. p += 2;
  1900. }
  1901. else {
  1902. char *map, *dflt;
  1903. map = apr_pstrmemdup(pool, p+2, endp-p-2);
  1904. key = map + (key-p-2);
  1905. *key++ = '\0';
  1906. dflt = find_char_in_curlies(key, '|');
  1907. if (dflt) {
  1908. *dflt++ = '\0';
  1909. }
  1910. /* reuse of key variable as result */
  1911. key = lookup_map(ctx->r, map, do_expand(key, ctx, entry));
  1912. if (!key && dflt && *dflt) {
  1913. key = do_expand(dflt, ctx, entry);
  1914. }
  1915. if (key) {
  1916. span = strlen(key);
  1917. current->len = span;
  1918. current->string = key;
  1919. outlen += span;
  1920. }
  1921. p = endp + 1;
  1922. }
  1923. }
  1924. }
  1925. /* backreference */
  1926. else if (apr_isdigit(p[1])) {
  1927. int n = p[1] - '0';
  1928. backrefinfo *bri = (*p == '$') ? &ctx->briRR : &ctx->briRC;
  1929. /* see ap_pregsub() in server/util.c */
  1930. if (bri->source && n < AP_MAX_REG_MATCH
  1931. && bri->regmatch[n].rm_eo > bri->regmatch[n].rm_so) {
  1932. span = bri->regmatch[n].rm_eo - bri->regmatch[n].rm_so;
  1933. if (entry && (entry->flags & RULEFLAG_ESCAPEBACKREF)) {
  1934. /* escape the backreference */
  1935. char *tmp2, *tmp;
  1936. tmp = apr_palloc(pool, span + 1);
  1937. strncpy(tmp, bri->source + bri->regmatch[n].rm_so, span);
  1938. tmp[span] = '\0';
  1939. tmp2 = escape_uri(pool, tmp);
  1940. rewritelog((ctx->r, 5, ctx->perdir, "escaping backreference '%s' to '%s'",
  1941. tmp, tmp2));
  1942. current->len = span = strlen(tmp2);
  1943. current->string = tmp2;
  1944. } else {
  1945. current->len = span;
  1946. current->string = bri->source + bri->regmatch[n].rm_so;
  1947. }
  1948. outlen += span;
  1949. }
  1950. p += 2;
  1951. }
  1952. /* not for us, just copy it */
  1953. else {
  1954. current->len = 1;
  1955. current->string = p++;
  1956. ++outlen;
  1957. }
  1958. /* check the remainder */
  1959. if (*p && (span = strcspn(p, "\\$%")) > 0) {
  1960. if (current->len) {
  1961. current->next = (spc < SMALL_EXPANSION)
  1962. ? &(sresult[spc++])
  1963. : (result_list *)apr_palloc(pool,
  1964. sizeof(result_list));
  1965. current = current->next;
  1966. current->next = NULL;
  1967. }
  1968. current->len = span;
  1969. current->string = p;
  1970. p += span;
  1971. outlen += span;
  1972. }
  1973. } while (p < input+inputlen);
  1974. /* assemble result */
  1975. c = p = apr_palloc(pool, outlen + 1); /* don't forget the \0 */
  1976. do {
  1977. if (result->len) {
  1978. ap_assert(c+result->len <= p+outlen); /* XXX: can be removed after
  1979. * extensive testing and
  1980. * review
  1981. */
  1982. memcpy(c, result->string, result->len);
  1983. c += result->len;
  1984. }
  1985. result = result->next;
  1986. } while (result);
  1987. p[outlen] = '\0';
  1988. return p;
  1989. }
  1990. /*
  1991. * perform all the expansions on the environment variables
  1992. */
  1993. static void do_expand_env(data_item *env, rewrite_ctx *ctx)
  1994. {
  1995. char *name, *val;
  1996. while (env) {
  1997. name = do_expand(env->data, ctx, NULL);
  1998. if ((val = ap_strchr(name, ':')) != NULL) {
  1999. *val++ = '\0';
  2000. apr_table_set(ctx->r->subprocess_env, name, val);
  2001. rewritelog((ctx->r, 5, NULL, "setting env variable '%s' to '%s'",
  2002. name, val));
  2003. }
  2004. env = env->next;
  2005. }
  2006. return;
  2007. }
  2008. /*
  2009. * perform all the expansions on the cookies
  2010. *
  2011. * TODO: use cached time similar to how logging does it
  2012. */
  2013. static void add_cookie(request_rec *r, char *s)
  2014. {
  2015. char *var;
  2016. char *val;
  2017. char *domain;
  2018. char *expires;
  2019. char *path;
  2020. char *secure;
  2021. char *httponly;
  2022. char *tok_cntx;
  2023. char *cookie;
  2024. var = apr_strtok(s, ":", &tok_cntx);
  2025. val = apr_strtok(NULL, ":", &tok_cntx);
  2026. domain = apr_strtok(NULL, ":", &tok_cntx);
  2027. if (var && val && domain) {
  2028. request_rec *rmain = r;
  2029. char *notename;
  2030. void *data;
  2031. while (rmain->main) {
  2032. rmain = rmain->main;
  2033. }
  2034. notename = apr_pstrcat(rmain->pool, var, "_rewrite", NULL);
  2035. apr_pool_userdata_get(&data, notename, rmain->pool);
  2036. if (!data) {
  2037. char *exp_time = NULL;
  2038. expires = apr_strtok(NULL, ":", &tok_cntx);
  2039. path = expires ? apr_strtok(NULL, ":", &tok_cntx) : NULL;
  2040. secure = path ? apr_strtok(NULL, ":", &tok_cntx) : NULL;
  2041. httponly = secure ? apr_strtok(NULL, ":", &tok_cntx) : NULL;
  2042. if (expires) {
  2043. apr_time_exp_t tms;
  2044. apr_time_exp_gmt(&tms, r->request_time
  2045. + apr_time_from_sec((60 * atol(expires))));
  2046. exp_time = apr_psprintf(r->pool, "%s, %.2d-%s-%.4d "
  2047. "%.2d:%.2d:%.2d GMT",
  2048. apr_day_snames[tms.tm_wday],
  2049. tms.tm_mday,
  2050. apr_month_snames[tms.tm_mon],
  2051. tms.tm_year+1900,
  2052. tms.tm_hour, tms.tm_min, tms.tm_sec);
  2053. }
  2054. cookie = apr_pstrcat(rmain->pool,
  2055. var, "=", val,
  2056. "; path=", path ? path : "/",
  2057. "; domain=", domain,
  2058. expires ? "; expires=" : NULL,
  2059. expires ? exp_time : NULL,
  2060. (secure && (!strcasecmp(secure, "true")
  2061. || !strcmp(secure, "1")
  2062. || !strcasecmp(secure,
  2063. "secure"))) ?
  2064. "; secure" : NULL,
  2065. (httponly && (!strcasecmp(httponly, "true")
  2066. || !strcmp(httponly, "1")
  2067. || !strcasecmp(httponly,
  2068. "HttpOnly"))) ?
  2069. "; HttpOnly" : NULL,
  2070. NULL);
  2071. apr_table_addn(rmain->err_headers_out, "Set-Cookie", cookie);
  2072. apr_pool_userdata_set("set", notename, NULL, rmain->pool);
  2073. rewritelog((rmain, 5, NULL, "setting cookie '%s'", cookie));
  2074. }
  2075. else {
  2076. rewritelog((rmain, 5, NULL, "skipping already set cookie '%s'",
  2077. var));
  2078. }
  2079. }
  2080. return;
  2081. }
  2082. static void do_expand_cookie(data_item *cookie, rewrite_ctx *ctx)
  2083. {
  2084. while (cookie) {
  2085. add_cookie(ctx->r, do_expand(cookie->data, ctx, NULL));
  2086. cookie = cookie->next;
  2087. }
  2088. return;
  2089. }
  2090. #if APR_HAS_USER
  2091. /*
  2092. * Expand tilde-paths (/~user) through Unix /etc/passwd
  2093. * database information (or other OS-specific database)
  2094. */
  2095. static char *expand_tildepaths(request_rec *r, char *uri)
  2096. {
  2097. if (uri && *uri == '/' && uri[1] == '~') {
  2098. char *p, *user;
  2099. p = user = uri + 2;
  2100. while (*p && *p != '/') {
  2101. ++p;
  2102. }
  2103. if (p > user) {
  2104. char *homedir;
  2105. user = apr_pstrmemdup(r->pool, user, p-user);
  2106. if (apr_uid_homepath_get(&homedir, user, r->pool) == APR_SUCCESS) {
  2107. if (*p) {
  2108. /* reuse of user variable */
  2109. user = homedir + strlen(homedir) - 1;
  2110. if (user >= homedir && *user == '/') {
  2111. *user = '\0';
  2112. }
  2113. return apr_pstrcat(r->pool, homedir, p, NULL);
  2114. }
  2115. else {
  2116. return homedir;
  2117. }
  2118. }
  2119. }
  2120. }
  2121. return uri;
  2122. }
  2123. #endif /* if APR_HAS_USER */
  2124. /*
  2125. * +-------------------------------------------------------+
  2126. * | |
  2127. * | rewriting lockfile support
  2128. * | |
  2129. * +-------------------------------------------------------+
  2130. */
  2131. static apr_status_t rewritelock_create(server_rec *s, apr_pool_t *p)
  2132. {
  2133. apr_status_t rc;
  2134. /* only operate if a lockfile is used */
  2135. if (lockname == NULL || *(lockname) == '\0') {
  2136. return APR_SUCCESS;
  2137. }
  2138. /* create the lockfile */
  2139. rc = apr_global_mutex_create(&rewrite_mapr_lock_acquire, lockname,
  2140. APR_LOCK_DEFAULT, p);
  2141. if (rc != APR_SUCCESS) {
  2142. ap_log_error(APLOG_MARK, APLOG_CRIT, rc, s,
  2143. "mod_rewrite: Parent could not create RewriteLock "
  2144. "file %s", lockname);
  2145. return rc;
  2146. }
  2147. #ifdef AP_NEED_SET_MUTEX_PERMS
  2148. rc = unixd_set_global_mutex_perms(rewrite_mapr_lock_acquire);
  2149. if (rc != APR_SUCCESS) {
  2150. ap_log_error(APLOG_MARK, APLOG_CRIT, rc, s,
  2151. "mod_rewrite: Parent could not set permissions "
  2152. "on RewriteLock; check User and Group directives");
  2153. return rc;
  2154. }
  2155. #endif
  2156. return APR_SUCCESS;
  2157. }
  2158. static apr_status_t rewritelock_remove(void *data)
  2159. {
  2160. /* only operate if a lockfile is used */
  2161. if (lockname == NULL || *(lockname) == '\0') {
  2162. return APR_SUCCESS;
  2163. }
  2164. /* destroy the rewritelock */
  2165. apr_global_mutex_destroy (rewrite_mapr_lock_acquire);
  2166. rewrite_mapr_lock_acquire = NULL;
  2167. lockname = NULL;
  2168. return(0);
  2169. }
  2170. /*
  2171. * +-------------------------------------------------------+
  2172. * | |
  2173. * | configuration directive handling
  2174. * | |
  2175. * +-------------------------------------------------------+
  2176. */
  2177. /*
  2178. * own command line parser for RewriteRule and RewriteCond,
  2179. * which doesn't have the '\\' problem.
  2180. * (returns true on error)
  2181. *
  2182. * XXX: what an inclined parser. Seems we have to leave it so
  2183. * for backwards compat. *sigh*
  2184. */
  2185. static int parseargline(char *str, char **a1, char **a2, char **a3)
  2186. {
  2187. char quote;
  2188. while (apr_isspace(*str)) {
  2189. ++str;
  2190. }
  2191. /*
  2192. * determine first argument
  2193. */
  2194. quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
  2195. *a1 = str;
  2196. for (; *str; ++str) {
  2197. if ((apr_isspace(*str) && !quote) || (*str == quote)) {
  2198. break;
  2199. }
  2200. if (*str == '\\' && apr_isspace(str[1])) {
  2201. ++str;
  2202. continue;
  2203. }
  2204. }
  2205. if (!*str) {
  2206. return 1;
  2207. }
  2208. *str++ = '\0';
  2209. while (apr_isspace(*str)) {
  2210. ++str;
  2211. }
  2212. /*
  2213. * determine second argument
  2214. */
  2215. quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
  2216. *a2 = str;
  2217. for (; *str; ++str) {
  2218. if ((apr_isspace(*str) && !quote) || (*str == quote)) {
  2219. break;
  2220. }
  2221. if (*str == '\\' && apr_isspace(str[1])) {
  2222. ++str;
  2223. continue;
  2224. }
  2225. }
  2226. if (!*str) {
  2227. *a3 = NULL; /* 3rd argument is optional */
  2228. return 0;
  2229. }
  2230. *str++ = '\0';
  2231. while (apr_isspace(*str)) {
  2232. ++str;
  2233. }
  2234. if (!*str) {
  2235. *a3 = NULL; /* 3rd argument is still optional */
  2236. return 0;
  2237. }
  2238. /*
  2239. * determine third argument
  2240. */
  2241. quote = (*str == '"' || *str == '\'') ? *str++ : '\0';
  2242. *a3 = str;
  2243. for (; *str; ++str) {
  2244. if ((apr_isspace(*str) && !quote) || (*str == quote)) {
  2245. break;
  2246. }
  2247. if (*str == '\\' && apr_isspace(str[1])) {
  2248. ++str;
  2249. continue;
  2250. }
  2251. }
  2252. *str = '\0';
  2253. return 0;
  2254. }
  2255. static void *config_server_create(apr_pool_t *p, server_rec *s)
  2256. {
  2257. rewrite_server_conf *a;
  2258. a = (rewrite_server_conf *)apr_pcalloc(p, sizeof(rewrite_server_conf));
  2259. a->state = ENGINE_DISABLED;
  2260. a->options = OPTION_NONE;
  2261. #ifndef REWRITELOG_DISABLED
  2262. a->rewritelogfile = NULL;
  2263. a->rewritelogfp = NULL;
  2264. a->rewriteloglevel = 0;
  2265. #endif
  2266. a->rewritemaps = apr_hash_make(p);
  2267. a->rewriteconds = apr_array_make(p, 2, sizeof(rewritecond_entry));
  2268. a->rewriterules = apr_array_make(p, 2, sizeof(rewriterule_entry));
  2269. a->server = s;
  2270. return (void *)a;
  2271. }
  2272. static void *config_server_merge(apr_pool_t *p, void *basev, void *overridesv)
  2273. {
  2274. rewrite_server_conf *a, *base, *overrides;
  2275. a = (rewrite_server_conf *)apr_pcalloc(p,
  2276. sizeof(rewrite_server_conf));
  2277. base = (rewrite_server_conf *)basev;
  2278. overrides = (rewrite_server_conf *)overridesv;
  2279. a->state = overrides->state;
  2280. a->options = overrides->options;
  2281. a->server = overrides->server;
  2282. if (a->options & OPTION_INHERIT) {
  2283. /*
  2284. * local directives override
  2285. * and anything else is inherited
  2286. */
  2287. #ifndef REWRITELOG_DISABLED
  2288. a->rewriteloglevel = overrides->rewriteloglevel != 0
  2289. ? overrides->rewriteloglevel
  2290. : base->rewriteloglevel;
  2291. a->rewritelogfile = overrides->rewritelogfile != NULL
  2292. ? overrides->rewritelogfile
  2293. : base->rewritelogfile;
  2294. a->rewritelogfp = overrides->rewritelogfp != NULL
  2295. ? overrides->rewritelogfp
  2296. : base->rewritelogfp;
  2297. #endif
  2298. a->rewritemaps = apr_hash_overlay(p, overrides->rewritemaps,
  2299. base->rewritemaps);
  2300. a->rewriteconds = apr_array_append(p, overrides->rewriteconds,
  2301. base->rewriteconds);
  2302. a->rewriterules = apr_array_append(p, overrides->rewriterules,
  2303. base->rewriterules);
  2304. }
  2305. else {
  2306. /*
  2307. * local directives override
  2308. * and anything else gets defaults
  2309. */
  2310. #ifndef REWRITELOG_DISABLED
  2311. a->rewriteloglevel = overrides->rewriteloglevel;
  2312. a->rewritelogfile = overrides->rewritelogfile;
  2313. a->rewritelogfp = overrides->rewritelogfp;
  2314. #endif
  2315. a->rewritemaps = overrides->rewritemaps;
  2316. a->rewriteconds = overrides->rewriteconds;
  2317. a->rewriterules = overrides->rewriterules;
  2318. }
  2319. return (void *)a;
  2320. }
  2321. static void *config_perdir_create(apr_pool_t *p, char *path)
  2322. {
  2323. rewrite_perdir_conf *a;
  2324. a = (rewrite_perdir_conf *)apr_pcalloc(p, sizeof(rewrite_perdir_conf));
  2325. a->state = ENGINE_DISABLED;
  2326. a->options = OPTION_NONE;
  2327. a->baseurl = NULL;
  2328. a->rewriteconds = apr_array_make(p, 2, sizeof(rewritecond_entry));
  2329. a->rewriterules = apr_array_make(p, 2, sizeof(rewriterule_entry));
  2330. if (path == NULL) {
  2331. a->directory = NULL;
  2332. }
  2333. else {
  2334. /* make sure it has a trailing slash */
  2335. if (path[strlen(path)-1] == '/') {
  2336. a->directory = apr_pstrdup(p, path);
  2337. }
  2338. else {
  2339. a->directory = apr_pstrcat(p, path, "/", NULL);
  2340. }
  2341. }
  2342. return (void *)a;
  2343. }
  2344. static void *config_perdir_merge(apr_pool_t *p, void *basev, void *overridesv)
  2345. {
  2346. rewrite_perdir_conf *a, *base, *overrides;
  2347. a = (rewrite_perdir_conf *)apr_pcalloc(p,
  2348. sizeof(rewrite_perdir_conf));
  2349. base = (rewrite_perdir_conf *)basev;
  2350. overrides = (rewrite_perdir_conf *)overridesv;
  2351. a->state = overrides->state;
  2352. a->options = overrides->options;
  2353. a->directory = overrides->directory;
  2354. a->baseurl = overrides->baseurl;
  2355. if (a->options & OPTION_INHERIT) {
  2356. a->rewriteconds = apr_array_append(p, overrides->rewriteconds,
  2357. base->rewriteconds);
  2358. a->rewriterules = apr_array_append(p, overrides->rewriterules,
  2359. base->rewriterules);
  2360. }
  2361. else {
  2362. a->rewriteconds = overrides->rewriteconds;
  2363. a->rewriterules = overrides->rewriterules;
  2364. }
  2365. return (void *)a;
  2366. }
  2367. static const char *cmd_rewriteengine(cmd_parms *cmd,
  2368. void *in_dconf, int flag)
  2369. {
  2370. rewrite_perdir_conf *dconf = in_dconf;
  2371. rewrite_server_conf *sconf;
  2372. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2373. if (cmd->path == NULL) { /* is server command */
  2374. sconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
  2375. }
  2376. else /* is per-directory command */ {
  2377. dconf->state = (flag ? ENGINE_ENABLED : ENGINE_DISABLED);
  2378. }
  2379. return NULL;
  2380. }
  2381. static const char *cmd_rewriteoptions(cmd_parms *cmd,
  2382. void *in_dconf, const char *option)
  2383. {
  2384. int options = 0;
  2385. char *w;
  2386. while (*option) {
  2387. w = ap_getword_conf(cmd->pool, &option);
  2388. if (!strcasecmp(w, "inherit")) {
  2389. options |= OPTION_INHERIT;
  2390. }
  2391. else if (!strncasecmp(w, "MaxRedirects=", 13)) {
  2392. ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
  2393. "RewriteOptions: MaxRedirects option has been "
  2394. "removed in favor of the global "
  2395. "LimitInternalRecursion directive and will be "
  2396. "ignored.");
  2397. }
  2398. else {
  2399. return apr_pstrcat(cmd->pool, "RewriteOptions: unknown option '",
  2400. w, "'", NULL);
  2401. }
  2402. }
  2403. /* put it into the appropriate config */
  2404. if (cmd->path == NULL) { /* is server command */
  2405. rewrite_server_conf *conf =
  2406. ap_get_module_config(cmd->server->module_config,
  2407. &rewrite_module);
  2408. conf->options |= options;
  2409. }
  2410. else { /* is per-directory command */
  2411. rewrite_perdir_conf *conf = in_dconf;
  2412. conf->options |= options;
  2413. }
  2414. return NULL;
  2415. }
  2416. #ifndef REWRITELOG_DISABLED
  2417. static const char *cmd_rewritelog(cmd_parms *cmd, void *dconf, const char *a1)
  2418. {
  2419. rewrite_server_conf *sconf;
  2420. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2421. sconf->rewritelogfile = a1;
  2422. return NULL;
  2423. }
  2424. static const char *cmd_rewriteloglevel(cmd_parms *cmd, void *dconf,
  2425. const char *a1)
  2426. {
  2427. rewrite_server_conf *sconf;
  2428. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2429. sconf->rewriteloglevel = atoi(a1);
  2430. return NULL;
  2431. }
  2432. #endif /* rewritelog */
  2433. static const char *cmd_rewritemap(cmd_parms *cmd, void *dconf, const char *a1,
  2434. const char *a2)
  2435. {
  2436. rewrite_server_conf *sconf;
  2437. rewritemap_entry *newmap;
  2438. apr_finfo_t st;
  2439. const char *fname;
  2440. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2441. newmap = apr_palloc(cmd->pool, sizeof(rewritemap_entry));
  2442. newmap->func = NULL;
  2443. if (strncasecmp(a2, "txt:", 4) == 0) {
  2444. if ((fname = ap_server_root_relative(cmd->pool, a2+4)) == NULL) {
  2445. return apr_pstrcat(cmd->pool, "RewriteMap: bad path to txt map: ",
  2446. a2+4, NULL);
  2447. }
  2448. newmap->type = MAPTYPE_TXT;
  2449. newmap->datafile = fname;
  2450. newmap->checkfile = fname;
  2451. newmap->checkfile2= NULL;
  2452. newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
  2453. (void *)cmd->server, a1);
  2454. }
  2455. else if (strncasecmp(a2, "rnd:", 4) == 0) {
  2456. if ((fname = ap_server_root_relative(cmd->pool, a2+4)) == NULL) {
  2457. return apr_pstrcat(cmd->pool, "RewriteMap: bad path to rnd map: ",
  2458. a2+4, NULL);
  2459. }
  2460. newmap->type = MAPTYPE_RND;
  2461. newmap->datafile = fname;
  2462. newmap->checkfile = fname;
  2463. newmap->checkfile2= NULL;
  2464. newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
  2465. (void *)cmd->server, a1);
  2466. }
  2467. else if (strncasecmp(a2, "dbm", 3) == 0) {
  2468. apr_status_t rv;
  2469. newmap->type = MAPTYPE_DBM;
  2470. fname = NULL;
  2471. newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
  2472. (void *)cmd->server, a1);
  2473. if (a2[3] == ':') {
  2474. newmap->dbmtype = "default";
  2475. fname = a2+4;
  2476. }
  2477. else if (a2[3] == '=') {
  2478. const char *colon = ap_strchr_c(a2 + 4, ':');
  2479. if (colon) {
  2480. newmap->dbmtype = apr_pstrndup(cmd->pool, a2 + 4,
  2481. colon - (a2 + 3) - 1);
  2482. fname = colon + 1;
  2483. }
  2484. }
  2485. if (!fname) {
  2486. return apr_pstrcat(cmd->pool, "RewriteMap: bad map:",
  2487. a2, NULL);
  2488. }
  2489. if ((newmap->datafile = ap_server_root_relative(cmd->pool,
  2490. fname)) == NULL) {
  2491. return apr_pstrcat(cmd->pool, "RewriteMap: bad path to dbm map: ",
  2492. fname, NULL);
  2493. }
  2494. rv = apr_dbm_get_usednames_ex(cmd->pool, newmap->dbmtype,
  2495. newmap->datafile, &newmap->checkfile,
  2496. &newmap->checkfile2);
  2497. if (rv != APR_SUCCESS) {
  2498. return apr_pstrcat(cmd->pool, "RewriteMap: dbm type ",
  2499. newmap->dbmtype, " is invalid", NULL);
  2500. }
  2501. }
  2502. else if (strncasecmp(a2, "prg:", 4) == 0) {
  2503. apr_tokenize_to_argv(a2 + 4, &newmap->argv, cmd->pool);
  2504. fname = newmap->argv[0];
  2505. if ((newmap->argv[0] = ap_server_root_relative(cmd->pool,
  2506. fname)) == NULL) {
  2507. return apr_pstrcat(cmd->pool, "RewriteMap: bad path to prg map: ",
  2508. fname, NULL);
  2509. }
  2510. newmap->type = MAPTYPE_PRG;
  2511. newmap->datafile = NULL;
  2512. newmap->checkfile = newmap->argv[0];
  2513. newmap->checkfile2= NULL;
  2514. newmap->cachename = NULL;
  2515. }
  2516. else if (strncasecmp(a2, "int:", 4) == 0) {
  2517. newmap->type = MAPTYPE_INT;
  2518. newmap->datafile = NULL;
  2519. newmap->checkfile = NULL;
  2520. newmap->checkfile2= NULL;
  2521. newmap->cachename = NULL;
  2522. newmap->func = (char *(*)(request_rec *,char *))
  2523. apr_hash_get(mapfunc_hash, a2+4, strlen(a2+4));
  2524. if ((sconf->state == ENGINE_ENABLED) && (newmap->func == NULL)) {
  2525. return apr_pstrcat(cmd->pool, "RewriteMap: internal map not found:",
  2526. a2+4, NULL);
  2527. }
  2528. }
  2529. else {
  2530. if ((fname = ap_server_root_relative(cmd->pool, a2)) == NULL) {
  2531. return apr_pstrcat(cmd->pool, "RewriteMap: bad path to txt map: ",
  2532. a2, NULL);
  2533. }
  2534. newmap->type = MAPTYPE_TXT;
  2535. newmap->datafile = fname;
  2536. newmap->checkfile = fname;
  2537. newmap->checkfile2= NULL;
  2538. newmap->cachename = apr_psprintf(cmd->pool, "%pp:%s",
  2539. (void *)cmd->server, a1);
  2540. }
  2541. newmap->fpin = NULL;
  2542. newmap->fpout = NULL;
  2543. if (newmap->checkfile && (sconf->state == ENGINE_ENABLED)
  2544. && (apr_stat(&st, newmap->checkfile, APR_FINFO_MIN,
  2545. cmd->pool) != APR_SUCCESS)) {
  2546. return apr_pstrcat(cmd->pool,
  2547. "RewriteMap: file for map ", a1,
  2548. " not found:", newmap->checkfile, NULL);
  2549. }
  2550. apr_hash_set(sconf->rewritemaps, a1, APR_HASH_KEY_STRING, newmap);
  2551. return NULL;
  2552. }
  2553. static const char *cmd_rewritelock(cmd_parms *cmd, void *dconf, const char *a1)
  2554. {
  2555. const char *error;
  2556. if ((error = ap_check_cmd_context(cmd, GLOBAL_ONLY)) != NULL)
  2557. return error;
  2558. /* fixup the path, especially for rewritelock_remove() */
  2559. lockname = ap_server_root_relative(cmd->pool, a1);
  2560. if (!lockname) {
  2561. return apr_pstrcat(cmd->pool, "Invalid RewriteLock path ", a1);
  2562. }
  2563. return NULL;
  2564. }
  2565. static const char *cmd_rewritebase(cmd_parms *cmd, void *in_dconf,
  2566. const char *a1)
  2567. {
  2568. rewrite_perdir_conf *dconf = in_dconf;
  2569. if (cmd->path == NULL || dconf == NULL) {
  2570. return "RewriteBase: only valid in per-directory config files";
  2571. }
  2572. if (a1[0] == '\0') {
  2573. return "RewriteBase: empty URL not allowed";
  2574. }
  2575. if (a1[0] != '/') {
  2576. return "RewriteBase: argument is not a valid URL";
  2577. }
  2578. dconf->baseurl = a1;
  2579. return NULL;
  2580. }
  2581. /*
  2582. * generic lexer for RewriteRule and RewriteCond flags.
  2583. * The parser will be passed in as a function pointer
  2584. * and called if a flag was found
  2585. */
  2586. static const char *cmd_parseflagfield(apr_pool_t *p, void *cfg, char *key,
  2587. const char *(*parse)(apr_pool_t *,
  2588. void *,
  2589. char *, char *))
  2590. {
  2591. char *val, *nextp, *endp;
  2592. const char *err;
  2593. endp = key + strlen(key) - 1;
  2594. if (*key != '[' || *endp != ']') {
  2595. return "bad flag delimiters";
  2596. }
  2597. *endp = ','; /* for simpler parsing */
  2598. ++key;
  2599. while (*key) {
  2600. /* skip leading spaces */
  2601. while (apr_isspace(*key)) {
  2602. ++key;
  2603. }
  2604. if (!*key || (nextp = ap_strchr(key, ',')) == NULL) { /* NULL should not
  2605. * happen, but ...
  2606. */
  2607. break;
  2608. }
  2609. /* strip trailing spaces */
  2610. endp = nextp - 1;
  2611. while (apr_isspace(*endp)) {
  2612. --endp;
  2613. }
  2614. *++endp = '\0';
  2615. /* split key and val */
  2616. val = ap_strchr(key, '=');
  2617. if (val) {
  2618. *val++ = '\0';
  2619. }
  2620. else {
  2621. val = endp;
  2622. }
  2623. err = parse(p, cfg, key, val);
  2624. if (err) {
  2625. return err;
  2626. }
  2627. key = nextp + 1;
  2628. }
  2629. return NULL;
  2630. }
  2631. static const char *cmd_rewritecond_setflag(apr_pool_t *p, void *_cfg,
  2632. char *key, char *val)
  2633. {
  2634. rewritecond_entry *cfg = _cfg;
  2635. if ( strcasecmp(key, "nocase") == 0
  2636. || strcasecmp(key, "NC") == 0 ) {
  2637. cfg->flags |= CONDFLAG_NOCASE;
  2638. }
  2639. else if ( strcasecmp(key, "ornext") == 0
  2640. || strcasecmp(key, "OR") == 0 ) {
  2641. cfg->flags |= CONDFLAG_ORNEXT;
  2642. }
  2643. else if ( strcasecmp(key, "novary") == 0
  2644. || strcasecmp(key, "NV") == 0 ) {
  2645. cfg->flags |= CONDFLAG_NOVARY;
  2646. }
  2647. else {
  2648. return apr_pstrcat(p, "unknown flag '", key, "'", NULL);
  2649. }
  2650. return NULL;
  2651. }
  2652. static const char *cmd_rewritecond(cmd_parms *cmd, void *in_dconf,
  2653. const char *in_str)
  2654. {
  2655. rewrite_perdir_conf *dconf = in_dconf;
  2656. char *str = apr_pstrdup(cmd->pool, in_str);
  2657. rewrite_server_conf *sconf;
  2658. rewritecond_entry *newcond;
  2659. ap_regex_t *regexp;
  2660. char *a1;
  2661. char *a2;
  2662. char *a3;
  2663. const char *err;
  2664. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2665. /* make a new entry in the internal temporary rewrite rule list */
  2666. if (cmd->path == NULL) { /* is server command */
  2667. newcond = apr_array_push(sconf->rewriteconds);
  2668. }
  2669. else { /* is per-directory command */
  2670. newcond = apr_array_push(dconf->rewriteconds);
  2671. }
  2672. /* parse the argument line ourself
  2673. * a1 .. a3 are substrings of str, which is a fresh copy
  2674. * of the argument line. So we can use a1 .. a3 without
  2675. * copying them again.
  2676. */
  2677. if (parseargline(str, &a1, &a2, &a3)) {
  2678. return apr_pstrcat(cmd->pool, "RewriteCond: bad argument line '", str,
  2679. "'", NULL);
  2680. }
  2681. /* arg1: the input string */
  2682. newcond->input = a1;
  2683. /* arg3: optional flags field
  2684. * (this has to be parsed first, because we need to
  2685. * know if the regex should be compiled with ICASE!)
  2686. */
  2687. newcond->flags = CONDFLAG_NONE;
  2688. if (a3 != NULL) {
  2689. if ((err = cmd_parseflagfield(cmd->pool, newcond, a3,
  2690. cmd_rewritecond_setflag)) != NULL) {
  2691. return apr_pstrcat(cmd->pool, "RewriteCond: ", err, NULL);
  2692. }
  2693. }
  2694. /* arg2: the pattern */
  2695. if (*a2 == '!') {
  2696. newcond->flags |= CONDFLAG_NOTMATCH;
  2697. ++a2;
  2698. }
  2699. /* determine the pattern type */
  2700. newcond->ptype = 0;
  2701. if (*a2 && a2[1]) {
  2702. if (!a2[2] && *a2 == '-') {
  2703. switch (a2[1]) {
  2704. case 'f': newcond->ptype = CONDPAT_FILE_EXISTS; break;
  2705. case 's': newcond->ptype = CONDPAT_FILE_SIZE; break;
  2706. case 'l': newcond->ptype = CONDPAT_FILE_LINK; break;
  2707. case 'd': newcond->ptype = CONDPAT_FILE_DIR; break;
  2708. case 'x': newcond->ptype = CONDPAT_FILE_XBIT; break;
  2709. case 'U': newcond->ptype = CONDPAT_LU_URL; break;
  2710. case 'F': newcond->ptype = CONDPAT_LU_FILE; break;
  2711. }
  2712. }
  2713. else {
  2714. switch (*a2) {
  2715. case '>': newcond->ptype = CONDPAT_STR_GT; break;
  2716. case '<': newcond->ptype = CONDPAT_STR_LT; break;
  2717. case '=': newcond->ptype = CONDPAT_STR_EQ;
  2718. /* "" represents an empty string */
  2719. if (*++a2 == '"' && a2[1] == '"' && !a2[2]) {
  2720. a2 += 2;
  2721. }
  2722. break;
  2723. }
  2724. }
  2725. }
  2726. if (newcond->ptype && newcond->ptype != CONDPAT_STR_EQ &&
  2727. (newcond->flags & CONDFLAG_NOCASE)) {
  2728. ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
  2729. "RewriteCond: NoCase option for non-regex pattern '%s' "
  2730. "is not supported and will be ignored.", a2);
  2731. newcond->flags &= ~CONDFLAG_NOCASE;
  2732. }
  2733. newcond->pattern = a2;
  2734. if (!newcond->ptype) {
  2735. regexp = ap_pregcomp(cmd->pool, a2,
  2736. AP_REG_EXTENDED | ((newcond->flags & CONDFLAG_NOCASE)
  2737. ? AP_REG_ICASE : 0));
  2738. if (!regexp) {
  2739. return apr_pstrcat(cmd->pool, "RewriteCond: cannot compile regular "
  2740. "expression '", a2, "'", NULL);
  2741. }
  2742. newcond->regexp = regexp;
  2743. }
  2744. return NULL;
  2745. }
  2746. static const char *cmd_rewriterule_setflag(apr_pool_t *p, void *_cfg,
  2747. char *key, char *val)
  2748. {
  2749. rewriterule_entry *cfg = _cfg;
  2750. int error = 0;
  2751. switch (*key++) {
  2752. case 'b':
  2753. case 'B':
  2754. if (!*key || !strcasecmp(key, "ackrefescaping")) {
  2755. cfg->flags |= RULEFLAG_ESCAPEBACKREF;
  2756. }
  2757. else {
  2758. ++error;
  2759. }
  2760. break;
  2761. case 'c':
  2762. case 'C':
  2763. if (!*key || !strcasecmp(key, "hain")) { /* chain */
  2764. cfg->flags |= RULEFLAG_CHAIN;
  2765. }
  2766. else if (((*key == 'O' || *key == 'o') && !key[1])
  2767. || !strcasecmp(key, "ookie")) { /* cookie */
  2768. data_item *cp = cfg->cookie;
  2769. if (!cp) {
  2770. cp = cfg->cookie = apr_palloc(p, sizeof(*cp));
  2771. }
  2772. else {
  2773. while (cp->next) {
  2774. cp = cp->next;
  2775. }
  2776. cp->next = apr_palloc(p, sizeof(*cp));
  2777. cp = cp->next;
  2778. }
  2779. cp->next = NULL;
  2780. cp->data = val;
  2781. }
  2782. else {
  2783. ++error;
  2784. }
  2785. break;
  2786. case 'd':
  2787. case 'D':
  2788. if (!*key || !strcasecmp(key, "PI") || !strcasecmp(key,"iscardpath")) {
  2789. cfg->flags |= (RULEFLAG_DISCARDPATHINFO);
  2790. }
  2791. break;
  2792. case 'e':
  2793. case 'E':
  2794. if (!*key || !strcasecmp(key, "nv")) { /* env */
  2795. data_item *cp = cfg->env;
  2796. if (!cp) {
  2797. cp = cfg->env = apr_palloc(p, sizeof(*cp));
  2798. }
  2799. else {
  2800. while (cp->next) {
  2801. cp = cp->next;
  2802. }
  2803. cp->next = apr_palloc(p, sizeof(*cp));
  2804. cp = cp->next;
  2805. }
  2806. cp->next = NULL;
  2807. cp->data = val;
  2808. }
  2809. else {
  2810. ++error;
  2811. }
  2812. break;
  2813. case 'f':
  2814. case 'F':
  2815. if (!*key || !strcasecmp(key, "orbidden")) { /* forbidden */
  2816. cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
  2817. cfg->forced_responsecode = HTTP_FORBIDDEN;
  2818. }
  2819. else {
  2820. ++error;
  2821. }
  2822. break;
  2823. case 'g':
  2824. case 'G':
  2825. if (!*key || !strcasecmp(key, "one")) { /* gone */
  2826. cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
  2827. cfg->forced_responsecode = HTTP_GONE;
  2828. }
  2829. else {
  2830. ++error;
  2831. }
  2832. break;
  2833. case 'h':
  2834. case 'H':
  2835. if (!*key || !strcasecmp(key, "andler")) { /* handler */
  2836. cfg->forced_handler = val;
  2837. }
  2838. else {
  2839. ++error;
  2840. }
  2841. break;
  2842. case 'l':
  2843. case 'L':
  2844. if (!*key || !strcasecmp(key, "ast")) { /* last */
  2845. cfg->flags |= RULEFLAG_LASTRULE;
  2846. }
  2847. else {
  2848. ++error;
  2849. }
  2850. break;
  2851. case 'n':
  2852. case 'N':
  2853. if (((*key == 'E' || *key == 'e') && !key[1])
  2854. || !strcasecmp(key, "oescape")) { /* noescape */
  2855. cfg->flags |= RULEFLAG_NOESCAPE;
  2856. }
  2857. else if (!*key || !strcasecmp(key, "ext")) { /* next */
  2858. cfg->flags |= RULEFLAG_NEWROUND;
  2859. }
  2860. else if (((*key == 'S' || *key == 's') && !key[1])
  2861. || !strcasecmp(key, "osubreq")) { /* nosubreq */
  2862. cfg->flags |= RULEFLAG_IGNOREONSUBREQ;
  2863. }
  2864. else if (((*key == 'C' || *key == 'c') && !key[1])
  2865. || !strcasecmp(key, "ocase")) { /* nocase */
  2866. cfg->flags |= RULEFLAG_NOCASE;
  2867. }
  2868. else {
  2869. ++error;
  2870. }
  2871. break;
  2872. case 'p':
  2873. case 'P':
  2874. if (!*key || !strcasecmp(key, "roxy")) { /* proxy */
  2875. cfg->flags |= RULEFLAG_PROXY;
  2876. }
  2877. else if (((*key == 'T' || *key == 't') && !key[1])
  2878. || !strcasecmp(key, "assthrough")) { /* passthrough */
  2879. cfg->flags |= RULEFLAG_PASSTHROUGH;
  2880. }
  2881. else {
  2882. ++error;
  2883. }
  2884. break;
  2885. case 'q':
  2886. case 'Q':
  2887. if ( !strcasecmp(key, "SA")
  2888. || !strcasecmp(key, "sappend")) { /* qsappend */
  2889. cfg->flags |= RULEFLAG_QSAPPEND;
  2890. }
  2891. else {
  2892. ++error;
  2893. }
  2894. break;
  2895. case 'r':
  2896. case 'R':
  2897. if (!*key || !strcasecmp(key, "edirect")) { /* redirect */
  2898. int status = 0;
  2899. cfg->flags |= RULEFLAG_FORCEREDIRECT;
  2900. if (strlen(val) > 0) {
  2901. if (strcasecmp(val, "permanent") == 0) {
  2902. status = HTTP_MOVED_PERMANENTLY;
  2903. }
  2904. else if (strcasecmp(val, "temp") == 0) {
  2905. status = HTTP_MOVED_TEMPORARILY;
  2906. }
  2907. else if (strcasecmp(val, "seeother") == 0) {
  2908. status = HTTP_SEE_OTHER;
  2909. }
  2910. else if (apr_isdigit(*val)) {
  2911. status = atoi(val);
  2912. if (status != HTTP_INTERNAL_SERVER_ERROR) {
  2913. int idx =
  2914. ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
  2915. if (ap_index_of_response(status) == idx) {
  2916. return apr_psprintf(p, "invalid HTTP "
  2917. "response code '%s' for "
  2918. "flag 'R'",
  2919. val);
  2920. }
  2921. }
  2922. if (!ap_is_HTTP_REDIRECT(status)) {
  2923. cfg->flags |= (RULEFLAG_STATUS | RULEFLAG_NOSUB);
  2924. }
  2925. }
  2926. cfg->forced_responsecode = status;
  2927. }
  2928. }
  2929. else {
  2930. ++error;
  2931. }
  2932. break;
  2933. case 's':
  2934. case 'S':
  2935. if (!*key || !strcasecmp(key, "kip")) { /* skip */
  2936. cfg->skip = atoi(val);
  2937. }
  2938. else {
  2939. ++error;
  2940. }
  2941. break;
  2942. case 't':
  2943. case 'T':
  2944. if (!*key || !strcasecmp(key, "ype")) { /* type */
  2945. cfg->forced_mimetype = val;
  2946. }
  2947. else {
  2948. ++error;
  2949. }
  2950. break;
  2951. default:
  2952. ++error;
  2953. break;
  2954. }
  2955. if (error) {
  2956. return apr_pstrcat(p, "unknown flag '", --key, "'", NULL);
  2957. }
  2958. return NULL;
  2959. }
  2960. static const char *cmd_rewriterule(cmd_parms *cmd, void *in_dconf,
  2961. const char *in_str)
  2962. {
  2963. rewrite_perdir_conf *dconf = in_dconf;
  2964. char *str = apr_pstrdup(cmd->pool, in_str);
  2965. rewrite_server_conf *sconf;
  2966. rewriterule_entry *newrule;
  2967. ap_regex_t *regexp;
  2968. char *a1;
  2969. char *a2;
  2970. char *a3;
  2971. const char *err;
  2972. sconf = ap_get_module_config(cmd->server->module_config, &rewrite_module);
  2973. /* make a new entry in the internal rewrite rule list */
  2974. if (cmd->path == NULL) { /* is server command */
  2975. newrule = apr_array_push(sconf->rewriterules);
  2976. }
  2977. else { /* is per-directory command */
  2978. newrule = apr_array_push(dconf->rewriterules);
  2979. }
  2980. /* parse the argument line ourself */
  2981. if (parseargline(str, &a1, &a2, &a3)) {
  2982. return apr_pstrcat(cmd->pool, "RewriteRule: bad argument line '", str,
  2983. "'", NULL);
  2984. }
  2985. /* arg3: optional flags field */
  2986. newrule->forced_mimetype = NULL;
  2987. newrule->forced_handler = NULL;
  2988. newrule->forced_responsecode = HTTP_MOVED_TEMPORARILY;
  2989. newrule->flags = RULEFLAG_NONE;
  2990. newrule->env = NULL;
  2991. newrule->cookie = NULL;
  2992. newrule->skip = 0;
  2993. if (a3 != NULL) {
  2994. if ((err = cmd_parseflagfield(cmd->pool, newrule, a3,
  2995. cmd_rewriterule_setflag)) != NULL) {
  2996. return apr_pstrcat(cmd->pool, "RewriteRule: ", err, NULL);
  2997. }
  2998. }
  2999. /* arg1: the pattern
  3000. * try to compile the regexp to test if is ok
  3001. */
  3002. if (*a1 == '!') {
  3003. newrule->flags |= RULEFLAG_NOTMATCH;
  3004. ++a1;
  3005. }
  3006. regexp = ap_pregcomp(cmd->pool, a1, AP_REG_EXTENDED |
  3007. ((newrule->flags & RULEFLAG_NOCASE)
  3008. ? AP_REG_ICASE : 0));
  3009. if (!regexp) {
  3010. return apr_pstrcat(cmd->pool,
  3011. "RewriteRule: cannot compile regular expression '",
  3012. a1, "'", NULL);
  3013. }
  3014. newrule->pattern = a1;
  3015. newrule->regexp = regexp;
  3016. /* arg2: the output string */
  3017. newrule->output = a2;
  3018. if (*a2 == '-' && !a2[1]) {
  3019. newrule->flags |= RULEFLAG_NOSUB;
  3020. }
  3021. /* now, if the server or per-dir config holds an
  3022. * array of RewriteCond entries, we take it for us
  3023. * and clear the array
  3024. */
  3025. if (cmd->path == NULL) { /* is server command */
  3026. newrule->rewriteconds = sconf->rewriteconds;
  3027. sconf->rewriteconds = apr_array_make(cmd->pool, 2,
  3028. sizeof(rewritecond_entry));
  3029. }
  3030. else { /* is per-directory command */
  3031. newrule->rewriteconds = dconf->rewriteconds;
  3032. dconf->rewriteconds = apr_array_make(cmd->pool, 2,
  3033. sizeof(rewritecond_entry));
  3034. }
  3035. return NULL;
  3036. }
  3037. /*
  3038. * +-------------------------------------------------------+
  3039. * | |
  3040. * | the rewriting engine
  3041. * | |
  3042. * +-------------------------------------------------------+
  3043. */
  3044. /* Lexicographic Compare */
  3045. static APR_INLINE int compare_lexicography(char *a, char *b)
  3046. {
  3047. apr_size_t i, lena, lenb;
  3048. lena = strlen(a);
  3049. lenb = strlen(b);
  3050. if (lena == lenb) {
  3051. for (i = 0; i < lena; ++i) {
  3052. if (a[i] != b[i]) {
  3053. return ((unsigned char)a[i] > (unsigned char)b[i]) ? 1 : -1;
  3054. }
  3055. }
  3056. return 0;
  3057. }
  3058. return ((lena > lenb) ? 1 : -1);
  3059. }
  3060. /*
  3061. * Apply a single rewriteCond
  3062. */
  3063. static int apply_rewrite_cond(rewritecond_entry *p, rewrite_ctx *ctx)
  3064. {
  3065. char *input = do_expand(p->input, ctx, NULL);
  3066. apr_finfo_t sb;
  3067. request_rec *rsub, *r = ctx->r;
  3068. ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
  3069. int rc = 0;
  3070. switch (p->ptype) {
  3071. case CONDPAT_FILE_EXISTS:
  3072. if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
  3073. && sb.filetype == APR_REG) {
  3074. rc = 1;
  3075. }
  3076. break;
  3077. case CONDPAT_FILE_SIZE:
  3078. if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
  3079. && sb.filetype == APR_REG && sb.size > 0) {
  3080. rc = 1;
  3081. }
  3082. break;
  3083. case CONDPAT_FILE_LINK:
  3084. #if !defined(OS2)
  3085. if ( apr_stat(&sb, input, APR_FINFO_MIN | APR_FINFO_LINK,
  3086. r->pool) == APR_SUCCESS
  3087. && sb.filetype == APR_LNK) {
  3088. rc = 1;
  3089. }
  3090. #endif
  3091. break;
  3092. case CONDPAT_FILE_DIR:
  3093. if ( apr_stat(&sb, input, APR_FINFO_MIN, r->pool) == APR_SUCCESS
  3094. && sb.filetype == APR_DIR) {
  3095. rc = 1;
  3096. }
  3097. break;
  3098. case CONDPAT_FILE_XBIT:
  3099. if ( apr_stat(&sb, input, APR_FINFO_PROT, r->pool) == APR_SUCCESS
  3100. && (sb.protection & (APR_UEXECUTE | APR_GEXECUTE | APR_WEXECUTE))) {
  3101. rc = 1;
  3102. }
  3103. break;
  3104. case CONDPAT_LU_URL:
  3105. if (*input && subreq_ok(r)) {
  3106. rsub = ap_sub_req_lookup_uri(input, r, NULL);
  3107. if (rsub->status < 400) {
  3108. rc = 1;
  3109. }
  3110. rewritelog((r, 5, NULL, "RewriteCond URI (-U) check: "
  3111. "path=%s -> status=%d", input, rsub->status));
  3112. ap_destroy_sub_req(rsub);
  3113. }
  3114. break;
  3115. case CONDPAT_LU_FILE:
  3116. if (*input && subreq_ok(r)) {
  3117. rsub = ap_sub_req_lookup_file(input, r, NULL);
  3118. if (rsub->status < 300 &&
  3119. /* double-check that file exists since default result is 200 */
  3120. apr_stat(&sb, rsub->filename, APR_FINFO_MIN,
  3121. r->pool) == APR_SUCCESS) {
  3122. rc = 1;
  3123. }
  3124. rewritelog((r, 5, NULL, "RewriteCond file (-F) check: path=%s "
  3125. "-> file=%s status=%d", input, rsub->filename,
  3126. rsub->status));
  3127. ap_destroy_sub_req(rsub);
  3128. }
  3129. break;
  3130. case CONDPAT_STR_GT:
  3131. rc = (compare_lexicography(input, p->pattern+1) == 1) ? 1 : 0;
  3132. break;
  3133. case CONDPAT_STR_LT:
  3134. rc = (compare_lexicography(input, p->pattern+1) == -1) ? 1 : 0;
  3135. break;
  3136. case CONDPAT_STR_EQ:
  3137. if (p->flags & CONDFLAG_NOCASE) {
  3138. rc = !strcasecmp(input, p->pattern);
  3139. }
  3140. else {
  3141. rc = !strcmp(input, p->pattern);
  3142. }
  3143. break;
  3144. default:
  3145. /* it is really a regexp pattern, so apply it */
  3146. rc = !ap_regexec(p->regexp, input, AP_MAX_REG_MATCH, regmatch, 0);
  3147. /* update briRC backref info */
  3148. if (rc && !(p->flags & CONDFLAG_NOTMATCH)) {
  3149. ctx->briRC.source = input;
  3150. ctx->briRC.nsub = p->regexp->re_nsub;
  3151. memcpy(ctx->briRC.regmatch, regmatch, sizeof(regmatch));
  3152. }
  3153. break;
  3154. }
  3155. if (p->flags & CONDFLAG_NOTMATCH) {
  3156. rc = !rc;
  3157. }
  3158. rewritelog((r, 4, ctx->perdir, "RewriteCond: input='%s' pattern='%s%s%s'%s "
  3159. "=> %s", input, (p->flags & CONDFLAG_NOTMATCH) ? "!" : "",
  3160. (p->ptype == CONDPAT_STR_EQ) ? "=" : "", p->pattern,
  3161. (p->flags & CONDFLAG_NOCASE) ? " [NC]" : "",
  3162. rc ? "matched" : "not-matched"));
  3163. return rc;
  3164. }
  3165. /* check for forced type and handler */
  3166. static APR_INLINE void force_type_handler(rewriterule_entry *p,
  3167. rewrite_ctx *ctx)
  3168. {
  3169. char *expanded;
  3170. if (p->forced_mimetype) {
  3171. expanded = do_expand(p->forced_mimetype, ctx, p);
  3172. if (*expanded) {
  3173. ap_str_tolower(expanded);
  3174. rewritelog((ctx->r, 2, ctx->perdir, "remember %s to have MIME-type "
  3175. "'%s'", ctx->r->filename, expanded));
  3176. apr_table_setn(ctx->r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR,
  3177. expanded);
  3178. }
  3179. }
  3180. if (p->forced_handler) {
  3181. expanded = do_expand(p->forced_handler, ctx, p);
  3182. if (*expanded) {
  3183. ap_str_tolower(expanded);
  3184. rewritelog((ctx->r, 2, ctx->perdir, "remember %s to have "
  3185. "Content-handler '%s'", ctx->r->filename, expanded));
  3186. apr_table_setn(ctx->r->notes, REWRITE_FORCED_HANDLER_NOTEVAR,
  3187. expanded);
  3188. }
  3189. }
  3190. }
  3191. /*
  3192. * Apply a single RewriteRule
  3193. */
  3194. static int apply_rewrite_rule(rewriterule_entry *p, rewrite_ctx *ctx)
  3195. {
  3196. ap_regmatch_t regmatch[AP_MAX_REG_MATCH];
  3197. apr_array_header_t *rewriteconds;
  3198. rewritecond_entry *conds;
  3199. int i, rc;
  3200. char *newuri = NULL;
  3201. request_rec *r = ctx->r;
  3202. int is_proxyreq = 0;
  3203. ctx->uri = r->filename;
  3204. if (ctx->perdir) {
  3205. apr_size_t dirlen = strlen(ctx->perdir);
  3206. /*
  3207. * Proxy request?
  3208. */
  3209. is_proxyreq = ( r->proxyreq && r->filename
  3210. && !strncmp(r->filename, "proxy:", 6));
  3211. /* Since we want to match against the (so called) full URL, we have
  3212. * to re-add the PATH_INFO postfix
  3213. */
  3214. if (r->path_info && *r->path_info) {
  3215. rewritelog((r, 3, ctx->perdir, "add path info postfix: %s -> %s%s",
  3216. ctx->uri, ctx->uri, r->path_info));
  3217. ctx->uri = apr_pstrcat(r->pool, ctx->uri, r->path_info, NULL);
  3218. }
  3219. /* Additionally we strip the physical path from the url to match
  3220. * it independent from the underlaying filesystem.
  3221. */
  3222. if (!is_proxyreq && strlen(ctx->uri) >= dirlen &&
  3223. !strncmp(ctx->uri, ctx->perdir, dirlen)) {
  3224. rewritelog((r, 3, ctx->perdir, "strip per-dir prefix: %s -> %s",
  3225. ctx->uri, ctx->uri + dirlen));
  3226. ctx->uri = ctx->uri + dirlen;
  3227. }
  3228. }
  3229. /* Try to match the URI against the RewriteRule pattern
  3230. * and exit immediately if it didn't apply.
  3231. */
  3232. rewritelog((r, 3, ctx->perdir, "applying pattern '%s' to uri '%s'",
  3233. p->pattern, ctx->uri));
  3234. rc = !ap_regexec(p->regexp, ctx->uri, AP_MAX_REG_MATCH, regmatch, 0);
  3235. if (! (( rc && !(p->flags & RULEFLAG_NOTMATCH)) ||
  3236. (!rc && (p->flags & RULEFLAG_NOTMATCH)) ) ) {
  3237. return 0;
  3238. }
  3239. /* It matched, wow! Now it's time to prepare the context structure for
  3240. * further processing
  3241. */
  3242. ctx->vary_this = NULL;
  3243. ctx->briRC.source = NULL;
  3244. if (p->flags & RULEFLAG_NOTMATCH) {
  3245. ctx->briRR.source = NULL;
  3246. }
  3247. else {
  3248. ctx->briRR.source = apr_pstrdup(r->pool, ctx->uri);
  3249. ctx->briRR.nsub = p->regexp->re_nsub;
  3250. memcpy(ctx->briRR.regmatch, regmatch, sizeof(regmatch));
  3251. }
  3252. /* Ok, we already know the pattern has matched, but we now
  3253. * additionally have to check for all existing preconditions
  3254. * (RewriteCond) which have to be also true. We do this at
  3255. * this very late stage to avoid unnessesary checks which
  3256. * would slow down the rewriting engine.
  3257. */
  3258. rewriteconds = p->rewriteconds;
  3259. conds = (rewritecond_entry *)rewriteconds->elts;
  3260. for (i = 0; i < rewriteconds->nelts; ++i) {
  3261. rewritecond_entry *c = &conds[i];
  3262. rc = apply_rewrite_cond(c, ctx);
  3263. /*
  3264. * Reset vary_this if the novary flag is set for this condition.
  3265. */
  3266. if (c->flags & CONDFLAG_NOVARY) {
  3267. ctx->vary_this = NULL;
  3268. }
  3269. if (c->flags & CONDFLAG_ORNEXT) {
  3270. if (!rc) {
  3271. /* One condition is false, but another can be still true. */
  3272. ctx->vary_this = NULL;
  3273. continue;
  3274. }
  3275. else {
  3276. /* skip the rest of the chained OR conditions */
  3277. while ( i < rewriteconds->nelts
  3278. && c->flags & CONDFLAG_ORNEXT) {
  3279. c = &conds[++i];
  3280. }
  3281. }
  3282. }
  3283. else if (!rc) {
  3284. return 0;
  3285. }
  3286. /* If some HTTP header was involved in the condition, remember it
  3287. * for later use
  3288. */
  3289. if (ctx->vary_this) {
  3290. ctx->vary = ctx->vary
  3291. ? apr_pstrcat(r->pool, ctx->vary, ", ", ctx->vary_this,
  3292. NULL)
  3293. : ctx->vary_this;
  3294. ctx->vary_this = NULL;
  3295. }
  3296. }
  3297. /* expand the result */
  3298. if (!(p->flags & RULEFLAG_NOSUB)) {
  3299. newuri = do_expand(p->output, ctx, p);
  3300. rewritelog((r, 2, ctx->perdir, "rewrite '%s' -> '%s'", ctx->uri,
  3301. newuri));
  3302. }
  3303. /* expand [E=var:val] and [CO=<cookie>] */
  3304. do_expand_env(p->env, ctx);
  3305. do_expand_cookie(p->cookie, ctx);
  3306. /* non-substitution rules ('RewriteRule <pat> -') end here. */
  3307. if (p->flags & RULEFLAG_NOSUB) {
  3308. force_type_handler(p, ctx);
  3309. if (p->flags & RULEFLAG_STATUS) {
  3310. rewritelog((r, 2, ctx->perdir, "forcing responsecode %d for %s",
  3311. p->forced_responsecode, r->filename));
  3312. r->status = p->forced_responsecode;
  3313. }
  3314. return 2;
  3315. }
  3316. /* Now adjust API's knowledge about r->filename and r->args */
  3317. r->filename = newuri;
  3318. if (ctx->perdir && (p->flags & RULEFLAG_DISCARDPATHINFO)) {
  3319. r->path_info = NULL;
  3320. }
  3321. splitout_queryargs(r, p->flags & RULEFLAG_QSAPPEND);
  3322. /* Add the previously stripped per-directory location prefix, unless
  3323. * (1) it's an absolute URL path and
  3324. * (2) it's a full qualified URL
  3325. */
  3326. if ( ctx->perdir && !is_proxyreq && *r->filename != '/'
  3327. && !is_absolute_uri(r->filename)) {
  3328. rewritelog((r, 3, ctx->perdir, "add per-dir prefix: %s -> %s%s",
  3329. r->filename, ctx->perdir, r->filename));
  3330. r->filename = apr_pstrcat(r->pool, ctx->perdir, r->filename, NULL);
  3331. }
  3332. /* If this rule is forced for proxy throughput
  3333. * (`RewriteRule ... ... [P]') then emulate mod_proxy's
  3334. * URL-to-filename handler to be sure mod_proxy is triggered
  3335. * for this URL later in the Apache API. But make sure it is
  3336. * a fully-qualified URL. (If not it is qualified with
  3337. * ourself).
  3338. */
  3339. if (p->flags & RULEFLAG_PROXY) {
  3340. /* For rules evaluated in server context, the mod_proxy fixup
  3341. * hook can be relied upon to escape the URI as and when
  3342. * necessary, since it occurs later. If in directory context,
  3343. * the ordering of the fixup hooks is forced such that
  3344. * mod_proxy comes first, so the URI must be escaped here
  3345. * instead. See PR 39746, 46428, and other headaches. */
  3346. if (ctx->perdir && (p->flags & RULEFLAG_NOESCAPE) == 0) {
  3347. char *old_filename = r->filename;
  3348. r->filename = ap_escape_uri(r->pool, r->filename);
  3349. rewritelog((r, 2, ctx->perdir, "escaped URI in per-dir context "
  3350. "for proxy, %s -> %s", old_filename, r->filename));
  3351. }
  3352. fully_qualify_uri(r);
  3353. rewritelog((r, 2, ctx->perdir, "forcing proxy-throughput with %s",
  3354. r->filename));
  3355. r->filename = apr_pstrcat(r->pool, "proxy:", r->filename, NULL);
  3356. return 1;
  3357. }
  3358. /* If this rule is explicitly forced for HTTP redirection
  3359. * (`RewriteRule .. .. [R]') then force an external HTTP
  3360. * redirect. But make sure it is a fully-qualified URL. (If
  3361. * not it is qualified with ourself).
  3362. */
  3363. if (p->flags & RULEFLAG_FORCEREDIRECT) {
  3364. fully_qualify_uri(r);
  3365. rewritelog((r, 2, ctx->perdir, "explicitly forcing redirect with %s",
  3366. r->filename));
  3367. r->status = p->forced_responsecode;
  3368. return 1;
  3369. }
  3370. /* Special Rewriting Feature: Self-Reduction
  3371. * We reduce the URL by stripping a possible
  3372. * http[s]://<ourhost>[:<port>] prefix, i.e. a prefix which
  3373. * corresponds to ourself. This is to simplify rewrite maps
  3374. * and to avoid recursion, etc. When this prefix is not a
  3375. * coincidence then the user has to use [R] explicitly (see
  3376. * above).
  3377. */
  3378. reduce_uri(r);
  3379. /* If this rule is still implicitly forced for HTTP
  3380. * redirection (`RewriteRule .. <scheme>://...') then
  3381. * directly force an external HTTP redirect.
  3382. */
  3383. if (is_absolute_uri(r->filename)) {
  3384. rewritelog((r, 2, ctx->perdir, "implicitly forcing redirect (rc=%d) "
  3385. "with %s", p->forced_responsecode, r->filename));
  3386. r->status = p->forced_responsecode;
  3387. return 1;
  3388. }
  3389. /* Finally remember the forced mime-type */
  3390. force_type_handler(p, ctx);
  3391. /* Puuhhhhhhhh... WHAT COMPLICATED STUFF ;_)
  3392. * But now we're done for this particular rule.
  3393. */
  3394. return 1;
  3395. }
  3396. /*
  3397. * Apply a complete rule set,
  3398. * i.e. a list of rewrite rules
  3399. */
  3400. static int apply_rewrite_list(request_rec *r, apr_array_header_t *rewriterules,
  3401. char *perdir)
  3402. {
  3403. rewriterule_entry *entries;
  3404. rewriterule_entry *p;
  3405. int i;
  3406. int changed;
  3407. int rc;
  3408. int s;
  3409. rewrite_ctx *ctx;
  3410. ctx = apr_palloc(r->pool, sizeof(*ctx));
  3411. ctx->perdir = perdir;
  3412. ctx->r = r;
  3413. /*
  3414. * Iterate over all existing rules
  3415. */
  3416. entries = (rewriterule_entry *)rewriterules->elts;
  3417. changed = 0;
  3418. loop:
  3419. for (i = 0; i < rewriterules->nelts; i++) {
  3420. p = &entries[i];
  3421. /*
  3422. * Ignore this rule on subrequests if we are explicitly
  3423. * asked to do so or this is a proxy-throughput or a
  3424. * forced redirect rule.
  3425. */
  3426. if (r->main != NULL &&
  3427. (p->flags & RULEFLAG_IGNOREONSUBREQ ||
  3428. p->flags & RULEFLAG_FORCEREDIRECT )) {
  3429. continue;
  3430. }
  3431. /*
  3432. * Apply the current rule.
  3433. */
  3434. ctx->vary = NULL;
  3435. rc = apply_rewrite_rule(p, ctx);
  3436. if (rc) {
  3437. /* Regardless of what we do next, we've found a match. Check to see
  3438. * if any of the request header fields were involved, and add them
  3439. * to the Vary field of the response.
  3440. */
  3441. if (ctx->vary) {
  3442. apr_table_merge(r->headers_out, "Vary", ctx->vary);
  3443. }
  3444. /*
  3445. * The rule sets the response code (implies match-only)
  3446. */
  3447. if (p->flags & RULEFLAG_STATUS) {
  3448. return ACTION_STATUS;
  3449. }
  3450. /*
  3451. * Indicate a change if this was not a match-only rule.
  3452. */
  3453. if (rc != 2) {
  3454. changed = ((p->flags & RULEFLAG_NOESCAPE)
  3455. ? ACTION_NOESCAPE : ACTION_NORMAL);
  3456. }
  3457. /*
  3458. * Pass-Through Feature (`RewriteRule .. .. [PT]'):
  3459. * Because the Apache 1.x API is very limited we
  3460. * need this hack to pass the rewritten URL to other
  3461. * modules like mod_alias, mod_userdir, etc.
  3462. */
  3463. if (p->flags & RULEFLAG_PASSTHROUGH) {
  3464. rewritelog((r, 2, perdir, "forcing '%s' to get passed through "
  3465. "to next API URI-to-filename handler", r->filename));
  3466. r->filename = apr_pstrcat(r->pool, "passthrough:",
  3467. r->filename, NULL);
  3468. changed = ACTION_NORMAL;
  3469. break;
  3470. }
  3471. /*
  3472. * Stop processing also on proxy pass-through and
  3473. * last-rule and new-round flags.
  3474. */
  3475. if (p->flags & (RULEFLAG_PROXY | RULEFLAG_LASTRULE)) {
  3476. break;
  3477. }
  3478. /*
  3479. * On "new-round" flag we just start from the top of
  3480. * the rewriting ruleset again.
  3481. */
  3482. if (p->flags & RULEFLAG_NEWROUND) {
  3483. goto loop;
  3484. }
  3485. /*
  3486. * If we are forced to skip N next rules, do it now.
  3487. */
  3488. if (p->skip > 0) {
  3489. s = p->skip;
  3490. while ( i < rewriterules->nelts
  3491. && s > 0) {
  3492. i++;
  3493. p = &entries[i];
  3494. s--;
  3495. }
  3496. }
  3497. }
  3498. else {
  3499. /*
  3500. * If current rule is chained with next rule(s),
  3501. * skip all this next rule(s)
  3502. */
  3503. while ( i < rewriterules->nelts
  3504. && p->flags & RULEFLAG_CHAIN) {
  3505. i++;
  3506. p = &entries[i];
  3507. }
  3508. }
  3509. }
  3510. return changed;
  3511. }
  3512. /*
  3513. * +-------------------------------------------------------+
  3514. * | |
  3515. * | Module Initialization Hooks
  3516. * | |
  3517. * +-------------------------------------------------------+
  3518. */
  3519. static int pre_config(apr_pool_t *pconf,
  3520. apr_pool_t *plog,
  3521. apr_pool_t *ptemp)
  3522. {
  3523. APR_OPTIONAL_FN_TYPE(ap_register_rewrite_mapfunc) *map_pfn_register;
  3524. /* register int: rewritemap handlers */
  3525. map_pfn_register = APR_RETRIEVE_OPTIONAL_FN(ap_register_rewrite_mapfunc);
  3526. if (map_pfn_register) {
  3527. map_pfn_register("tolower", rewrite_mapfunc_tolower);
  3528. map_pfn_register("toupper", rewrite_mapfunc_toupper);
  3529. map_pfn_register("escape", rewrite_mapfunc_escape);
  3530. map_pfn_register("unescape", rewrite_mapfunc_unescape);
  3531. }
  3532. return OK;
  3533. }
  3534. static int post_config(apr_pool_t *p,
  3535. apr_pool_t *plog,
  3536. apr_pool_t *ptemp,
  3537. server_rec *s)
  3538. {
  3539. apr_status_t rv;
  3540. void *data;
  3541. int first_time = 0;
  3542. const char *userdata_key = "rewrite_init_module";
  3543. apr_pool_userdata_get(&data, userdata_key, s->process->pool);
  3544. if (!data) {
  3545. first_time = 1;
  3546. apr_pool_userdata_set((const void *)1, userdata_key,
  3547. apr_pool_cleanup_null, s->process->pool);
  3548. }
  3549. /* check if proxy module is available */
  3550. proxy_available = (ap_find_linked_module("mod_proxy.c") != NULL);
  3551. rv = rewritelock_create(s, p);
  3552. if (rv != APR_SUCCESS) {
  3553. return HTTP_INTERNAL_SERVER_ERROR;
  3554. }
  3555. apr_pool_cleanup_register(p, (void *)s, rewritelock_remove,
  3556. apr_pool_cleanup_null);
  3557. /* step through the servers and
  3558. * - open each rewriting logfile
  3559. * - open the RewriteMap prg:xxx programs
  3560. */
  3561. for (; s; s = s->next) {
  3562. #ifndef REWRITELOG_DISABLED
  3563. if (!open_rewritelog(s, p)) {
  3564. return HTTP_INTERNAL_SERVER_ERROR;
  3565. }
  3566. #endif
  3567. if (!first_time) {
  3568. if (run_rewritemap_programs(s, p) != APR_SUCCESS) {
  3569. return HTTP_INTERNAL_SERVER_ERROR;
  3570. }
  3571. }
  3572. }
  3573. rewrite_ssl_lookup = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
  3574. rewrite_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);
  3575. return OK;
  3576. }
  3577. static void init_child(apr_pool_t *p, server_rec *s)
  3578. {
  3579. apr_status_t rv = 0; /* get a rid of gcc warning (REWRITELOG_DISABLED) */
  3580. if (lockname != NULL && *(lockname) != '\0') {
  3581. rv = apr_global_mutex_child_init(&rewrite_mapr_lock_acquire,
  3582. lockname, p);
  3583. if (rv != APR_SUCCESS) {
  3584. ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
  3585. "mod_rewrite: could not init rewrite_mapr_lock_acquire"
  3586. " in child");
  3587. }
  3588. }
  3589. /* create the lookup cache */
  3590. if (!init_cache(p)) {
  3591. ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
  3592. "mod_rewrite: could not init map cache in child");
  3593. }
  3594. }
  3595. /*
  3596. * +-------------------------------------------------------+
  3597. * | |
  3598. * | runtime hooks
  3599. * | |
  3600. * +-------------------------------------------------------+
  3601. */
  3602. /*
  3603. * URI-to-filename hook
  3604. * [deals with RewriteRules in server context]
  3605. */
  3606. static int hook_uri2file(request_rec *r)
  3607. {
  3608. rewrite_server_conf *conf;
  3609. const char *saved_rulestatus;
  3610. const char *var;
  3611. const char *thisserver;
  3612. char *thisport;
  3613. const char *thisurl;
  3614. unsigned int port;
  3615. int rulestatus;
  3616. /*
  3617. * retrieve the config structures
  3618. */
  3619. conf = ap_get_module_config(r->server->module_config, &rewrite_module);
  3620. /*
  3621. * only do something under runtime if the engine is really enabled,
  3622. * else return immediately!
  3623. */
  3624. if (conf->state == ENGINE_DISABLED) {
  3625. return DECLINED;
  3626. }
  3627. /*
  3628. * check for the ugly API case of a virtual host section where no
  3629. * mod_rewrite directives exists. In this situation we became no chance
  3630. * by the API to setup our default per-server config so we have to
  3631. * on-the-fly assume we have the default config. But because the default
  3632. * config has a disabled rewriting engine we are lucky because can
  3633. * just stop operating now.
  3634. */
  3635. if (conf->server != r->server) {
  3636. return DECLINED;
  3637. }
  3638. if ((r->unparsed_uri[0] == '*' && r->unparsed_uri[1] == '\0')
  3639. || !r->uri || r->uri[0] != '/') {
  3640. return DECLINED;
  3641. }
  3642. /*
  3643. * add the SCRIPT_URL variable to the env. this is a bit complicated
  3644. * due to the fact that apache uses subrequests and internal redirects
  3645. */
  3646. if (r->main == NULL) {
  3647. var = apr_table_get(r->subprocess_env, REDIRECT_ENVVAR_SCRIPT_URL);
  3648. if (var == NULL) {
  3649. apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, r->uri);
  3650. }
  3651. else {
  3652. apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
  3653. }
  3654. }
  3655. else {
  3656. var = apr_table_get(r->main->subprocess_env, ENVVAR_SCRIPT_URL);
  3657. apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URL, var);
  3658. }
  3659. /*
  3660. * create the SCRIPT_URI variable for the env
  3661. */
  3662. /* add the canonical URI of this URL */
  3663. thisserver = ap_get_server_name(r);
  3664. port = ap_get_server_port(r);
  3665. if (ap_is_default_port(port, r)) {
  3666. thisport = "";
  3667. }
  3668. else {
  3669. thisport = apr_psprintf(r->pool, ":%u", port);
  3670. }
  3671. thisurl = apr_table_get(r->subprocess_env, ENVVAR_SCRIPT_URL);
  3672. /* set the variable */
  3673. var = apr_pstrcat(r->pool, ap_http_scheme(r), "://", thisserver, thisport,
  3674. thisurl, NULL);
  3675. apr_table_setn(r->subprocess_env, ENVVAR_SCRIPT_URI, var);
  3676. if (!(saved_rulestatus = apr_table_get(r->notes,"mod_rewrite_rewritten"))) {
  3677. /* if filename was not initially set,
  3678. * we start with the requested URI
  3679. */
  3680. if (r->filename == NULL) {
  3681. r->filename = apr_pstrdup(r->pool, r->uri);
  3682. rewritelog((r, 2, NULL, "init rewrite engine with requested uri %s",
  3683. r->filename));
  3684. }
  3685. else {
  3686. rewritelog((r, 2, NULL, "init rewrite engine with passed filename "
  3687. "%s. Original uri = %s", r->filename, r->uri));
  3688. }
  3689. /*
  3690. * now apply the rules ...
  3691. */
  3692. rulestatus = apply_rewrite_list(r, conf->rewriterules, NULL);
  3693. apr_table_set(r->notes,"mod_rewrite_rewritten",
  3694. apr_psprintf(r->pool,"%d",rulestatus));
  3695. }
  3696. else {
  3697. rewritelog((r, 2, NULL, "uri already rewritten. Status %s, Uri %s, "
  3698. "r->filename %s", saved_rulestatus, r->uri, r->filename));
  3699. rulestatus = atoi(saved_rulestatus);
  3700. }
  3701. if (rulestatus) {
  3702. unsigned skip;
  3703. apr_size_t flen;
  3704. if (ACTION_STATUS == rulestatus) {
  3705. int n = r->status;
  3706. r->status = HTTP_OK;
  3707. return n;
  3708. }
  3709. flen = r->filename ? strlen(r->filename) : 0;
  3710. if (flen > 6 && strncmp(r->filename, "proxy:", 6) == 0) {
  3711. /* it should be go on as an internal proxy request */
  3712. /* check if the proxy module is enabled, so
  3713. * we can actually use it!
  3714. */
  3715. if (!proxy_available) {
  3716. ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
  3717. "attempt to make remote request from mod_rewrite "
  3718. "without proxy enabled: %s", r->filename);
  3719. return HTTP_FORBIDDEN;
  3720. }
  3721. if (rulestatus == ACTION_NOESCAPE) {
  3722. apr_table_setn(r->notes, "proxy-nocanon", "1");
  3723. }
  3724. /* make sure the QUERY_STRING and
  3725. * PATH_INFO parts get incorporated
  3726. */
  3727. if (r->path_info != NULL) {
  3728. r->filename = apr_pstrcat(r->pool, r->filename,
  3729. r->path_info, NULL);
  3730. }
  3731. if ((r->args != NULL)
  3732. && ((r->proxyreq == PROXYREQ_PROXY)
  3733. || (rulestatus == ACTION_NOESCAPE))) {
  3734. /* see proxy_http:proxy_http_canon() */
  3735. r->filename = apr_pstrcat(r->pool, r->filename,
  3736. "?", r->args, NULL);
  3737. }
  3738. /* now make sure the request gets handled by the proxy handler */
  3739. if (PROXYREQ_NONE == r->proxyreq) {
  3740. r->proxyreq = PROXYREQ_REVERSE;
  3741. }
  3742. r->handler = "proxy-server";
  3743. rewritelog((r, 1, NULL, "go-ahead with proxy request %s [OK]",
  3744. r->filename));
  3745. return OK;
  3746. }
  3747. else if ((skip = is_absolute_uri(r->filename)) > 0) {
  3748. int n;
  3749. /* it was finally rewritten to a remote URL */
  3750. if (rulestatus != ACTION_NOESCAPE) {
  3751. rewritelog((r, 1, NULL, "escaping %s for redirect",
  3752. r->filename));
  3753. r->filename = escape_absolute_uri(r->pool, r->filename, skip);
  3754. }
  3755. /* append the QUERY_STRING part */
  3756. if (r->args) {
  3757. r->filename = apr_pstrcat(r->pool, r->filename, "?",
  3758. (rulestatus == ACTION_NOESCAPE)
  3759. ? r->args
  3760. : ap_escape_uri(r->pool, r->args),
  3761. NULL);
  3762. }
  3763. /* determine HTTP redirect response code */
  3764. if (ap_is_HTTP_REDIRECT(r->status)) {
  3765. n = r->status;
  3766. r->status = HTTP_OK; /* make Apache kernel happy */
  3767. }
  3768. else {
  3769. n = HTTP_MOVED_TEMPORARILY;
  3770. }
  3771. /* now do the redirection */
  3772. apr_table_setn(r->headers_out, "Location", r->filename);
  3773. rewritelog((r, 1, NULL, "redirect to %s [REDIRECT/%d]", r->filename,
  3774. n));
  3775. return n;
  3776. }
  3777. else if (flen > 12 && strncmp(r->filename, "passthrough:", 12) == 0) {
  3778. /*
  3779. * Hack because of underpowered API: passing the current
  3780. * rewritten filename through to other URL-to-filename handlers
  3781. * just as it were the requested URL. This is to enable
  3782. * post-processing by mod_alias, etc. which always act on
  3783. * r->uri! The difference here is: We do not try to
  3784. * add the document root
  3785. */
  3786. r->uri = apr_pstrdup(r->pool, r->filename+12);
  3787. return DECLINED;
  3788. }
  3789. else {
  3790. /* it was finally rewritten to a local path */
  3791. /* expand "/~user" prefix */
  3792. #if APR_HAS_USER
  3793. r->filename = expand_tildepaths(r, r->filename);
  3794. #endif
  3795. rewritelog((r, 2, NULL, "local path result: %s", r->filename));
  3796. /* the filename must be either an absolute local path or an
  3797. * absolute local URL.
  3798. */
  3799. if ( *r->filename != '/'
  3800. && !ap_os_is_path_absolute(r->pool, r->filename)) {
  3801. return HTTP_BAD_REQUEST;
  3802. }
  3803. /* if there is no valid prefix, we call
  3804. * the translator from the core and
  3805. * prefix the filename with document_root
  3806. *
  3807. * NOTICE:
  3808. * We cannot leave out the prefix_stat because
  3809. * - when we always prefix with document_root
  3810. * then no absolute path can be created, e.g. via
  3811. * emulating a ScriptAlias directive, etc.
  3812. * - when we always NOT prefix with document_root
  3813. * then the files under document_root have to
  3814. * be references directly and document_root
  3815. * gets never used and will be a dummy parameter -
  3816. * this is also bad
  3817. *
  3818. * BUT:
  3819. * Under real Unix systems this is no problem,
  3820. * because we only do stat() on the first directory
  3821. * and this gets cached by the kernel for along time!
  3822. */
  3823. if (!prefix_stat(r->filename, r->pool)) {
  3824. int res;
  3825. char *tmp = r->uri;
  3826. r->uri = r->filename;
  3827. res = ap_core_translate(r);
  3828. r->uri = tmp;
  3829. if (res != OK) {
  3830. rewritelog((r, 1, NULL, "prefixing with document_root of %s"
  3831. " FAILED", r->filename));
  3832. return res;
  3833. }
  3834. rewritelog((r, 2, NULL, "prefixed with document_root to %s",
  3835. r->filename));
  3836. }
  3837. rewritelog((r, 1, NULL, "go-ahead with %s [OK]", r->filename));
  3838. return OK;
  3839. }
  3840. }
  3841. else {
  3842. rewritelog((r, 1, NULL, "pass through %s", r->filename));
  3843. return DECLINED;
  3844. }
  3845. }
  3846. /*
  3847. * Fixup hook
  3848. * [RewriteRules in directory context]
  3849. */
  3850. static int hook_fixup(request_rec *r)
  3851. {
  3852. rewrite_perdir_conf *dconf;
  3853. char *cp;
  3854. char *cp2;
  3855. const char *ccp;
  3856. apr_size_t l;
  3857. int rulestatus;
  3858. int n;
  3859. char *ofilename;
  3860. int is_proxyreq;
  3861. dconf = (rewrite_perdir_conf *)ap_get_module_config(r->per_dir_config,
  3862. &rewrite_module);
  3863. /* if there is no per-dir config we return immediately */
  3864. if (dconf == NULL) {
  3865. return DECLINED;
  3866. }
  3867. /* if there are no real (i.e. no RewriteRule directives!)
  3868. per-dir config of us, we return also immediately */
  3869. if (dconf->directory == NULL) {
  3870. return DECLINED;
  3871. }
  3872. /*
  3873. * Proxy request?
  3874. */
  3875. is_proxyreq = ( r->proxyreq && r->filename
  3876. && !strncmp(r->filename, "proxy:", 6));
  3877. /*
  3878. * .htaccess file is called before really entering the directory, i.e.:
  3879. * URL: http://localhost/foo and .htaccess is located in foo directory
  3880. * Ignore such attempts, since they may lead to undefined behaviour.
  3881. */
  3882. if (!is_proxyreq) {
  3883. l = strlen(dconf->directory) - 1;
  3884. if (r->filename && strlen(r->filename) == l &&
  3885. (dconf->directory)[l] == '/' &&
  3886. !strncmp(r->filename, dconf->directory, l)) {
  3887. return DECLINED;
  3888. }
  3889. }
  3890. /*
  3891. * only do something under runtime if the engine is really enabled,
  3892. * for this directory, else return immediately!
  3893. */
  3894. if (dconf->state == ENGINE_DISABLED) {
  3895. return DECLINED;
  3896. }
  3897. /*
  3898. * Do the Options check after engine check, so
  3899. * the user is able to explicitely turn RewriteEngine Off.
  3900. */
  3901. if (!(ap_allow_options(r) & (OPT_SYM_LINKS | OPT_SYM_OWNER))) {
  3902. /* FollowSymLinks is mandatory! */
  3903. ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
  3904. "Options FollowSymLinks or SymLinksIfOwnerMatch is off "
  3905. "which implies that RewriteRule directive is forbidden: "
  3906. "%s", r->filename);
  3907. return HTTP_FORBIDDEN;
  3908. }
  3909. /*
  3910. * remember the current filename before rewriting for later check
  3911. * to prevent deadlooping because of internal redirects
  3912. * on final URL/filename which can be equal to the inital one.
  3913. * also, we'll restore original r->filename if we decline this
  3914. * request
  3915. */
  3916. ofilename = r->filename;
  3917. if (r->filename == NULL) {
  3918. r->filename = apr_pstrdup(r->pool, r->uri);
  3919. rewritelog((r, 2, "init rewrite engine with requested uri %s",
  3920. r->filename));
  3921. }
  3922. /*
  3923. * now apply the rules ...
  3924. */
  3925. rulestatus = apply_rewrite_list(r, dconf->rewriterules, dconf->directory);
  3926. if (rulestatus) {
  3927. unsigned skip;
  3928. if (ACTION_STATUS == rulestatus) {
  3929. int n = r->status;
  3930. r->status = HTTP_OK;
  3931. return n;
  3932. }
  3933. l = strlen(r->filename);
  3934. if (l > 6 && strncmp(r->filename, "proxy:", 6) == 0) {
  3935. /* it should go on as an internal proxy request */
  3936. /* make sure the QUERY_STRING and
  3937. * PATH_INFO parts get incorporated
  3938. * (r->path_info was already appended by the
  3939. * rewriting engine because of the per-dir context!)
  3940. */
  3941. if (r->args != NULL) {
  3942. r->filename = apr_pstrcat(r->pool, r->filename,
  3943. "?", r->args, NULL);
  3944. }
  3945. /* now make sure the request gets handled by the proxy handler */
  3946. if (PROXYREQ_NONE == r->proxyreq) {
  3947. r->proxyreq = PROXYREQ_REVERSE;
  3948. }
  3949. r->handler = "proxy-server";
  3950. rewritelog((r, 1, dconf->directory, "go-ahead with proxy request "
  3951. "%s [OK]", r->filename));
  3952. return OK;
  3953. }
  3954. else if ((skip = is_absolute_uri(r->filename)) > 0) {
  3955. /* it was finally rewritten to a remote URL */
  3956. /* because we are in a per-dir context
  3957. * first try to replace the directory with its base-URL
  3958. * if there is a base-URL available
  3959. */
  3960. if (dconf->baseurl != NULL) {
  3961. /* skip 'scheme://' */
  3962. cp = r->filename + skip;
  3963. if ((cp = ap_strchr(cp, '/')) != NULL && *(++cp)) {
  3964. rewritelog((r, 2, dconf->directory,
  3965. "trying to replace prefix %s with %s",
  3966. dconf->directory, dconf->baseurl));
  3967. /* I think, that hack needs an explanation:
  3968. * well, here is it:
  3969. * mod_rewrite was written for unix systems, were
  3970. * absolute file-system paths start with a slash.
  3971. * URL-paths _also_ start with slashes, so they
  3972. * can be easily compared with system paths.
  3973. *
  3974. * the following assumes, that the actual url-path
  3975. * may be prefixed by the current directory path and
  3976. * tries to replace the system path with the RewriteBase
  3977. * URL.
  3978. * That assumption is true if we use a RewriteRule like
  3979. *
  3980. * RewriteRule ^foo bar [R]
  3981. *
  3982. * (see apply_rewrite_rule function)
  3983. * However on systems that don't have a / as system
  3984. * root this will never match, so we skip the / after the
  3985. * hostname and compare/substitute only the stuff after it.
  3986. *
  3987. * (note that cp was already increased to the right value)
  3988. */
  3989. cp2 = subst_prefix_path(r, cp, (*dconf->directory == '/')
  3990. ? dconf->directory + 1
  3991. : dconf->directory,
  3992. dconf->baseurl + 1);
  3993. if (strcmp(cp2, cp) != 0) {
  3994. *cp = '\0';
  3995. r->filename = apr_pstrcat(r->pool, r->filename,
  3996. cp2, NULL);
  3997. }
  3998. }
  3999. }
  4000. /* now prepare the redirect... */
  4001. if (rulestatus != ACTION_NOESCAPE) {
  4002. rewritelog((r, 1, dconf->directory, "escaping %s for redirect",
  4003. r->filename));
  4004. r->filename = escape_absolute_uri(r->pool, r->filename, skip);
  4005. }
  4006. /* append the QUERY_STRING part */
  4007. if (r->args) {
  4008. r->filename = apr_pstrcat(r->pool, r->filename, "?",
  4009. (rulestatus == ACTION_NOESCAPE)
  4010. ? r->args
  4011. : ap_escape_uri(r->pool, r->args),
  4012. NULL);
  4013. }
  4014. /* determine HTTP redirect response code */
  4015. if (ap_is_HTTP_REDIRECT(r->status)) {
  4016. n = r->status;
  4017. r->status = HTTP_OK; /* make Apache kernel happy */
  4018. }
  4019. else {
  4020. n = HTTP_MOVED_TEMPORARILY;
  4021. }
  4022. /* now do the redirection */
  4023. apr_table_setn(r->headers_out, "Location", r->filename);
  4024. rewritelog((r, 1, dconf->directory, "redirect to %s [REDIRECT/%d]",
  4025. r->filename, n));
  4026. return n;
  4027. }
  4028. else {
  4029. /* it was finally rewritten to a local path */
  4030. /* if someone used the PASSTHROUGH flag in per-dir
  4031. * context we just ignore it. It is only useful
  4032. * in per-server context
  4033. */
  4034. if (l > 12 && strncmp(r->filename, "passthrough:", 12) == 0) {
  4035. r->filename = apr_pstrdup(r->pool, r->filename+12);
  4036. }
  4037. /* the filename must be either an absolute local path or an
  4038. * absolute local URL.
  4039. */
  4040. if ( *r->filename != '/'
  4041. && !ap_os_is_path_absolute(r->pool, r->filename)) {
  4042. return HTTP_BAD_REQUEST;
  4043. }
  4044. /* Check for deadlooping:
  4045. * At this point we KNOW that at least one rewriting
  4046. * rule was applied, but when the resulting URL is
  4047. * the same as the initial URL, we are not allowed to
  4048. * use the following internal redirection stuff because
  4049. * this would lead to a deadloop.
  4050. */
  4051. if (ofilename != NULL && strcmp(r->filename, ofilename) == 0) {
  4052. rewritelog((r, 1, dconf->directory, "initial URL equal rewritten"
  4053. " URL: %s [IGNORING REWRITE]", r->filename));
  4054. return OK;
  4055. }
  4056. /* if there is a valid base-URL then substitute
  4057. * the per-dir prefix with this base-URL if the
  4058. * current filename still is inside this per-dir
  4059. * context. If not then treat the result as a
  4060. * plain URL
  4061. */
  4062. if (dconf->baseurl != NULL) {
  4063. rewritelog((r, 2, dconf->directory, "trying to replace prefix "
  4064. "%s with %s", dconf->directory, dconf->baseurl));
  4065. r->filename = subst_prefix_path(r, r->filename,
  4066. dconf->directory,
  4067. dconf->baseurl);
  4068. }
  4069. else {
  4070. /* if no explicit base-URL exists we assume
  4071. * that the directory prefix is also a valid URL
  4072. * for this webserver and only try to remove the
  4073. * document_root if it is prefix
  4074. */
  4075. if ((ccp = ap_document_root(r)) != NULL) {
  4076. /* strip trailing slash */
  4077. l = strlen(ccp);
  4078. if (ccp[l-1] == '/') {
  4079. --l;
  4080. }
  4081. if (!strncmp(r->filename, ccp, l) &&
  4082. r->filename[l] == '/') {
  4083. rewritelog((r, 2,dconf->directory, "strip document_root"
  4084. " prefix: %s -> %s", r->filename,
  4085. r->filename+l));
  4086. r->filename = apr_pstrdup(r->pool, r->filename+l);
  4087. }
  4088. }
  4089. }
  4090. /* now initiate the internal redirect */
  4091. rewritelog((r, 1, dconf->directory, "internal redirect with %s "
  4092. "[INTERNAL REDIRECT]", r->filename));
  4093. r->filename = apr_pstrcat(r->pool, "redirect:", r->filename, NULL);
  4094. r->handler = "redirect-handler";
  4095. return OK;
  4096. }
  4097. }
  4098. else {
  4099. rewritelog((r, 1, dconf->directory, "pass through %s", r->filename));
  4100. r->filename = ofilename;
  4101. return DECLINED;
  4102. }
  4103. }
  4104. /*
  4105. * MIME-type hook
  4106. * [T=...,H=...] execution
  4107. */
  4108. static int hook_mimetype(request_rec *r)
  4109. {
  4110. const char *t;
  4111. /* type */
  4112. t = apr_table_get(r->notes, REWRITE_FORCED_MIMETYPE_NOTEVAR);
  4113. if (t && *t) {
  4114. rewritelog((r, 1, NULL, "force filename %s to have MIME-type '%s'",
  4115. r->filename, t));
  4116. ap_set_content_type(r, t);
  4117. }
  4118. /* handler */
  4119. t = apr_table_get(r->notes, REWRITE_FORCED_HANDLER_NOTEVAR);
  4120. if (t && *t) {
  4121. rewritelog((r, 1, NULL, "force filename %s to have the "
  4122. "Content-handler '%s'", r->filename, t));
  4123. r->handler = t;
  4124. }
  4125. return OK;
  4126. }
  4127. /*
  4128. * "content" handler for internal redirects
  4129. */
  4130. static int handler_redirect(request_rec *r)
  4131. {
  4132. if (strcmp(r->handler, "redirect-handler")) {
  4133. return DECLINED;
  4134. }
  4135. /* just make sure that we are really meant! */
  4136. if (strncmp(r->filename, "redirect:", 9) != 0) {
  4137. return DECLINED;
  4138. }
  4139. /* now do the internal redirect */
  4140. ap_internal_redirect(apr_pstrcat(r->pool, r->filename+9,
  4141. r->args ? "?" : NULL, r->args, NULL), r);
  4142. /* and return gracefully */
  4143. return OK;
  4144. }
  4145. /*
  4146. * +-------------------------------------------------------+
  4147. * | |
  4148. * | Module paraphernalia
  4149. * | |
  4150. * +-------------------------------------------------------+
  4151. */
  4152. #ifdef REWRITELOG_DISABLED
  4153. static const char *fake_rewritelog(cmd_parms *cmd, void *dummy, const char *a1)
  4154. {
  4155. return "RewriteLog and RewriteLogLevel are not supported by this build "
  4156. "of mod_rewrite because it was compiled using the "
  4157. "-DREWRITELOG_DISABLED compiler option. You have to recompile "
  4158. "mod_rewrite WITHOUT this option in order to use the rewrite log.";
  4159. }
  4160. #endif
  4161. static const command_rec command_table[] = {
  4162. AP_INIT_FLAG( "RewriteEngine", cmd_rewriteengine, NULL, OR_FILEINFO,
  4163. "On or Off to enable or disable (default) the whole "
  4164. "rewriting engine"),
  4165. AP_INIT_ITERATE( "RewriteOptions", cmd_rewriteoptions, NULL, OR_FILEINFO,
  4166. "List of option strings to set"),
  4167. AP_INIT_TAKE1( "RewriteBase", cmd_rewritebase, NULL, OR_FILEINFO,
  4168. "the base URL of the per-directory context"),
  4169. AP_INIT_RAW_ARGS("RewriteCond", cmd_rewritecond, NULL, OR_FILEINFO,
  4170. "an input string and a to be applied regexp-pattern"),
  4171. AP_INIT_RAW_ARGS("RewriteRule", cmd_rewriterule, NULL, OR_FILEINFO,
  4172. "an URL-applied regexp-pattern and a substitution URL"),
  4173. AP_INIT_TAKE2( "RewriteMap", cmd_rewritemap, NULL, RSRC_CONF,
  4174. "a mapname and a filename"),
  4175. AP_INIT_TAKE1( "RewriteLock", cmd_rewritelock, NULL, RSRC_CONF,
  4176. "the filename of a lockfile used for inter-process "
  4177. "synchronization"),
  4178. #ifndef REWRITELOG_DISABLED
  4179. AP_INIT_TAKE1( "RewriteLog", cmd_rewritelog, NULL, RSRC_CONF,
  4180. "the filename of the rewriting logfile"),
  4181. AP_INIT_TAKE1( "RewriteLogLevel", cmd_rewriteloglevel, NULL, RSRC_CONF,
  4182. "the level of the rewriting logfile verbosity "
  4183. "(0=none, 1=std, .., 9=max)"),
  4184. #else
  4185. AP_INIT_TAKE1( "RewriteLog", fake_rewritelog, NULL, RSRC_CONF,
  4186. "[DISABLED] the filename of the rewriting logfile"),
  4187. AP_INIT_TAKE1( "RewriteLogLevel", fake_rewritelog, NULL, RSRC_CONF,
  4188. "[DISABLED] the level of the rewriting logfile verbosity"),
  4189. #endif
  4190. { NULL }
  4191. };
  4192. static void ap_register_rewrite_mapfunc(char *name, rewrite_mapfunc_t *func)
  4193. {
  4194. apr_hash_set(mapfunc_hash, name, strlen(name), (const void *)func);
  4195. }
  4196. static void register_hooks(apr_pool_t *p)
  4197. {
  4198. /* fixup after mod_proxy, so that the proxied url will not
  4199. * escaped accidentally by mod_proxy's fixup.
  4200. */
  4201. static const char * const aszPre[]={ "mod_proxy.c", NULL };
  4202. /* make the hashtable before registering the function, so that
  4203. * other modules are prevented from accessing uninitialized memory.
  4204. */
  4205. mapfunc_hash = apr_hash_make(p);
  4206. APR_REGISTER_OPTIONAL_FN(ap_register_rewrite_mapfunc);
  4207. ap_hook_handler(handler_redirect, NULL, NULL, APR_HOOK_MIDDLE);
  4208. ap_hook_pre_config(pre_config, NULL, NULL, APR_HOOK_MIDDLE);
  4209. ap_hook_post_config(post_config, NULL, NULL, APR_HOOK_MIDDLE);
  4210. ap_hook_child_init(init_child, NULL, NULL, APR_HOOK_MIDDLE);
  4211. ap_hook_fixups(hook_fixup, aszPre, NULL, APR_HOOK_FIRST);
  4212. ap_hook_fixups(hook_mimetype, NULL, NULL, APR_HOOK_LAST);
  4213. ap_hook_translate_name(hook_uri2file, NULL, NULL, APR_HOOK_FIRST);
  4214. }
  4215. /* the main config structure */
  4216. module AP_MODULE_DECLARE_DATA rewrite_module = {
  4217. STANDARD20_MODULE_STUFF,
  4218. config_perdir_create, /* create per-dir config structures */
  4219. config_perdir_merge, /* merge per-dir config structures */
  4220. config_server_create, /* create per-server config structures */
  4221. config_server_merge, /* merge per-server config structures */
  4222. command_table, /* table of config file commands */
  4223. register_hooks /* register hooks */
  4224. };
  4225. /*EOF*/