http.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235
  1. /*
  2. * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
  3. * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "event2/event-config.h"
  28. #include "evconfig-private.h"
  29. #ifdef EVENT__HAVE_SYS_PARAM_H
  30. #include <sys/param.h>
  31. #endif
  32. #ifdef EVENT__HAVE_SYS_TYPES_H
  33. #include <sys/types.h>
  34. #endif
  35. #ifdef HAVE_SYS_IOCCOM_H
  36. #include <sys/ioccom.h>
  37. #endif
  38. #ifdef EVENT__HAVE_SYS_RESOURCE_H
  39. #include <sys/resource.h>
  40. #endif
  41. #ifdef EVENT__HAVE_SYS_TIME_H
  42. #include <sys/time.h>
  43. #endif
  44. #ifdef EVENT__HAVE_SYS_WAIT_H
  45. #include <sys/wait.h>
  46. #endif
  47. #ifndef _WIN32
  48. #include <sys/socket.h>
  49. #include <sys/stat.h>
  50. #else /* _WIN32 */
  51. #include <winsock2.h>
  52. #include <ws2tcpip.h>
  53. #endif /* _WIN32 */
  54. #ifdef EVENT__HAVE_SYS_UN_H
  55. #include <sys/un.h>
  56. #endif
  57. #ifdef EVENT__HAVE_AFUNIX_H
  58. #error #include <afunix.h>
  59. #endif
  60. #include <sys/queue.h>
  61. #ifdef EVENT__HAVE_NETINET_IN_H
  62. #include <netinet/in.h>
  63. #endif
  64. #ifdef EVENT__HAVE_ARPA_INET_H
  65. #include <arpa/inet.h>
  66. #endif
  67. #ifdef EVENT__HAVE_NETDB_H
  68. #include <netdb.h>
  69. #endif
  70. #ifdef _WIN32
  71. #include <winsock2.h>
  72. #endif
  73. #include <errno.h>
  74. #include <stdio.h>
  75. #include <stdlib.h>
  76. #include <string.h>
  77. #ifndef _WIN32
  78. #include <syslog.h>
  79. #endif /* !_WIN32 */
  80. #include <signal.h>
  81. #ifdef EVENT__HAVE_UNISTD_H
  82. #include <unistd.h>
  83. #endif
  84. #ifdef EVENT__HAVE_FCNTL_H
  85. #include <fcntl.h>
  86. #endif
  87. #undef timeout_pending
  88. #undef timeout_initialized
  89. #include "strlcpy-internal.h"
  90. #include "event2/http.h"
  91. #include "event2/event.h"
  92. #include "event2/buffer.h"
  93. #include "event2/bufferevent.h"
  94. #include "event2/http_struct.h"
  95. #include "event2/http_compat.h"
  96. #include "event2/util.h"
  97. #include "event2/listener.h"
  98. #include "log-internal.h"
  99. #include "util-internal.h"
  100. #include "http-internal.h"
  101. #include "mm-internal.h"
  102. #include "bufferevent-internal.h"
  103. #ifndef EVENT__HAVE_GETNAMEINFO
  104. #define NI_MAXSERV 32
  105. #define NI_MAXHOST 1025
  106. #ifndef NI_NUMERICHOST
  107. #define NI_NUMERICHOST 1
  108. #endif
  109. #ifndef NI_NUMERICSERV
  110. #define NI_NUMERICSERV 2
  111. #endif
  112. static int
  113. fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
  114. size_t hostlen, char *serv, size_t servlen, int flags)
  115. {
  116. struct sockaddr_in *sin = (struct sockaddr_in *)sa;
  117. if (serv != NULL) {
  118. char tmpserv[16];
  119. evutil_snprintf(tmpserv, sizeof(tmpserv),
  120. "%d", ntohs(sin->sin_port));
  121. if (strlcpy(serv, tmpserv, servlen) >= servlen)
  122. return (-1);
  123. }
  124. if (host != NULL) {
  125. if (flags & NI_NUMERICHOST) {
  126. if (strlcpy(host, inet_ntoa(sin->sin_addr),
  127. hostlen) >= hostlen)
  128. return (-1);
  129. else
  130. return (0);
  131. } else {
  132. struct hostent *hp;
  133. hp = gethostbyaddr((char *)&sin->sin_addr,
  134. sizeof(struct in_addr), AF_INET);
  135. if (hp == NULL)
  136. return (-2);
  137. if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
  138. return (-1);
  139. else
  140. return (0);
  141. }
  142. }
  143. return (0);
  144. }
  145. #endif
  146. #define REQ_VERSION_BEFORE(req, major_v, minor_v) \
  147. ((req)->major < (major_v) || \
  148. ((req)->major == (major_v) && (req)->minor < (minor_v)))
  149. #define REQ_VERSION_ATLEAST(req, major_v, minor_v) \
  150. ((req)->major > (major_v) || \
  151. ((req)->major == (major_v) && (req)->minor >= (minor_v)))
  152. #ifndef MIN
  153. #define MIN(a,b) (((a)<(b))?(a):(b))
  154. #endif
  155. extern int debug;
  156. static evutil_socket_t create_bind_socket_nonblock(struct evutil_addrinfo *, int reuse);
  157. static evutil_socket_t bind_socket(const char *, ev_uint16_t, int reuse);
  158. static void name_from_addr(struct sockaddr *, ev_socklen_t, char **, char **);
  159. static struct evhttp_uri *evhttp_uri_parse_authority(char *source_uri);
  160. static int evhttp_associate_new_request_with_connection(
  161. struct evhttp_connection *evcon);
  162. static void evhttp_connection_start_detectclose(
  163. struct evhttp_connection *evcon);
  164. static void evhttp_connection_stop_detectclose(
  165. struct evhttp_connection *evcon);
  166. static void evhttp_request_dispatch(struct evhttp_connection* evcon);
  167. static void evhttp_read_firstline(struct evhttp_connection *evcon,
  168. struct evhttp_request *req);
  169. static void evhttp_read_header(struct evhttp_connection *evcon,
  170. struct evhttp_request *req);
  171. static int evhttp_add_header_internal(struct evkeyvalq *headers,
  172. const char *key, const char *value);
  173. static const char *evhttp_response_phrase_internal(int code);
  174. static void evhttp_get_request(struct evhttp *, evutil_socket_t, struct sockaddr *, ev_socklen_t);
  175. static void evhttp_write_buffer(struct evhttp_connection *,
  176. void (*)(struct evhttp_connection *, void *), void *);
  177. static void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
  178. static struct evhttp_cb *
  179. evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req, int chunked);
  180. /* callbacks for bufferevent */
  181. static void evhttp_read_cb(struct bufferevent *, void *);
  182. static void evhttp_write_cb(struct bufferevent *, void *);
  183. static void evhttp_error_cb(struct bufferevent *bufev, short what, void *arg);
  184. static int evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
  185. const char *hostname);
  186. #ifndef EVENT__HAVE_STRSEP
  187. /* strsep replacement for platforms that lack it. Only works if
  188. * del is one character long. */
  189. static char *
  190. strsep(char **s, const char *del)
  191. {
  192. char *d, *tok;
  193. EVUTIL_ASSERT(strlen(del) == 1);
  194. if (!s || !*s)
  195. return NULL;
  196. tok = *s;
  197. d = strstr(tok, del);
  198. if (d) {
  199. *d = '\0';
  200. *s = d + 1;
  201. } else
  202. *s = NULL;
  203. return tok;
  204. }
  205. #endif
  206. static size_t
  207. html_replace(const char ch, const char **escaped)
  208. {
  209. switch (ch) {
  210. case '<':
  211. *escaped = "&lt;";
  212. return 4;
  213. case '>':
  214. *escaped = "&gt;";
  215. return 4;
  216. case '"':
  217. *escaped = "&quot;";
  218. return 6;
  219. case '\'':
  220. *escaped = "&#039;";
  221. return 6;
  222. case '&':
  223. *escaped = "&amp;";
  224. return 5;
  225. default:
  226. break;
  227. }
  228. return 1;
  229. }
  230. /*
  231. * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
  232. * &#039; and &amp; correspondingly.
  233. *
  234. * The returned string needs to be freed by the caller.
  235. */
  236. char *
  237. evhttp_htmlescape(const char *html)
  238. {
  239. size_t i;
  240. size_t new_size = 0, old_size = 0;
  241. char *escaped_html, *p;
  242. if (html == NULL)
  243. return (NULL);
  244. old_size = strlen(html);
  245. for (i = 0; i < old_size; ++i) {
  246. const char *replaced = NULL;
  247. const size_t replace_size = html_replace(html[i], &replaced);
  248. if (replace_size > EV_SIZE_MAX - new_size) {
  249. event_warn("%s: html_replace overflow", __func__);
  250. return (NULL);
  251. }
  252. new_size += replace_size;
  253. }
  254. if (new_size == EV_SIZE_MAX)
  255. return (NULL);
  256. p = escaped_html = mm_malloc(new_size + 1);
  257. if (escaped_html == NULL) {
  258. event_warn("%s: malloc(%lu)", __func__,
  259. (unsigned long)(new_size + 1));
  260. return (NULL);
  261. }
  262. for (i = 0; i < old_size; ++i) {
  263. const char *replaced = &html[i];
  264. const size_t len = html_replace(html[i], &replaced);
  265. memcpy(p, replaced, len);
  266. p += len;
  267. }
  268. *p = '\0';
  269. return (escaped_html);
  270. }
  271. /** Given an evhttp_cmd_type, returns a constant string containing the
  272. * equivalent HTTP command, or NULL if the evhttp_command_type is
  273. * unrecognized. */
  274. static const char *
  275. evhttp_method(enum evhttp_cmd_type type)
  276. {
  277. const char *method;
  278. switch (type) {
  279. case EVHTTP_REQ_GET:
  280. method = "GET";
  281. break;
  282. case EVHTTP_REQ_POST:
  283. method = "POST";
  284. break;
  285. case EVHTTP_REQ_HEAD:
  286. method = "HEAD";
  287. break;
  288. case EVHTTP_REQ_PUT:
  289. method = "PUT";
  290. break;
  291. case EVHTTP_REQ_DELETE:
  292. method = "DELETE";
  293. break;
  294. case EVHTTP_REQ_OPTIONS:
  295. method = "OPTIONS";
  296. break;
  297. case EVHTTP_REQ_TRACE:
  298. method = "TRACE";
  299. break;
  300. case EVHTTP_REQ_CONNECT:
  301. method = "CONNECT";
  302. break;
  303. case EVHTTP_REQ_PATCH:
  304. method = "PATCH";
  305. break;
  306. default:
  307. method = NULL;
  308. break;
  309. }
  310. return (method);
  311. }
  312. /**
  313. * Determines if a response should have a body.
  314. * Follows the rules in RFC 2616 section 4.3.
  315. * @return 1 if the response MUST have a body; 0 if the response MUST NOT have
  316. * a body.
  317. */
  318. static int
  319. evhttp_response_needs_body(struct evhttp_request *req)
  320. {
  321. return (req->response_code != HTTP_NOCONTENT &&
  322. req->response_code != HTTP_NOTMODIFIED &&
  323. (req->response_code < 100 || req->response_code >= 200) &&
  324. req->type != EVHTTP_REQ_CONNECT &&
  325. req->type != EVHTTP_REQ_HEAD);
  326. }
  327. /** Helper: called after we've added some data to an evcon's bufferevent's
  328. * output buffer. Sets the evconn's writing-is-done callback, and puts
  329. * the bufferevent into writing mode.
  330. */
  331. static void
  332. evhttp_write_buffer(struct evhttp_connection *evcon,
  333. void (*cb)(struct evhttp_connection *, void *), void *arg)
  334. {
  335. event_debug(("%s: preparing to write buffer\n", __func__));
  336. /* Set call back */
  337. evcon->cb = cb;
  338. evcon->cb_arg = arg;
  339. /* Disable the read callback: we don't actually care about data;
  340. * we only care about close detection. (We don't disable reading --
  341. * EV_READ, since we *do* want to learn about any close events.) */
  342. bufferevent_setcb(evcon->bufev,
  343. NULL, /*read*/
  344. evhttp_write_cb,
  345. evhttp_error_cb,
  346. evcon);
  347. bufferevent_enable(evcon->bufev, EV_READ|EV_WRITE);
  348. }
  349. static void
  350. evhttp_send_continue_done(struct evhttp_connection *evcon, void *arg)
  351. {
  352. bufferevent_disable(evcon->bufev, EV_WRITE);
  353. }
  354. static void
  355. evhttp_send_continue(struct evhttp_connection *evcon,
  356. struct evhttp_request *req)
  357. {
  358. bufferevent_enable(evcon->bufev, EV_WRITE);
  359. evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
  360. "HTTP/%d.%d 100 Continue\r\n\r\n",
  361. req->major, req->minor);
  362. evcon->cb = evhttp_send_continue_done;
  363. evcon->cb_arg = NULL;
  364. bufferevent_setcb(evcon->bufev,
  365. evhttp_read_cb,
  366. evhttp_write_cb,
  367. evhttp_error_cb,
  368. evcon);
  369. }
  370. /** Helper: returns true iff evconn is in any connected state. */
  371. static int
  372. evhttp_connected(struct evhttp_connection *evcon)
  373. {
  374. switch (evcon->state) {
  375. case EVCON_DISCONNECTED:
  376. case EVCON_CONNECTING:
  377. return (0);
  378. case EVCON_IDLE:
  379. case EVCON_READING_FIRSTLINE:
  380. case EVCON_READING_HEADERS:
  381. case EVCON_READING_BODY:
  382. case EVCON_READING_TRAILER:
  383. case EVCON_WRITING:
  384. default:
  385. return (1);
  386. }
  387. }
  388. /* Create the headers needed for an outgoing HTTP request, adds them to
  389. * the request's header list, and writes the request line to the
  390. * connection's output buffer.
  391. */
  392. static void
  393. evhttp_make_header_request(struct evhttp_connection *evcon,
  394. struct evhttp_request *req)
  395. {
  396. const char *method;
  397. evhttp_remove_header(req->output_headers, "Proxy-Connection");
  398. /* Generate request line */
  399. if (!(method = evhttp_method(req->type))) {
  400. method = "NULL";
  401. }
  402. evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
  403. "%s %s HTTP/%d.%d\r\n",
  404. method, req->uri, req->major, req->minor);
  405. /* Add the content length on a post or put request if missing */
  406. if ((req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
  407. evhttp_find_header(req->output_headers, "Content-Length") == NULL){
  408. char size[22];
  409. evutil_snprintf(size, sizeof(size), EV_SIZE_FMT,
  410. EV_SIZE_ARG(evbuffer_get_length(req->output_buffer)));
  411. evhttp_add_header(req->output_headers, "Content-Length", size);
  412. }
  413. }
  414. /** Return true if the list of headers in 'headers', intepreted with respect
  415. * to flags, means that we should send a "connection: close" when the request
  416. * is done. */
  417. static int
  418. evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
  419. {
  420. if (flags & EVHTTP_PROXY_REQUEST) {
  421. /* proxy connection */
  422. const char *connection = evhttp_find_header(headers, "Proxy-Connection");
  423. return (connection == NULL || evutil_ascii_strcasecmp(connection, "keep-alive") != 0);
  424. } else {
  425. const char *connection = evhttp_find_header(headers, "Connection");
  426. return (connection != NULL && evutil_ascii_strcasecmp(connection, "close") == 0);
  427. }
  428. }
  429. static int
  430. evhttp_is_request_connection_close(struct evhttp_request *req)
  431. {
  432. if (req->type == EVHTTP_REQ_CONNECT)
  433. return 0;
  434. return
  435. evhttp_is_connection_close(req->flags, req->input_headers) ||
  436. evhttp_is_connection_close(req->flags, req->output_headers);
  437. }
  438. /* Return true iff 'headers' contains 'Connection: keep-alive' */
  439. static int
  440. evhttp_is_connection_keepalive(struct evkeyvalq* headers)
  441. {
  442. const char *connection = evhttp_find_header(headers, "Connection");
  443. return (connection != NULL
  444. && evutil_ascii_strncasecmp(connection, "keep-alive", 10) == 0);
  445. }
  446. /* Add a correct "Date" header to headers, unless it already has one. */
  447. static void
  448. evhttp_maybe_add_date_header(struct evkeyvalq *headers)
  449. {
  450. if (evhttp_find_header(headers, "Date") == NULL) {
  451. char date[50];
  452. if (sizeof(date) - evutil_date_rfc1123(date, sizeof(date), NULL) > 0) {
  453. evhttp_add_header(headers, "Date", date);
  454. }
  455. }
  456. }
  457. /* Add a "Content-Length" header with value 'content_length' to headers,
  458. * unless it already has a content-length or transfer-encoding header. */
  459. static void
  460. evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
  461. size_t content_length)
  462. {
  463. if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
  464. evhttp_find_header(headers, "Content-Length") == NULL) {
  465. char len[22];
  466. evutil_snprintf(len, sizeof(len), EV_SIZE_FMT,
  467. EV_SIZE_ARG(content_length));
  468. evhttp_add_header(headers, "Content-Length", len);
  469. }
  470. }
  471. /*
  472. * Create the headers needed for an HTTP reply in req->output_headers,
  473. * and write the first HTTP response for req line to evcon.
  474. */
  475. static void
  476. evhttp_make_header_response(struct evhttp_connection *evcon,
  477. struct evhttp_request *req)
  478. {
  479. int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
  480. evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
  481. "HTTP/%d.%d %d %s\r\n",
  482. req->major, req->minor, req->response_code,
  483. req->response_code_line);
  484. if (req->major == 1) {
  485. if (req->minor >= 1)
  486. evhttp_maybe_add_date_header(req->output_headers);
  487. /*
  488. * if the protocol is 1.0; and the connection was keep-alive
  489. * we need to add a keep-alive header, too.
  490. */
  491. if (req->minor == 0 && is_keepalive)
  492. evhttp_add_header(req->output_headers,
  493. "Connection", "keep-alive");
  494. if ((req->minor >= 1 || is_keepalive) &&
  495. evhttp_response_needs_body(req)) {
  496. /*
  497. * we need to add the content length if the
  498. * user did not give it, this is required for
  499. * persistent connections to work.
  500. */
  501. evhttp_maybe_add_content_length_header(
  502. req->output_headers,
  503. evbuffer_get_length(req->output_buffer));
  504. }
  505. }
  506. /* Potentially add headers for unidentified content. */
  507. if (evhttp_response_needs_body(req)) {
  508. if (evhttp_find_header(req->output_headers,
  509. "Content-Type") == NULL
  510. && evcon->http_server->default_content_type) {
  511. evhttp_add_header(req->output_headers,
  512. "Content-Type",
  513. evcon->http_server->default_content_type);
  514. }
  515. }
  516. /* if the request asked for a close, we send a close, too */
  517. if (evhttp_is_connection_close(req->flags, req->input_headers)) {
  518. evhttp_remove_header(req->output_headers, "Connection");
  519. if (!(req->flags & EVHTTP_PROXY_REQUEST))
  520. evhttp_add_header(req->output_headers, "Connection", "close");
  521. evhttp_remove_header(req->output_headers, "Proxy-Connection");
  522. }
  523. }
  524. enum expect { NO, CONTINUE, OTHER };
  525. static enum expect evhttp_have_expect(struct evhttp_request *req, int input)
  526. {
  527. const char *expect;
  528. struct evkeyvalq *h = input ? req->input_headers : req->output_headers;
  529. if (!(req->kind == EVHTTP_REQUEST) || !REQ_VERSION_ATLEAST(req, 1, 1))
  530. return NO;
  531. expect = evhttp_find_header(h, "Expect");
  532. if (!expect)
  533. return NO;
  534. return !evutil_ascii_strcasecmp(expect, "100-continue") ? CONTINUE : OTHER;
  535. }
  536. /** Generate all headers appropriate for sending the http request in req (or
  537. * the response, if we're sending a response), and write them to evcon's
  538. * bufferevent. Also writes all data from req->output_buffer */
  539. static void
  540. evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
  541. {
  542. struct evkeyval *header;
  543. struct evbuffer *output = bufferevent_get_output(evcon->bufev);
  544. /*
  545. * Depending if this is a HTTP request or response, we might need to
  546. * add some new headers or remove existing headers.
  547. */
  548. if (req->kind == EVHTTP_REQUEST) {
  549. evhttp_make_header_request(evcon, req);
  550. } else {
  551. evhttp_make_header_response(evcon, req);
  552. }
  553. TAILQ_FOREACH(header, req->output_headers, next) {
  554. evbuffer_add_printf(output, "%s: %s\r\n",
  555. header->key, header->value);
  556. }
  557. evbuffer_add(output, "\r\n", 2);
  558. if (evhttp_have_expect(req, 0) != CONTINUE &&
  559. evbuffer_get_length(req->output_buffer)) {
  560. /*
  561. * For a request, we add the POST data, for a reply, this
  562. * is the regular data.
  563. */
  564. evbuffer_add_buffer(output, req->output_buffer);
  565. }
  566. }
  567. void
  568. evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
  569. ev_ssize_t new_max_headers_size)
  570. {
  571. if (new_max_headers_size<0)
  572. evcon->max_headers_size = EV_SIZE_MAX;
  573. else
  574. evcon->max_headers_size = new_max_headers_size;
  575. }
  576. void
  577. evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
  578. ev_ssize_t new_max_body_size)
  579. {
  580. if (new_max_body_size<0)
  581. evcon->max_body_size = EV_UINT64_MAX;
  582. else
  583. evcon->max_body_size = new_max_body_size;
  584. }
  585. static int
  586. evhttp_connection_incoming_fail(struct evhttp_request *req,
  587. enum evhttp_request_error error)
  588. {
  589. switch (error) {
  590. case EVREQ_HTTP_DATA_TOO_LONG:
  591. req->response_code = HTTP_ENTITYTOOLARGE;
  592. break;
  593. default:
  594. req->response_code = HTTP_BADREQUEST;
  595. }
  596. switch (error) {
  597. case EVREQ_HTTP_TIMEOUT:
  598. case EVREQ_HTTP_EOF:
  599. /*
  600. * these are cases in which we probably should just
  601. * close the connection and not send a reply. this
  602. * case may happen when a browser keeps a persistent
  603. * connection open and we timeout on the read. when
  604. * the request is still being used for sending, we
  605. * need to disassociated it from the connection here.
  606. */
  607. if (!req->userdone) {
  608. /* remove it so that it will not be freed */
  609. TAILQ_REMOVE(&req->evcon->requests, req, next);
  610. /* indicate that this request no longer has a
  611. * connection object
  612. */
  613. req->evcon = NULL;
  614. }
  615. return (-1);
  616. case EVREQ_HTTP_INVALID_HEADER:
  617. case EVREQ_HTTP_BUFFER_ERROR:
  618. case EVREQ_HTTP_REQUEST_CANCEL:
  619. case EVREQ_HTTP_DATA_TOO_LONG:
  620. default: /* xxx: probably should just error on default */
  621. /* the callback looks at the uri to determine errors */
  622. if (req->uri) {
  623. mm_free(req->uri);
  624. req->uri = NULL;
  625. }
  626. if (req->uri_elems) {
  627. evhttp_uri_free(req->uri_elems);
  628. req->uri_elems = NULL;
  629. }
  630. /*
  631. * the callback needs to send a reply, once the reply has
  632. * been send, the connection should get freed.
  633. */
  634. (*req->cb)(req, req->cb_arg);
  635. }
  636. return (0);
  637. }
  638. /* Free connection ownership of which can be acquired by user using
  639. * evhttp_request_own(). */
  640. static inline void
  641. evhttp_request_free_auto(struct evhttp_request *req)
  642. {
  643. if (!(req->flags & EVHTTP_USER_OWNED))
  644. evhttp_request_free(req);
  645. }
  646. static void
  647. evhttp_request_free_(struct evhttp_connection *evcon, struct evhttp_request *req)
  648. {
  649. TAILQ_REMOVE(&evcon->requests, req, next);
  650. evhttp_request_free_auto(req);
  651. }
  652. /* Called when evcon has experienced a (non-recoverable? -NM) error, as
  653. * given in error. If it's an outgoing connection, reset the connection,
  654. * retry any pending requests, and inform the user. If it's incoming,
  655. * delegates to evhttp_connection_incoming_fail(). */
  656. void
  657. evhttp_connection_fail_(struct evhttp_connection *evcon,
  658. enum evhttp_request_error error)
  659. {
  660. const int errsave = EVUTIL_SOCKET_ERROR();
  661. struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
  662. void (*cb)(struct evhttp_request *, void *);
  663. void *cb_arg;
  664. void (*error_cb)(enum evhttp_request_error, void *);
  665. void *error_cb_arg;
  666. EVUTIL_ASSERT(req != NULL);
  667. bufferevent_disable(evcon->bufev, EV_READ|EV_WRITE);
  668. if (evcon->flags & EVHTTP_CON_INCOMING) {
  669. /*
  670. * for incoming requests, there are two different
  671. * failure cases. it's either a network level error
  672. * or an http layer error. for problems on the network
  673. * layer like timeouts we just drop the connections.
  674. * For HTTP problems, we might have to send back a
  675. * reply before the connection can be freed.
  676. */
  677. if (evhttp_connection_incoming_fail(req, error) == -1)
  678. evhttp_connection_free(evcon);
  679. return;
  680. }
  681. error_cb = req->error_cb;
  682. error_cb_arg = req->cb_arg;
  683. /* when the request was canceled, the callback is not executed */
  684. if (error != EVREQ_HTTP_REQUEST_CANCEL) {
  685. /* save the callback for later; the cb might free our object */
  686. cb = req->cb;
  687. cb_arg = req->cb_arg;
  688. } else {
  689. cb = NULL;
  690. cb_arg = NULL;
  691. }
  692. /* do not fail all requests; the next request is going to get
  693. * send over a new connection. when a user cancels a request,
  694. * all other pending requests should be processed as normal
  695. */
  696. evhttp_request_free_(evcon, req);
  697. /* reset the connection */
  698. evhttp_connection_reset_(evcon);
  699. /* We are trying the next request that was queued on us */
  700. if (TAILQ_FIRST(&evcon->requests) != NULL)
  701. evhttp_connection_connect_(evcon);
  702. else
  703. if ((evcon->flags & EVHTTP_CON_OUTGOING) &&
  704. (evcon->flags & EVHTTP_CON_AUTOFREE)) {
  705. evhttp_connection_free(evcon);
  706. }
  707. /* The call to evhttp_connection_reset_ overwrote errno.
  708. * Let's restore the original errno, so that the user's
  709. * callback can have a better idea of what the error was.
  710. */
  711. EVUTIL_SET_SOCKET_ERROR(errsave);
  712. /* inform the user */
  713. if (error_cb != NULL)
  714. error_cb(error, error_cb_arg);
  715. if (cb != NULL)
  716. (*cb)(NULL, cb_arg);
  717. }
  718. /* Bufferevent callback: invoked when any data has been written from an
  719. * http connection's bufferevent */
  720. static void
  721. evhttp_write_cb(struct bufferevent *bufev, void *arg)
  722. {
  723. struct evhttp_connection *evcon = arg;
  724. /* Activate our call back */
  725. if (evcon->cb != NULL)
  726. (*evcon->cb)(evcon, evcon->cb_arg);
  727. }
  728. /**
  729. * Advance the connection state.
  730. * - If this is an outgoing connection, we've just processed the response;
  731. * idle or close the connection.
  732. * - If this is an incoming connection, we've just processed the request;
  733. * respond.
  734. */
  735. static void
  736. evhttp_connection_done(struct evhttp_connection *evcon)
  737. {
  738. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  739. int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
  740. int free_evcon = 0;
  741. if (con_outgoing) {
  742. /* idle or close the connection */
  743. int need_close = evhttp_is_request_connection_close(req);
  744. TAILQ_REMOVE(&evcon->requests, req, next);
  745. req->evcon = NULL;
  746. evcon->state = EVCON_IDLE;
  747. /* check if we got asked to close the connection */
  748. if (need_close)
  749. evhttp_connection_reset_(evcon);
  750. if (TAILQ_FIRST(&evcon->requests) != NULL) {
  751. /*
  752. * We have more requests; reset the connection
  753. * and deal with the next request.
  754. */
  755. if (!evhttp_connected(evcon))
  756. evhttp_connection_connect_(evcon);
  757. else
  758. evhttp_request_dispatch(evcon);
  759. } else if (!need_close) {
  760. /*
  761. * The connection is going to be persistent, but we
  762. * need to detect if the other side closes it.
  763. */
  764. evhttp_connection_start_detectclose(evcon);
  765. } else if ((evcon->flags & EVHTTP_CON_AUTOFREE)) {
  766. /*
  767. * If we have no more requests that need completion
  768. * and we're not waiting for the connection to close
  769. */
  770. free_evcon = 1;
  771. }
  772. } else {
  773. /*
  774. * incoming connection - we need to leave the request on the
  775. * connection so that we can reply to it.
  776. */
  777. evcon->state = EVCON_WRITING;
  778. }
  779. /* notify the user of the request */
  780. (*req->cb)(req, req->cb_arg);
  781. /* if this was an outgoing request, we own and it's done. so free it. */
  782. if (con_outgoing) {
  783. evhttp_request_free_auto(req);
  784. }
  785. /* If this was the last request of an outgoing connection and we're
  786. * not waiting to receive a connection close event and we want to
  787. * automatically free the connection. We check to ensure our request
  788. * list is empty one last time just in case our callback added a
  789. * new request.
  790. */
  791. if (free_evcon && TAILQ_FIRST(&evcon->requests) == NULL) {
  792. evhttp_connection_free(evcon);
  793. }
  794. }
  795. /*
  796. * Handles reading from a chunked request.
  797. * return ALL_DATA_READ:
  798. * all data has been read
  799. * return MORE_DATA_EXPECTED:
  800. * more data is expected
  801. * return DATA_CORRUPTED:
  802. * data is corrupted
  803. * return REQUEST_CANCELED:
  804. * request was canceled by the user calling evhttp_cancel_request
  805. * return DATA_TOO_LONG:
  806. * ran over the maximum limit
  807. */
  808. static enum message_read_status
  809. evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
  810. {
  811. if (req == NULL || buf == NULL) {
  812. return DATA_CORRUPTED;
  813. }
  814. while (1) {
  815. size_t buflen;
  816. if ((buflen = evbuffer_get_length(buf)) == 0) {
  817. break;
  818. }
  819. /* evbuffer_get_length returns size_t, but len variable is ssize_t,
  820. * check for overflow conditions */
  821. if (buflen > EV_SSIZE_MAX) {
  822. return DATA_CORRUPTED;
  823. }
  824. if (req->ntoread < 0) {
  825. /* Read chunk size */
  826. ev_int64_t ntoread;
  827. char *p = evbuffer_readln(buf, NULL, EVBUFFER_EOL_CRLF);
  828. char *endp;
  829. int error;
  830. if (p == NULL)
  831. break;
  832. /* the last chunk is on a new line? */
  833. if (strlen(p) == 0) {
  834. mm_free(p);
  835. continue;
  836. }
  837. ntoread = evutil_strtoll(p, &endp, 16);
  838. error = (*p == '\0' ||
  839. (*endp != '\0' && *endp != ' ') ||
  840. ntoread < 0);
  841. mm_free(p);
  842. if (error) {
  843. /* could not get chunk size */
  844. return (DATA_CORRUPTED);
  845. }
  846. /* ntoread is signed int64, body_size is unsigned size_t, check for under/overflow conditions */
  847. if ((ev_uint64_t)ntoread > EV_SIZE_MAX - req->body_size) {
  848. return DATA_CORRUPTED;
  849. }
  850. if (req->body_size + (size_t)ntoread > req->evcon->max_body_size) {
  851. /* failed body length test */
  852. event_debug(("Request body is too long"));
  853. return (DATA_TOO_LONG);
  854. }
  855. req->body_size += (size_t)ntoread;
  856. req->ntoread = ntoread;
  857. if (req->ntoread == 0) {
  858. /* Last chunk */
  859. return (ALL_DATA_READ);
  860. }
  861. continue;
  862. }
  863. /* req->ntoread is signed int64, len is ssize_t, based on arch,
  864. * ssize_t could only be 32b, check for these conditions */
  865. if (req->ntoread > EV_SSIZE_MAX) {
  866. return DATA_CORRUPTED;
  867. }
  868. /* don't have enough to complete a chunk; wait for more */
  869. if (req->ntoread > 0 && buflen < (ev_uint64_t)req->ntoread)
  870. return (MORE_DATA_EXPECTED);
  871. /* Completed chunk */
  872. evbuffer_remove_buffer(buf, req->input_buffer, (size_t)req->ntoread);
  873. req->ntoread = -1;
  874. if (req->chunk_cb != NULL) {
  875. req->flags |= EVHTTP_REQ_DEFER_FREE;
  876. (*req->chunk_cb)(req, req->chunk_cb_arg);
  877. evbuffer_drain(req->input_buffer,
  878. evbuffer_get_length(req->input_buffer));
  879. req->flags &= ~EVHTTP_REQ_DEFER_FREE;
  880. if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
  881. return (REQUEST_CANCELED);
  882. }
  883. }
  884. }
  885. if (req->chunk_cb != NULL) {
  886. req->flags |= EVHTTP_REQ_PROCESS_CHUNKS_END;
  887. (*req->chunk_cb)(req, req->chunk_cb_arg);
  888. req->flags &= ~EVHTTP_REQ_PROCESS_CHUNKS_END;
  889. }
  890. return (MORE_DATA_EXPECTED);
  891. }
  892. static void
  893. evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
  894. {
  895. struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
  896. switch (evhttp_parse_headers_(req, buf)) {
  897. case DATA_CORRUPTED:
  898. case DATA_TOO_LONG:
  899. evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
  900. break;
  901. case ALL_DATA_READ:
  902. bufferevent_disable(evcon->bufev, EV_READ);
  903. evhttp_connection_done(evcon);
  904. break;
  905. case MORE_DATA_EXPECTED:
  906. case REQUEST_CANCELED: /* ??? */
  907. default:
  908. break;
  909. }
  910. }
  911. static void
  912. evhttp_lingering_close(struct evhttp_connection *evcon,
  913. struct evhttp_request *req)
  914. {
  915. struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
  916. size_t n = evbuffer_get_length(buf);
  917. if (n > (size_t) req->ntoread)
  918. n = (size_t) req->ntoread;
  919. req->ntoread -= n;
  920. req->body_size += n;
  921. event_debug(("Request body is too long, left " EV_I64_FMT,
  922. EV_I64_ARG(req->ntoread)));
  923. evbuffer_drain(buf, n);
  924. if (!req->ntoread)
  925. evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
  926. }
  927. static void
  928. evhttp_lingering_fail(struct evhttp_connection *evcon,
  929. struct evhttp_request *req)
  930. {
  931. if (evcon->flags & EVHTTP_CON_LINGERING_CLOSE)
  932. evhttp_lingering_close(evcon, req);
  933. else
  934. evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
  935. }
  936. static void
  937. evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
  938. {
  939. struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
  940. if (req->chunked) {
  941. switch (evhttp_handle_chunked_read(req, buf)) {
  942. case ALL_DATA_READ:
  943. /* finished last chunk */
  944. evcon->state = EVCON_READING_TRAILER;
  945. evhttp_read_trailer(evcon, req);
  946. return;
  947. case DATA_CORRUPTED:
  948. case DATA_TOO_LONG:
  949. /* corrupted data */
  950. evhttp_connection_fail_(evcon,
  951. EVREQ_HTTP_DATA_TOO_LONG);
  952. return;
  953. case REQUEST_CANCELED:
  954. /* request canceled */
  955. evhttp_request_free_auto(req);
  956. return;
  957. case MORE_DATA_EXPECTED:
  958. default:
  959. break;
  960. }
  961. } else if (req->ntoread < 0) {
  962. /* Read until connection close. */
  963. if ((size_t)(req->body_size + evbuffer_get_length(buf)) < req->body_size) {
  964. evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
  965. return;
  966. }
  967. req->body_size += evbuffer_get_length(buf);
  968. evbuffer_add_buffer(req->input_buffer, buf);
  969. } else if (req->chunk_cb != NULL || evbuffer_get_length(buf) >= (size_t)req->ntoread) {
  970. /* XXX: the above get_length comparison has to be fixed for overflow conditions! */
  971. /* We've postponed moving the data until now, but we're
  972. * about to use it. */
  973. size_t n = evbuffer_get_length(buf);
  974. if (n > (size_t) req->ntoread)
  975. n = (size_t) req->ntoread;
  976. req->ntoread -= n;
  977. req->body_size += n;
  978. evbuffer_remove_buffer(buf, req->input_buffer, n);
  979. }
  980. if (req->body_size > req->evcon->max_body_size ||
  981. (!req->chunked && req->ntoread >= 0 &&
  982. (size_t)req->ntoread > req->evcon->max_body_size)) {
  983. /* XXX: The above casted comparison must checked for overflow */
  984. /* failed body length test */
  985. evhttp_lingering_fail(evcon, req);
  986. return;
  987. }
  988. if (evbuffer_get_length(req->input_buffer) > 0 && req->chunk_cb != NULL) {
  989. req->flags |= EVHTTP_REQ_DEFER_FREE;
  990. (*req->chunk_cb)(req, req->chunk_cb_arg);
  991. req->flags &= ~EVHTTP_REQ_DEFER_FREE;
  992. evbuffer_drain(req->input_buffer,
  993. evbuffer_get_length(req->input_buffer));
  994. if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
  995. evhttp_request_free_auto(req);
  996. return;
  997. }
  998. }
  999. if (!req->ntoread) {
  1000. bufferevent_disable(evcon->bufev, EV_READ);
  1001. /* Completed content length */
  1002. evhttp_connection_done(evcon);
  1003. return;
  1004. }
  1005. }
  1006. #define get_deferred_queue(evcon) \
  1007. ((evcon)->base)
  1008. /*
  1009. * Gets called when more data becomes available
  1010. */
  1011. static void
  1012. evhttp_read_cb(struct bufferevent *bufev, void *arg)
  1013. {
  1014. struct evhttp_connection *evcon = arg;
  1015. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  1016. /* Cancel if it's pending. */
  1017. event_deferred_cb_cancel_(get_deferred_queue(evcon),
  1018. &evcon->read_more_deferred_cb);
  1019. switch (evcon->state) {
  1020. case EVCON_READING_FIRSTLINE:
  1021. evhttp_read_firstline(evcon, req);
  1022. /* note the request may have been freed in
  1023. * evhttp_read_body */
  1024. break;
  1025. case EVCON_READING_HEADERS:
  1026. evhttp_read_header(evcon, req);
  1027. /* note the request may have been freed in
  1028. * evhttp_read_body */
  1029. break;
  1030. case EVCON_READING_BODY:
  1031. evhttp_read_body(evcon, req);
  1032. /* note the request may have been freed in
  1033. * evhttp_read_body */
  1034. break;
  1035. case EVCON_READING_TRAILER:
  1036. evhttp_read_trailer(evcon, req);
  1037. break;
  1038. case EVCON_IDLE:
  1039. {
  1040. #ifdef USE_DEBUG
  1041. struct evbuffer *input;
  1042. size_t total_len;
  1043. input = bufferevent_get_input(evcon->bufev);
  1044. total_len = evbuffer_get_length(input);
  1045. event_debug(("%s: read "EV_SIZE_FMT
  1046. " bytes in EVCON_IDLE state,"
  1047. " resetting connection",
  1048. __func__, EV_SIZE_ARG(total_len)));
  1049. #endif
  1050. evhttp_connection_reset_(evcon);
  1051. }
  1052. break;
  1053. case EVCON_DISCONNECTED:
  1054. case EVCON_CONNECTING:
  1055. case EVCON_WRITING:
  1056. default:
  1057. event_errx(1, "%s: illegal connection state %d",
  1058. __func__, evcon->state);
  1059. }
  1060. }
  1061. static void
  1062. evhttp_deferred_read_cb(struct event_callback *cb, void *data)
  1063. {
  1064. struct evhttp_connection *evcon = data;
  1065. struct bufferevent *bev = evcon->bufev;
  1066. if (bev->readcb)
  1067. (bev->readcb)(evcon->bufev, evcon);
  1068. }
  1069. static void
  1070. evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
  1071. {
  1072. /* This is after writing the request to the server */
  1073. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  1074. struct evbuffer *output = bufferevent_get_output(evcon->bufev);
  1075. EVUTIL_ASSERT(req != NULL);
  1076. EVUTIL_ASSERT(evcon->state == EVCON_WRITING);
  1077. /* We need to wait until we've written all of our output data before we can
  1078. * continue */
  1079. if (evbuffer_get_length(output) > 0)
  1080. return;
  1081. /* We are done writing our header and are now expecting the response */
  1082. req->kind = EVHTTP_RESPONSE;
  1083. evhttp_start_read_(evcon);
  1084. }
  1085. /*
  1086. * Clean up a connection object
  1087. */
  1088. void
  1089. evhttp_connection_free(struct evhttp_connection *evcon)
  1090. {
  1091. struct evhttp_request *req;
  1092. int need_close = 0;
  1093. /* notify interested parties that this connection is going down */
  1094. if (evcon->fd != -1) {
  1095. if (evhttp_connected(evcon) && evcon->closecb != NULL)
  1096. (*evcon->closecb)(evcon, evcon->closecb_arg);
  1097. }
  1098. /* remove all requests that might be queued on this
  1099. * connection. for server connections, this should be empty.
  1100. * because it gets dequeued either in evhttp_connection_done or
  1101. * evhttp_connection_fail_.
  1102. */
  1103. while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
  1104. evhttp_request_free_(evcon, req);
  1105. }
  1106. if (evcon->http_server != NULL) {
  1107. struct evhttp *http = evcon->http_server;
  1108. TAILQ_REMOVE(&http->connections, evcon, next);
  1109. }
  1110. if (event_initialized(&evcon->retry_ev)) {
  1111. event_del(&evcon->retry_ev);
  1112. event_debug_unassign(&evcon->retry_ev);
  1113. }
  1114. event_deferred_cb_cancel_(get_deferred_queue(evcon),
  1115. &evcon->read_more_deferred_cb);
  1116. if (evcon->bufev != NULL) {
  1117. need_close =
  1118. !(bufferevent_get_options_(evcon->bufev) & BEV_OPT_CLOSE_ON_FREE);
  1119. if (evcon->fd == -1)
  1120. evcon->fd = bufferevent_getfd(evcon->bufev);
  1121. bufferevent_free(evcon->bufev);
  1122. }
  1123. if (evcon->fd != -1) {
  1124. shutdown(evcon->fd, EVUTIL_SHUT_WR);
  1125. if (need_close)
  1126. evutil_closesocket(evcon->fd);
  1127. }
  1128. if (evcon->bind_address != NULL)
  1129. mm_free(evcon->bind_address);
  1130. if (evcon->address != NULL)
  1131. mm_free(evcon->address);
  1132. mm_free(evcon);
  1133. }
  1134. void
  1135. evhttp_connection_free_on_completion(struct evhttp_connection *evcon) {
  1136. evcon->flags |= EVHTTP_CON_AUTOFREE;
  1137. }
  1138. void
  1139. evhttp_connection_set_local_address(struct evhttp_connection *evcon,
  1140. const char *address)
  1141. {
  1142. EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
  1143. if (evcon->bind_address)
  1144. mm_free(evcon->bind_address);
  1145. if ((evcon->bind_address = mm_strdup(address)) == NULL)
  1146. event_warn("%s: strdup", __func__);
  1147. }
  1148. void
  1149. evhttp_connection_set_local_port(struct evhttp_connection *evcon,
  1150. ev_uint16_t port)
  1151. {
  1152. EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
  1153. evcon->bind_port = port;
  1154. }
  1155. static void
  1156. evhttp_request_dispatch(struct evhttp_connection* evcon)
  1157. {
  1158. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  1159. /* this should not usually happy but it's possible */
  1160. if (req == NULL)
  1161. return;
  1162. EVUTIL_ASSERT(req->kind == EVHTTP_REQUEST);
  1163. /* delete possible close detection events */
  1164. evhttp_connection_stop_detectclose(evcon);
  1165. /* we assume that the connection is connected already */
  1166. EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
  1167. evcon->state = EVCON_WRITING;
  1168. /* Create the header from the store arguments */
  1169. evhttp_make_header(evcon, req);
  1170. evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
  1171. }
  1172. /* Reset our connection state: disables reading/writing, closes our fd (if
  1173. * any), clears out buffers, and puts us in state DISCONNECTED. */
  1174. void
  1175. evhttp_connection_reset_(struct evhttp_connection *evcon)
  1176. {
  1177. struct evbuffer *tmp;
  1178. int err;
  1179. bufferevent_setcb(evcon->bufev, NULL, NULL, NULL, NULL);
  1180. /* XXXX This is not actually an optimal fix. Instead we ought to have
  1181. an API for "stop connecting", or use bufferevent_setfd to turn off
  1182. connecting. But for Libevent 2.0, this seems like a minimal change
  1183. least likely to disrupt the rest of the bufferevent and http code.
  1184. Why is this here? If the fd is set in the bufferevent, and the
  1185. bufferevent is connecting, then you can't actually stop the
  1186. bufferevent from trying to connect with bufferevent_disable(). The
  1187. connect will never trigger, since we close the fd, but the timeout
  1188. might. That caused an assertion failure in evhttp_connection_fail_.
  1189. */
  1190. bufferevent_disable_hard_(evcon->bufev, EV_READ|EV_WRITE);
  1191. if (evcon->fd == -1)
  1192. evcon->fd = bufferevent_getfd(evcon->bufev);
  1193. if (evcon->fd != -1) {
  1194. /* inform interested parties about connection close */
  1195. if (evhttp_connected(evcon) && evcon->closecb != NULL)
  1196. (*evcon->closecb)(evcon, evcon->closecb_arg);
  1197. /* if we have a bufferevent factory callback set, get a new bufferevent */
  1198. if (NULL != evcon->bufcb && -1 != bufferevent_getfd(evcon->bufev)) {
  1199. struct bufferevent *bev = (*evcon->bufcb)(evcon->bufcb_arg);
  1200. if (NULL == bev) {
  1201. event_warn("%s: bufferevent factory callback failed", __func__);
  1202. }
  1203. else {
  1204. if (bufferevent_get_base(bev) != evcon->base) {
  1205. bufferevent_base_set(evcon->base, bev);
  1206. }
  1207. bufferevent_free(evcon->bufev);
  1208. evcon->bufev = bev;
  1209. }
  1210. }
  1211. shutdown(evcon->fd, EVUTIL_SHUT_WR);
  1212. evutil_closesocket(evcon->fd);
  1213. evcon->fd = -1;
  1214. }
  1215. err = bufferevent_setfd(evcon->bufev, -1);
  1216. EVUTIL_ASSERT(!err && "setfd");
  1217. /* we need to clean up any buffered data */
  1218. tmp = bufferevent_get_output(evcon->bufev);
  1219. err = evbuffer_drain(tmp, -1);
  1220. EVUTIL_ASSERT(!err && "drain output");
  1221. tmp = bufferevent_get_input(evcon->bufev);
  1222. err = evbuffer_drain(tmp, -1);
  1223. EVUTIL_ASSERT(!err && "drain input");
  1224. evcon->flags &= ~EVHTTP_CON_READING_ERROR;
  1225. evcon->state = EVCON_DISCONNECTED;
  1226. }
  1227. static void
  1228. evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
  1229. {
  1230. evcon->flags |= EVHTTP_CON_CLOSEDETECT;
  1231. bufferevent_enable(evcon->bufev, EV_READ);
  1232. }
  1233. static void
  1234. evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
  1235. {
  1236. evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
  1237. bufferevent_disable(evcon->bufev, EV_READ);
  1238. }
  1239. static void
  1240. evhttp_connection_retry(evutil_socket_t fd, short what, void *arg)
  1241. {
  1242. struct evhttp_connection *evcon = arg;
  1243. evcon->state = EVCON_DISCONNECTED;
  1244. evhttp_connection_connect_(evcon);
  1245. }
  1246. static void
  1247. evhttp_connection_cb_cleanup(struct evhttp_connection *evcon)
  1248. {
  1249. struct evcon_requestq requests;
  1250. evhttp_connection_reset_(evcon);
  1251. if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
  1252. struct timeval tv_retry = evcon->initial_retry_timeout;
  1253. int i;
  1254. evtimer_assign(&evcon->retry_ev, evcon->base, evhttp_connection_retry, evcon);
  1255. /* XXXX handle failure from evhttp_add_event */
  1256. for (i=0; i < evcon->retry_cnt; ++i) {
  1257. tv_retry.tv_usec *= 2;
  1258. if (tv_retry.tv_usec > 1000000) {
  1259. tv_retry.tv_usec -= 1000000;
  1260. tv_retry.tv_sec += 1;
  1261. }
  1262. tv_retry.tv_sec *= 2;
  1263. if (tv_retry.tv_sec > 3600) {
  1264. tv_retry.tv_sec = 3600;
  1265. tv_retry.tv_usec = 0;
  1266. }
  1267. }
  1268. event_add(&evcon->retry_ev, &tv_retry);
  1269. evcon->retry_cnt++;
  1270. return;
  1271. }
  1272. /*
  1273. * User callback can do evhttp_make_request() on the same
  1274. * evcon so new request will be added to evcon->requests. To
  1275. * avoid freeing it prematurely we iterate over the copy of
  1276. * the queue.
  1277. */
  1278. TAILQ_INIT(&requests);
  1279. while (TAILQ_FIRST(&evcon->requests) != NULL) {
  1280. struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
  1281. TAILQ_REMOVE(&evcon->requests, request, next);
  1282. TAILQ_INSERT_TAIL(&requests, request, next);
  1283. }
  1284. /* for now, we just signal all requests by executing their callbacks */
  1285. while (TAILQ_FIRST(&requests) != NULL) {
  1286. struct evhttp_request *request = TAILQ_FIRST(&requests);
  1287. TAILQ_REMOVE(&requests, request, next);
  1288. request->evcon = NULL;
  1289. /* we might want to set an error here */
  1290. request->cb(request, request->cb_arg);
  1291. evhttp_request_free_auto(request);
  1292. }
  1293. }
  1294. static void
  1295. evhttp_connection_read_on_write_error(struct evhttp_connection *evcon,
  1296. struct evhttp_request *req)
  1297. {
  1298. struct evbuffer *buf;
  1299. /** Second time, we can't read anything */
  1300. if (evcon->flags & EVHTTP_CON_READING_ERROR) {
  1301. evcon->flags &= ~EVHTTP_CON_READING_ERROR;
  1302. evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
  1303. return;
  1304. }
  1305. req->kind = EVHTTP_RESPONSE;
  1306. buf = bufferevent_get_output(evcon->bufev);
  1307. evbuffer_unfreeze(buf, 1);
  1308. evbuffer_drain(buf, evbuffer_get_length(buf));
  1309. evbuffer_freeze(buf, 1);
  1310. evhttp_start_read_(evcon);
  1311. evcon->flags |= EVHTTP_CON_READING_ERROR;
  1312. }
  1313. static void
  1314. evhttp_error_cb(struct bufferevent *bufev, short what, void *arg)
  1315. {
  1316. struct evhttp_connection *evcon = arg;
  1317. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  1318. if (evcon->fd == -1)
  1319. evcon->fd = bufferevent_getfd(bufev);
  1320. switch (evcon->state) {
  1321. case EVCON_CONNECTING:
  1322. if (what & BEV_EVENT_TIMEOUT) {
  1323. event_debug(("%s: connection timeout for \"%s:%d\" on "
  1324. EV_SOCK_FMT,
  1325. __func__, evcon->address, evcon->port,
  1326. EV_SOCK_ARG(evcon->fd)));
  1327. evhttp_connection_cb_cleanup(evcon);
  1328. return;
  1329. }
  1330. break;
  1331. case EVCON_READING_BODY:
  1332. if (!req->chunked && req->ntoread < 0
  1333. && what == (BEV_EVENT_READING|BEV_EVENT_EOF)) {
  1334. /* EOF on read can be benign */
  1335. evhttp_connection_done(evcon);
  1336. return;
  1337. }
  1338. break;
  1339. case EVCON_DISCONNECTED:
  1340. case EVCON_IDLE:
  1341. case EVCON_READING_FIRSTLINE:
  1342. case EVCON_READING_HEADERS:
  1343. case EVCON_READING_TRAILER:
  1344. case EVCON_WRITING:
  1345. default:
  1346. break;
  1347. }
  1348. /* when we are in close detect mode, a read error means that
  1349. * the other side closed their connection.
  1350. */
  1351. if (evcon->flags & EVHTTP_CON_CLOSEDETECT) {
  1352. evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
  1353. EVUTIL_ASSERT(evcon->http_server == NULL);
  1354. /* For connections from the client, we just
  1355. * reset the connection so that it becomes
  1356. * disconnected.
  1357. */
  1358. EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
  1359. evhttp_connection_reset_(evcon);
  1360. /*
  1361. * If we have no more requests that need completion
  1362. * and we want to auto-free the connection when all
  1363. * requests have been completed.
  1364. */
  1365. if (TAILQ_FIRST(&evcon->requests) == NULL
  1366. && (evcon->flags & EVHTTP_CON_OUTGOING)
  1367. && (evcon->flags & EVHTTP_CON_AUTOFREE)) {
  1368. evhttp_connection_free(evcon);
  1369. }
  1370. return;
  1371. }
  1372. if (what & BEV_EVENT_TIMEOUT) {
  1373. evhttp_connection_fail_(evcon, EVREQ_HTTP_TIMEOUT);
  1374. } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
  1375. if (what & BEV_EVENT_WRITING &&
  1376. evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR) {
  1377. evhttp_connection_read_on_write_error(evcon, req);
  1378. return;
  1379. }
  1380. if (what & BEV_EVENT_READING &&
  1381. evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR &&
  1382. evbuffer_get_length(bufferevent_get_input(bufev))) {
  1383. event_deferred_cb_schedule_(get_deferred_queue(evcon),
  1384. &evcon->read_more_deferred_cb);
  1385. return;
  1386. }
  1387. evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
  1388. } else if (what == BEV_EVENT_CONNECTED) {
  1389. } else {
  1390. evhttp_connection_fail_(evcon, EVREQ_HTTP_BUFFER_ERROR);
  1391. }
  1392. }
  1393. /*
  1394. * Event callback for asynchronous connection attempt.
  1395. */
  1396. static void
  1397. evhttp_connection_cb(struct bufferevent *bufev, short what, void *arg)
  1398. {
  1399. struct evhttp_connection *evcon = arg;
  1400. int error;
  1401. ev_socklen_t errsz = sizeof(error);
  1402. if (evcon->fd == -1)
  1403. evcon->fd = bufferevent_getfd(bufev);
  1404. if (!(what & BEV_EVENT_CONNECTED)) {
  1405. /* some operating systems return ECONNREFUSED immediately
  1406. * when connecting to a local address. the cleanup is going
  1407. * to reschedule this function call.
  1408. */
  1409. #ifndef _WIN32
  1410. if (errno == ECONNREFUSED)
  1411. goto cleanup;
  1412. #endif
  1413. evhttp_error_cb(bufev, what, arg);
  1414. return;
  1415. }
  1416. if (evcon->fd == -1) {
  1417. event_debug(("%s: bufferevent_getfd returned -1",
  1418. __func__));
  1419. goto cleanup;
  1420. }
  1421. /* Check if the connection completed */
  1422. if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
  1423. &errsz) == -1) {
  1424. event_debug(("%s: getsockopt for \"%s:%d\" on "EV_SOCK_FMT,
  1425. __func__, evcon->address, evcon->port,
  1426. EV_SOCK_ARG(evcon->fd)));
  1427. goto cleanup;
  1428. }
  1429. if (error) {
  1430. event_debug(("%s: connect failed for \"%s:%d\" on "
  1431. EV_SOCK_FMT": %s",
  1432. __func__, evcon->address, evcon->port,
  1433. EV_SOCK_ARG(evcon->fd),
  1434. evutil_socket_error_to_string(error)));
  1435. goto cleanup;
  1436. }
  1437. /* We are connected to the server now */
  1438. event_debug(("%s: connected to \"%s:%d\" on "EV_SOCK_FMT"\n",
  1439. __func__, evcon->address, evcon->port,
  1440. EV_SOCK_ARG(evcon->fd)));
  1441. /* Reset the retry count as we were successful in connecting */
  1442. evcon->retry_cnt = 0;
  1443. evcon->state = EVCON_IDLE;
  1444. /* reset the bufferevent cbs */
  1445. bufferevent_setcb(evcon->bufev,
  1446. evhttp_read_cb,
  1447. evhttp_write_cb,
  1448. evhttp_error_cb,
  1449. evcon);
  1450. if (!evutil_timerisset(&evcon->timeout)) {
  1451. const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
  1452. const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
  1453. bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
  1454. } else {
  1455. bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
  1456. }
  1457. /* try to start requests that have queued up on this connection */
  1458. evhttp_request_dispatch(evcon);
  1459. return;
  1460. cleanup:
  1461. evhttp_connection_cb_cleanup(evcon);
  1462. }
  1463. /*
  1464. * Check if we got a valid response code.
  1465. */
  1466. static int
  1467. evhttp_valid_response_code(int code)
  1468. {
  1469. if (code == 0)
  1470. return (0);
  1471. return (1);
  1472. }
  1473. static int
  1474. evhttp_parse_http_version(const char *version, struct evhttp_request *req)
  1475. {
  1476. int major, minor;
  1477. char ch;
  1478. int n = sscanf(version, "HTTP/%d.%d%c", &major, &minor, &ch);
  1479. if (n != 2 || major > 1) {
  1480. event_debug(("%s: bad version %s on message %p from %s",
  1481. __func__, version, req, req->remote_host));
  1482. return (-1);
  1483. }
  1484. req->major = major;
  1485. req->minor = minor;
  1486. return (0);
  1487. }
  1488. /* Parses the status line of a web server */
  1489. static int
  1490. evhttp_parse_response_line(struct evhttp_request *req, char *line)
  1491. {
  1492. char *protocol;
  1493. char *number;
  1494. const char *readable = "";
  1495. protocol = strsep(&line, " ");
  1496. if (line == NULL)
  1497. return (-1);
  1498. number = strsep(&line, " ");
  1499. if (line != NULL)
  1500. readable = line;
  1501. if (evhttp_parse_http_version(protocol, req) < 0)
  1502. return (-1);
  1503. req->response_code = atoi(number);
  1504. if (!evhttp_valid_response_code(req->response_code)) {
  1505. event_debug(("%s: bad response code \"%s\"",
  1506. __func__, number));
  1507. return (-1);
  1508. }
  1509. if (req->response_code_line != NULL)
  1510. mm_free(req->response_code_line);
  1511. if ((req->response_code_line = mm_strdup(readable)) == NULL) {
  1512. event_warn("%s: strdup", __func__);
  1513. return (-1);
  1514. }
  1515. return (0);
  1516. }
  1517. /* Parse the first line of a HTTP request */
  1518. static int
  1519. evhttp_parse_request_line(struct evhttp_request *req, char *line, size_t len)
  1520. {
  1521. char *eos = line + len;
  1522. char *method;
  1523. char *uri;
  1524. char *version;
  1525. const char *hostname;
  1526. const char *scheme;
  1527. size_t method_len;
  1528. enum evhttp_cmd_type type;
  1529. while (eos > line && *(eos-1) == ' ') {
  1530. *(eos-1) = '\0';
  1531. --eos;
  1532. --len;
  1533. }
  1534. if (len < strlen("GET / HTTP/1.0"))
  1535. return -1;
  1536. /* Parse the request line */
  1537. method = strsep(&line, " ");
  1538. if (!line)
  1539. return -1;
  1540. uri = line;
  1541. version = strrchr(uri, ' ');
  1542. if (!version || uri == version)
  1543. return -1;
  1544. *version = '\0';
  1545. version++;
  1546. method_len = (uri - method) - 1;
  1547. type = EVHTTP_REQ_UNKNOWN_;
  1548. /* First line */
  1549. switch (method_len) {
  1550. case 3:
  1551. /* The length of the method string is 3, meaning it can only be one of two methods: GET or PUT */
  1552. /* Since both GET and PUT share the same character 'T' at the end,
  1553. * if the string doesn't have 'T', we can immediately determine this
  1554. * is an invalid HTTP method */
  1555. if (method[2] != 'T') {
  1556. break;
  1557. }
  1558. switch (*method) {
  1559. case 'G':
  1560. /* This first byte is 'G', so make sure the next byte is
  1561. * 'E', if it isn't then this isn't a valid method */
  1562. if (method[1] == 'E') {
  1563. type = EVHTTP_REQ_GET;
  1564. }
  1565. break;
  1566. case 'P':
  1567. /* First byte is P, check second byte for 'U', if not,
  1568. * we know it's an invalid method */
  1569. if (method[1] == 'U') {
  1570. type = EVHTTP_REQ_PUT;
  1571. }
  1572. break;
  1573. default:
  1574. break;
  1575. }
  1576. break;
  1577. case 4:
  1578. /* The method length is 4 bytes, leaving only the methods "POST" and "HEAD" */
  1579. switch (*method) {
  1580. case 'P':
  1581. if (method[3] == 'T' && method[2] == 'S' && method[1] == 'O') {
  1582. type = EVHTTP_REQ_POST;
  1583. }
  1584. break;
  1585. case 'H':
  1586. if (method[3] == 'D' && method[2] == 'A' && method[1] == 'E') {
  1587. type = EVHTTP_REQ_HEAD;
  1588. }
  1589. break;
  1590. default:
  1591. break;
  1592. }
  1593. break;
  1594. case 5:
  1595. /* Method length is 5 bytes, which can only encompass PATCH and TRACE */
  1596. switch (*method) {
  1597. case 'P':
  1598. if (method[4] == 'H' && method[3] == 'C' && method[2] == 'T' && method[1] == 'A') {
  1599. type = EVHTTP_REQ_PATCH;
  1600. }
  1601. break;
  1602. case 'T':
  1603. if (method[4] == 'E' && method[3] == 'C' && method[2] == 'A' && method[1] == 'R') {
  1604. type = EVHTTP_REQ_TRACE;
  1605. }
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. break;
  1611. case 6:
  1612. /* Method length is 6, only valid method 6 bytes in length is DELEte */
  1613. /* If the first byte isn't 'D' then it's invalid */
  1614. if (*method != 'D') {
  1615. break;
  1616. }
  1617. if (method[5] == 'E' && method[4] == 'T' && method[3] == 'E' && method[2] == 'L' && method[1] == 'E') {
  1618. type = EVHTTP_REQ_DELETE;
  1619. }
  1620. break;
  1621. case 7:
  1622. /* Method length is 7, only valid methods are "OPTIONS" and "CONNECT" */
  1623. switch (*method) {
  1624. case 'O':
  1625. if (method[6] == 'S' && method[5] == 'N' && method[4] == 'O' &&
  1626. method[3] == 'I' && method[2] == 'T' && method[1] == 'P') {
  1627. type = EVHTTP_REQ_OPTIONS;
  1628. }
  1629. break;
  1630. case 'C':
  1631. if (method[6] == 'T' && method[5] == 'C' && method[4] == 'E' &&
  1632. method[3] == 'N' && method[2] == 'N' && method[1] == 'O') {
  1633. type = EVHTTP_REQ_CONNECT;
  1634. }
  1635. break;
  1636. default:
  1637. break;
  1638. }
  1639. break;
  1640. } /* switch */
  1641. if ((int)type == EVHTTP_REQ_UNKNOWN_) {
  1642. event_debug(("%s: bad method %s on request %p from %s",
  1643. __func__, method, req, req->remote_host));
  1644. /* No error yet; we'll give a better error later when
  1645. * we see that req->type is unsupported. */
  1646. }
  1647. req->type = type;
  1648. if (evhttp_parse_http_version(version, req) < 0)
  1649. return -1;
  1650. if ((req->uri = mm_strdup(uri)) == NULL) {
  1651. event_debug(("%s: mm_strdup", __func__));
  1652. return -1;
  1653. }
  1654. if (type == EVHTTP_REQ_CONNECT) {
  1655. if ((req->uri_elems = evhttp_uri_parse_authority(req->uri)) == NULL) {
  1656. return -1;
  1657. }
  1658. } else {
  1659. if ((req->uri_elems = evhttp_uri_parse_with_flags(req->uri,
  1660. EVHTTP_URI_NONCONFORMANT)) == NULL) {
  1661. return -1;
  1662. }
  1663. }
  1664. /* If we have an absolute-URI, check to see if it is an http request
  1665. for a known vhost or server alias. If we don't know about this
  1666. host, we consider it a proxy request. */
  1667. scheme = evhttp_uri_get_scheme(req->uri_elems);
  1668. hostname = evhttp_uri_get_host(req->uri_elems);
  1669. if (scheme && (!evutil_ascii_strcasecmp(scheme, "http") ||
  1670. !evutil_ascii_strcasecmp(scheme, "https")) &&
  1671. hostname &&
  1672. !evhttp_find_vhost(req->evcon->http_server, NULL, hostname))
  1673. req->flags |= EVHTTP_PROXY_REQUEST;
  1674. {
  1675. struct evhttp_cb * chunkcb = evhttp_dispatch_callback(&req->evcon->http_server->callbacks, req, 1);
  1676. if (chunkcb) {
  1677. req->chunk_cb = chunkcb->cb;
  1678. req->chunk_cb_arg = chunkcb->cbarg;
  1679. }
  1680. }
  1681. return 0;
  1682. }
  1683. const char *
  1684. evhttp_find_header(const struct evkeyvalq *headers, const char *key)
  1685. {
  1686. struct evkeyval *header;
  1687. TAILQ_FOREACH(header, headers, next) {
  1688. if (evutil_ascii_strcasecmp(header->key, key) == 0)
  1689. return (header->value);
  1690. }
  1691. return (NULL);
  1692. }
  1693. void
  1694. evhttp_clear_headers(struct evkeyvalq *headers)
  1695. {
  1696. struct evkeyval *header;
  1697. for (header = TAILQ_FIRST(headers);
  1698. header != NULL;
  1699. header = TAILQ_FIRST(headers)) {
  1700. TAILQ_REMOVE(headers, header, next);
  1701. mm_free(header->key);
  1702. mm_free(header->value);
  1703. mm_free(header);
  1704. }
  1705. }
  1706. /*
  1707. * Returns 0, if the header was successfully removed.
  1708. * Returns -1, if the header could not be found.
  1709. */
  1710. int
  1711. evhttp_remove_header(struct evkeyvalq *headers, const char *key)
  1712. {
  1713. struct evkeyval *header;
  1714. TAILQ_FOREACH(header, headers, next) {
  1715. if (evutil_ascii_strcasecmp(header->key, key) == 0)
  1716. break;
  1717. }
  1718. if (header == NULL)
  1719. return (-1);
  1720. /* Free and remove the header that we found */
  1721. TAILQ_REMOVE(headers, header, next);
  1722. mm_free(header->key);
  1723. mm_free(header->value);
  1724. mm_free(header);
  1725. return (0);
  1726. }
  1727. static int
  1728. evhttp_header_is_valid_value(const char *value)
  1729. {
  1730. const char *p = value;
  1731. while ((p = strpbrk(p, "\r\n")) != NULL) {
  1732. /* we really expect only one new line */
  1733. p += strspn(p, "\r\n");
  1734. /* we expect a space or tab for continuation */
  1735. if (*p != ' ' && *p != '\t')
  1736. return (0);
  1737. }
  1738. return (1);
  1739. }
  1740. int
  1741. evhttp_add_header(struct evkeyvalq *headers,
  1742. const char *key, const char *value)
  1743. {
  1744. event_debug(("%s: key: %s val: %s\n", __func__, key, value));
  1745. if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
  1746. /* drop illegal headers */
  1747. event_debug(("%s: dropping illegal header key\n", __func__));
  1748. return (-1);
  1749. }
  1750. if (!evhttp_header_is_valid_value(value)) {
  1751. event_debug(("%s: dropping illegal header value\n", __func__));
  1752. return (-1);
  1753. }
  1754. return (evhttp_add_header_internal(headers, key, value));
  1755. }
  1756. static int
  1757. evhttp_add_header_internal(struct evkeyvalq *headers,
  1758. const char *key, const char *value)
  1759. {
  1760. struct evkeyval *header = mm_calloc(1, sizeof(struct evkeyval));
  1761. if (header == NULL) {
  1762. event_warn("%s: calloc", __func__);
  1763. return (-1);
  1764. }
  1765. if ((header->key = mm_strdup(key)) == NULL) {
  1766. mm_free(header);
  1767. event_warn("%s: strdup", __func__);
  1768. return (-1);
  1769. }
  1770. if ((header->value = mm_strdup(value)) == NULL) {
  1771. mm_free(header->key);
  1772. mm_free(header);
  1773. event_warn("%s: strdup", __func__);
  1774. return (-1);
  1775. }
  1776. TAILQ_INSERT_TAIL(headers, header, next);
  1777. return (0);
  1778. }
  1779. /*
  1780. * Parses header lines from a request or a response into the specified
  1781. * request object given an event buffer.
  1782. *
  1783. * Returns
  1784. * DATA_CORRUPTED on error
  1785. * MORE_DATA_EXPECTED when we need to read more headers
  1786. * ALL_DATA_READ when all headers have been read.
  1787. */
  1788. enum message_read_status
  1789. evhttp_parse_firstline_(struct evhttp_request *req, struct evbuffer *buffer)
  1790. {
  1791. char *line;
  1792. enum message_read_status status = ALL_DATA_READ;
  1793. size_t len;
  1794. /* XXX try */
  1795. line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF);
  1796. if (line == NULL) {
  1797. if (req->evcon != NULL &&
  1798. evbuffer_get_length(buffer) > req->evcon->max_headers_size)
  1799. return (DATA_TOO_LONG);
  1800. else
  1801. return (MORE_DATA_EXPECTED);
  1802. }
  1803. if (req->evcon != NULL && len > req->evcon->max_headers_size) {
  1804. mm_free(line);
  1805. return (DATA_TOO_LONG);
  1806. }
  1807. req->headers_size = len;
  1808. switch (req->kind) {
  1809. case EVHTTP_REQUEST:
  1810. if (evhttp_parse_request_line(req, line, len) == -1)
  1811. status = DATA_CORRUPTED;
  1812. break;
  1813. case EVHTTP_RESPONSE:
  1814. if (evhttp_parse_response_line(req, line) == -1)
  1815. status = DATA_CORRUPTED;
  1816. break;
  1817. default:
  1818. status = DATA_CORRUPTED;
  1819. }
  1820. mm_free(line);
  1821. return (status);
  1822. }
  1823. static int
  1824. evhttp_append_to_last_header(struct evkeyvalq *headers, char *line)
  1825. {
  1826. struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
  1827. char *newval;
  1828. size_t old_len, line_len;
  1829. if (header == NULL)
  1830. return (-1);
  1831. old_len = strlen(header->value);
  1832. /* Strip space from start and end of line. */
  1833. while (*line == ' ' || *line == '\t')
  1834. ++line;
  1835. evutil_rtrim_lws_(line);
  1836. line_len = strlen(line);
  1837. newval = mm_realloc(header->value, old_len + line_len + 2);
  1838. if (newval == NULL)
  1839. return (-1);
  1840. newval[old_len] = ' ';
  1841. memcpy(newval + old_len + 1, line, line_len + 1);
  1842. header->value = newval;
  1843. return (0);
  1844. }
  1845. enum message_read_status
  1846. evhttp_parse_headers_(struct evhttp_request *req, struct evbuffer* buffer)
  1847. {
  1848. enum message_read_status errcode = DATA_CORRUPTED;
  1849. char *line;
  1850. enum message_read_status status = MORE_DATA_EXPECTED;
  1851. struct evkeyvalq* headers = req->input_headers;
  1852. size_t len;
  1853. while ((line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF))
  1854. != NULL) {
  1855. char *skey, *svalue;
  1856. req->headers_size += len;
  1857. if (req->evcon != NULL &&
  1858. req->headers_size > req->evcon->max_headers_size) {
  1859. errcode = DATA_TOO_LONG;
  1860. goto error;
  1861. }
  1862. if (*line == '\0') { /* Last header - Done */
  1863. status = ALL_DATA_READ;
  1864. mm_free(line);
  1865. break;
  1866. }
  1867. /* Check if this is a continuation line */
  1868. if (*line == ' ' || *line == '\t') {
  1869. if (evhttp_append_to_last_header(headers, line) == -1)
  1870. goto error;
  1871. mm_free(line);
  1872. continue;
  1873. }
  1874. /* Processing of header lines */
  1875. svalue = line;
  1876. skey = strsep(&svalue, ":");
  1877. if (svalue == NULL)
  1878. goto error;
  1879. svalue += strspn(svalue, " ");
  1880. evutil_rtrim_lws_(svalue);
  1881. if (evhttp_add_header(headers, skey, svalue) == -1)
  1882. goto error;
  1883. mm_free(line);
  1884. }
  1885. if (status == MORE_DATA_EXPECTED) {
  1886. if (req->evcon != NULL &&
  1887. req->headers_size + evbuffer_get_length(buffer) > req->evcon->max_headers_size)
  1888. return (DATA_TOO_LONG);
  1889. }
  1890. return (status);
  1891. error:
  1892. mm_free(line);
  1893. return (errcode);
  1894. }
  1895. static int
  1896. evhttp_get_body_length(struct evhttp_request *req)
  1897. {
  1898. struct evkeyvalq *headers = req->input_headers;
  1899. const char *content_length;
  1900. const char *connection;
  1901. content_length = evhttp_find_header(headers, "Content-Length");
  1902. connection = evhttp_find_header(headers, "Connection");
  1903. if (content_length == NULL && connection == NULL)
  1904. req->ntoread = -1;
  1905. else if (content_length == NULL &&
  1906. evutil_ascii_strcasecmp(connection, "Close") != 0) {
  1907. req->ntoread = 0;
  1908. } else if (content_length == NULL) {
  1909. req->ntoread = -1;
  1910. } else {
  1911. char *endp;
  1912. ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
  1913. if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
  1914. event_debug(("%s: illegal content length: %s",
  1915. __func__, content_length));
  1916. return (-1);
  1917. }
  1918. req->ntoread = ntoread;
  1919. }
  1920. event_debug(("%s: bytes to read: "EV_I64_FMT" (in buffer "EV_SIZE_FMT")\n",
  1921. __func__, EV_I64_ARG(req->ntoread),
  1922. EV_SIZE_ARG(evbuffer_get_length(bufferevent_get_input(req->evcon->bufev)))));
  1923. return (0);
  1924. }
  1925. static int
  1926. evhttp_method_may_have_body(enum evhttp_cmd_type type)
  1927. {
  1928. switch (type) {
  1929. case EVHTTP_REQ_POST:
  1930. case EVHTTP_REQ_PUT:
  1931. case EVHTTP_REQ_PATCH:
  1932. case EVHTTP_REQ_GET:
  1933. case EVHTTP_REQ_DELETE:
  1934. case EVHTTP_REQ_OPTIONS:
  1935. case EVHTTP_REQ_CONNECT:
  1936. return 1;
  1937. case EVHTTP_REQ_TRACE:
  1938. case EVHTTP_REQ_HEAD:
  1939. default:
  1940. return 0;
  1941. }
  1942. }
  1943. static void
  1944. evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
  1945. {
  1946. const char *xfer_enc;
  1947. /* If this is a request without a body, then we are done */
  1948. if (req->kind == EVHTTP_REQUEST &&
  1949. !evhttp_method_may_have_body(req->type)) {
  1950. evhttp_connection_done(evcon);
  1951. return;
  1952. }
  1953. evcon->state = EVCON_READING_BODY;
  1954. xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
  1955. if (xfer_enc != NULL && evutil_ascii_strcasecmp(xfer_enc, "chunked") == 0) {
  1956. req->chunked = 1;
  1957. req->ntoread = -1;
  1958. } else {
  1959. if (evhttp_get_body_length(req) == -1) {
  1960. evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
  1961. return;
  1962. }
  1963. if (req->kind == EVHTTP_REQUEST && req->ntoread < 1) {
  1964. /* An incoming request with no content-length and no
  1965. * transfer-encoding has no body. */
  1966. evhttp_connection_done(evcon);
  1967. return;
  1968. }
  1969. }
  1970. /* Should we send a 100 Continue status line? */
  1971. switch (evhttp_have_expect(req, 1)) {
  1972. case CONTINUE:
  1973. /* XXX It would be nice to do some sanity
  1974. checking here. Does the resource exist?
  1975. Should the resource accept post requests? If
  1976. no, we should respond with an error. For
  1977. now, just optimistically tell the client to
  1978. send their message body. */
  1979. if (req->ntoread > 0) {
  1980. /* ntoread is ev_int64_t, max_body_size is ev_uint64_t */
  1981. if ((req->evcon->max_body_size <= EV_INT64_MAX) &&
  1982. (ev_uint64_t)req->ntoread > req->evcon->max_body_size) {
  1983. evhttp_lingering_fail(evcon, req);
  1984. return;
  1985. }
  1986. }
  1987. if (!evbuffer_get_length(bufferevent_get_input(evcon->bufev)))
  1988. evhttp_send_continue(evcon, req);
  1989. break;
  1990. case OTHER:
  1991. evhttp_send_error(req, HTTP_EXPECTATIONFAILED, NULL);
  1992. return;
  1993. case NO: break;
  1994. }
  1995. evhttp_read_body(evcon, req);
  1996. /* note the request may have been freed in evhttp_read_body */
  1997. }
  1998. static void
  1999. evhttp_read_firstline(struct evhttp_connection *evcon,
  2000. struct evhttp_request *req)
  2001. {
  2002. enum message_read_status res;
  2003. res = evhttp_parse_firstline_(req, bufferevent_get_input(evcon->bufev));
  2004. if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
  2005. /* Error while reading, terminate */
  2006. event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
  2007. __func__, EV_SOCK_ARG(evcon->fd)));
  2008. evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
  2009. return;
  2010. } else if (res == MORE_DATA_EXPECTED) {
  2011. /* Need more header lines */
  2012. return;
  2013. }
  2014. evcon->state = EVCON_READING_HEADERS;
  2015. evhttp_read_header(evcon, req);
  2016. }
  2017. static void
  2018. evhttp_read_header(struct evhttp_connection *evcon,
  2019. struct evhttp_request *req)
  2020. {
  2021. enum message_read_status res;
  2022. evutil_socket_t fd = evcon->fd;
  2023. res = evhttp_parse_headers_(req, bufferevent_get_input(evcon->bufev));
  2024. if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
  2025. /* Error while reading, terminate */
  2026. event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
  2027. __func__, EV_SOCK_ARG(fd)));
  2028. evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
  2029. return;
  2030. } else if (res == MORE_DATA_EXPECTED) {
  2031. /* Need more header lines */
  2032. return;
  2033. }
  2034. /* Callback can shut down connection with negative return value */
  2035. if (req->header_cb != NULL) {
  2036. if ((*req->header_cb)(req, req->cb_arg) < 0) {
  2037. evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
  2038. return;
  2039. }
  2040. }
  2041. /* Done reading headers, do the real work */
  2042. switch (req->kind) {
  2043. case EVHTTP_REQUEST:
  2044. event_debug(("%s: checking for post data on "EV_SOCK_FMT"\n",
  2045. __func__, EV_SOCK_ARG(fd)));
  2046. evhttp_get_body(evcon, req);
  2047. /* note the request may have been freed in evhttp_get_body */
  2048. break;
  2049. case EVHTTP_RESPONSE:
  2050. /* Start over if we got a 100 Continue response. */
  2051. if (req->response_code == 100) {
  2052. struct evbuffer *output = bufferevent_get_output(evcon->bufev);
  2053. evbuffer_add_buffer(output, req->output_buffer);
  2054. evhttp_start_write_(evcon);
  2055. return;
  2056. }
  2057. if (!evhttp_response_needs_body(req)) {
  2058. event_debug(("%s: skipping body for code %d\n",
  2059. __func__, req->response_code));
  2060. evhttp_connection_done(evcon);
  2061. } else {
  2062. event_debug(("%s: start of read body for %s on "
  2063. EV_SOCK_FMT"\n",
  2064. __func__, req->remote_host, EV_SOCK_ARG(fd)));
  2065. evhttp_get_body(evcon, req);
  2066. /* note the request may have been freed in
  2067. * evhttp_get_body */
  2068. }
  2069. break;
  2070. default:
  2071. event_warnx("%s: bad header on "EV_SOCK_FMT, __func__,
  2072. EV_SOCK_ARG(fd));
  2073. evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
  2074. break;
  2075. }
  2076. /* request may have been freed above */
  2077. }
  2078. /*
  2079. * Creates a TCP connection to the specified port and executes a callback
  2080. * when finished. Failure or success is indicate by the passed connection
  2081. * object.
  2082. *
  2083. * Although this interface accepts a hostname, it is intended to take
  2084. * only numeric hostnames so that non-blocking DNS resolution can
  2085. * happen elsewhere.
  2086. */
  2087. struct evhttp_connection *evhttp_connection_base_bufferevent_factory_new(
  2088. struct event_base *base, struct evdns_base *dnsbase,
  2089. bev_factory_cb cb, void * arg, const char *address, unsigned short port)
  2090. {
  2091. struct bufferevent *bev = NULL;
  2092. if (NULL != cb) {
  2093. if (NULL == (bev = (*cb)(arg))) {
  2094. event_warn("%s: bufferevent factory callback failed", __func__);
  2095. return (NULL);
  2096. }
  2097. }
  2098. struct evhttp_connection *ret =
  2099. evhttp_connection_base_bufferevent_new(base, dnsbase, bev, address, port);
  2100. if (NULL != ret) {
  2101. ret->bufcb = cb;
  2102. ret->bufcb_arg = arg;
  2103. }
  2104. return (ret);
  2105. }
  2106. struct evhttp_connection *
  2107. evhttp_connection_new(const char *address, ev_uint16_t port)
  2108. {
  2109. return (evhttp_connection_base_new(NULL, NULL, address, port));
  2110. }
  2111. struct evhttp_connection *
  2112. evhttp_connection_base_bufferevent_new(struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev,
  2113. const char *address, ev_uint16_t port)
  2114. {
  2115. struct evhttp_connection *evcon = NULL;
  2116. event_debug(("Attempting connection to %s:%d\n", address, port));
  2117. if ((evcon = mm_calloc(1, sizeof(struct evhttp_connection))) == NULL) {
  2118. event_warn("%s: calloc failed", __func__);
  2119. goto error;
  2120. }
  2121. evcon->fd = -1;
  2122. evcon->port = port;
  2123. evcon->max_headers_size = EV_SIZE_MAX;
  2124. evcon->max_body_size = EV_SIZE_MAX;
  2125. evutil_timerclear(&evcon->timeout);
  2126. evcon->retry_cnt = evcon->retry_max = 0;
  2127. if ((evcon->address = mm_strdup(address)) == NULL) {
  2128. event_warn("%s: strdup failed", __func__);
  2129. goto error;
  2130. }
  2131. if (bev == NULL) {
  2132. if (!(bev = bufferevent_socket_new(base, -1, 0))) {
  2133. event_warn("%s: bufferevent_socket_new failed", __func__);
  2134. goto error;
  2135. }
  2136. }
  2137. bufferevent_setcb(bev, evhttp_read_cb, evhttp_write_cb, evhttp_error_cb, evcon);
  2138. evcon->bufev = bev;
  2139. evcon->state = EVCON_DISCONNECTED;
  2140. TAILQ_INIT(&evcon->requests);
  2141. evcon->initial_retry_timeout.tv_sec = 2;
  2142. evcon->initial_retry_timeout.tv_usec = 0;
  2143. if (base != NULL) {
  2144. evcon->base = base;
  2145. if (bufferevent_get_base(bev) != base)
  2146. bufferevent_base_set(base, evcon->bufev);
  2147. }
  2148. event_deferred_cb_init_(
  2149. &evcon->read_more_deferred_cb,
  2150. bufferevent_get_priority(bev),
  2151. evhttp_deferred_read_cb, evcon);
  2152. evcon->dns_base = dnsbase;
  2153. evcon->ai_family = AF_UNSPEC;
  2154. return (evcon);
  2155. error:
  2156. if (evcon != NULL)
  2157. evhttp_connection_free(evcon);
  2158. return (NULL);
  2159. }
  2160. struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon)
  2161. {
  2162. return evcon->bufev;
  2163. }
  2164. struct evhttp *
  2165. evhttp_connection_get_server(struct evhttp_connection *evcon)
  2166. {
  2167. return evcon->http_server;
  2168. }
  2169. struct evhttp_connection *
  2170. evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
  2171. const char *address, ev_uint16_t port)
  2172. {
  2173. return evhttp_connection_base_bufferevent_new(base, dnsbase, NULL, address, port);
  2174. }
  2175. void evhttp_connection_set_family(struct evhttp_connection *evcon,
  2176. int family)
  2177. {
  2178. evcon->ai_family = family;
  2179. }
  2180. int evhttp_connection_set_flags(struct evhttp_connection *evcon,
  2181. int flags)
  2182. {
  2183. int avail_flags = 0;
  2184. avail_flags |= EVHTTP_CON_REUSE_CONNECTED_ADDR;
  2185. avail_flags |= EVHTTP_CON_READ_ON_WRITE_ERROR;
  2186. if (flags & ~avail_flags || flags > EVHTTP_CON_PUBLIC_FLAGS_END)
  2187. return 1;
  2188. evcon->flags &= ~avail_flags;
  2189. evcon->flags |= flags;
  2190. return 0;
  2191. }
  2192. void
  2193. evhttp_connection_set_base(struct evhttp_connection *evcon,
  2194. struct event_base *base)
  2195. {
  2196. EVUTIL_ASSERT(evcon->base == NULL);
  2197. EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
  2198. evcon->base = base;
  2199. bufferevent_base_set(base, evcon->bufev);
  2200. }
  2201. void
  2202. evhttp_connection_set_timeout(struct evhttp_connection *evcon,
  2203. int timeout_in_secs)
  2204. {
  2205. if (timeout_in_secs == -1)
  2206. evhttp_connection_set_timeout_tv(evcon, NULL);
  2207. else {
  2208. struct timeval tv;
  2209. tv.tv_sec = timeout_in_secs;
  2210. tv.tv_usec = 0;
  2211. evhttp_connection_set_timeout_tv(evcon, &tv);
  2212. }
  2213. }
  2214. void
  2215. evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
  2216. const struct timeval* tv)
  2217. {
  2218. if (tv) {
  2219. evcon->timeout = *tv;
  2220. bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
  2221. } else {
  2222. const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
  2223. const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
  2224. evutil_timerclear(&evcon->timeout);
  2225. bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
  2226. }
  2227. }
  2228. void
  2229. evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
  2230. const struct timeval *tv)
  2231. {
  2232. if (tv) {
  2233. evcon->initial_retry_timeout = *tv;
  2234. } else {
  2235. evutil_timerclear(&evcon->initial_retry_timeout);
  2236. evcon->initial_retry_timeout.tv_sec = 2;
  2237. }
  2238. }
  2239. void
  2240. evhttp_connection_set_retries(struct evhttp_connection *evcon,
  2241. int retry_max)
  2242. {
  2243. evcon->retry_max = retry_max;
  2244. }
  2245. void
  2246. evhttp_connection_set_closecb(struct evhttp_connection *evcon,
  2247. void (*cb)(struct evhttp_connection *, void *), void *cbarg)
  2248. {
  2249. evcon->closecb = cb;
  2250. evcon->closecb_arg = cbarg;
  2251. }
  2252. void
  2253. evhttp_connection_get_peer(struct evhttp_connection *evcon,
  2254. char **address, ev_uint16_t *port)
  2255. {
  2256. *address = evcon->address;
  2257. *port = evcon->port;
  2258. }
  2259. const struct sockaddr*
  2260. evhttp_connection_get_addr(struct evhttp_connection *evcon)
  2261. {
  2262. return bufferevent_socket_get_conn_address_(evcon->bufev);
  2263. }
  2264. int
  2265. evhttp_connection_connect_(struct evhttp_connection *evcon)
  2266. {
  2267. int old_state = evcon->state;
  2268. const char *address = evcon->address;
  2269. const struct sockaddr *sa = evhttp_connection_get_addr(evcon);
  2270. int ret;
  2271. if (evcon->state == EVCON_CONNECTING)
  2272. return (0);
  2273. evhttp_connection_reset_(evcon);
  2274. EVUTIL_ASSERT(!(evcon->flags & EVHTTP_CON_INCOMING));
  2275. evcon->flags |= EVHTTP_CON_OUTGOING;
  2276. if (evcon->bind_address || evcon->bind_port) {
  2277. evcon->fd = bind_socket(
  2278. evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
  2279. if (evcon->fd == -1) {
  2280. event_debug(("%s: failed to bind to \"%s\"",
  2281. __func__, evcon->bind_address));
  2282. return (-1);
  2283. }
  2284. if (bufferevent_setfd(evcon->bufev, evcon->fd))
  2285. return (-1);
  2286. } else {
  2287. if (bufferevent_setfd(evcon->bufev, -1))
  2288. return (-1);
  2289. }
  2290. /* Set up a callback for successful connection setup */
  2291. bufferevent_setcb(evcon->bufev,
  2292. NULL /* evhttp_read_cb */,
  2293. NULL /* evhttp_write_cb */,
  2294. evhttp_connection_cb,
  2295. evcon);
  2296. if (!evutil_timerisset(&evcon->timeout)) {
  2297. const struct timeval conn_tv = { HTTP_CONNECT_TIMEOUT, 0 };
  2298. bufferevent_set_timeouts(evcon->bufev, &conn_tv, &conn_tv);
  2299. } else {
  2300. bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
  2301. }
  2302. /* make sure that we get a write callback */
  2303. if (bufferevent_enable(evcon->bufev, EV_WRITE))
  2304. return (-1);
  2305. evcon->state = EVCON_CONNECTING;
  2306. if (evcon->flags & EVHTTP_CON_REUSE_CONNECTED_ADDR &&
  2307. sa &&
  2308. (sa->sa_family == AF_INET || sa->sa_family == AF_INET6)) {
  2309. int socklen = sizeof(struct sockaddr_in);
  2310. if (sa->sa_family == AF_INET6) {
  2311. socklen = sizeof(struct sockaddr_in6);
  2312. }
  2313. ret = bufferevent_socket_connect(evcon->bufev, sa, socklen);
  2314. } else {
  2315. ret = bufferevent_socket_connect_hostname(evcon->bufev,
  2316. evcon->dns_base, evcon->ai_family, address, evcon->port);
  2317. }
  2318. if (ret < 0) {
  2319. evcon->state = old_state;
  2320. event_sock_warn(evcon->fd, "%s: connection to \"%s\" failed",
  2321. __func__, evcon->address);
  2322. /* some operating systems return ECONNREFUSED immediately
  2323. * when connecting to a local address. the cleanup is going
  2324. * to reschedule this function call.
  2325. */
  2326. evhttp_connection_cb_cleanup(evcon);
  2327. return (0);
  2328. }
  2329. return (0);
  2330. }
  2331. /*
  2332. * Starts an HTTP request on the provided evhttp_connection object.
  2333. * If the connection object is not connected to the web server already,
  2334. * this will start the connection.
  2335. */
  2336. int
  2337. evhttp_make_request(struct evhttp_connection *evcon,
  2338. struct evhttp_request *req,
  2339. enum evhttp_cmd_type type, const char *uri)
  2340. {
  2341. /* We are making a request */
  2342. req->kind = EVHTTP_REQUEST;
  2343. req->type = type;
  2344. if (req->uri != NULL)
  2345. mm_free(req->uri);
  2346. if ((req->uri = mm_strdup(uri)) == NULL) {
  2347. event_warn("%s: strdup", __func__);
  2348. evhttp_request_free_auto(req);
  2349. return (-1);
  2350. }
  2351. /* Set the protocol version if it is not supplied */
  2352. if (!req->major && !req->minor) {
  2353. req->major = 1;
  2354. req->minor = 1;
  2355. }
  2356. EVUTIL_ASSERT(req->evcon == NULL);
  2357. req->evcon = evcon;
  2358. EVUTIL_ASSERT(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
  2359. TAILQ_INSERT_TAIL(&evcon->requests, req, next);
  2360. /* We do not want to conflict with retry_ev */
  2361. if (evcon->retry_cnt)
  2362. return (0);
  2363. /* If the connection object is not connected; make it so */
  2364. if (!evhttp_connected(evcon)) {
  2365. int res = evhttp_connection_connect_(evcon);
  2366. /* evhttp_connection_fail_(), which is called through
  2367. * evhttp_connection_connect_(), assumes that req lies in
  2368. * evcon->requests. Thus, enqueue the request in advance and
  2369. * remove it in the error case. */
  2370. if (res != 0)
  2371. TAILQ_REMOVE(&evcon->requests, req, next);
  2372. return (res);
  2373. }
  2374. /*
  2375. * If it's connected already and we are the first in the queue,
  2376. * then we can dispatch this request immediately. Otherwise, it
  2377. * will be dispatched once the pending requests are completed.
  2378. */
  2379. if (TAILQ_FIRST(&evcon->requests) == req)
  2380. evhttp_request_dispatch(evcon);
  2381. return (0);
  2382. }
  2383. void
  2384. evhttp_cancel_request(struct evhttp_request *req)
  2385. {
  2386. struct evhttp_connection *evcon = req->evcon;
  2387. if (evcon != NULL) {
  2388. /* We need to remove it from the connection */
  2389. if (TAILQ_FIRST(&evcon->requests) == req) {
  2390. /* it's currently being worked on, so reset
  2391. * the connection.
  2392. */
  2393. evhttp_connection_fail_(evcon,
  2394. EVREQ_HTTP_REQUEST_CANCEL);
  2395. /* connection fail freed the request */
  2396. return;
  2397. } else {
  2398. /* otherwise, we can just remove it from the
  2399. * queue
  2400. */
  2401. TAILQ_REMOVE(&evcon->requests, req, next);
  2402. }
  2403. }
  2404. evhttp_request_free_auto(req);
  2405. }
  2406. /*
  2407. * Reads data from file descriptor into request structure
  2408. * Request structure needs to be set up correctly.
  2409. */
  2410. void
  2411. evhttp_start_read_(struct evhttp_connection *evcon)
  2412. {
  2413. bufferevent_disable(evcon->bufev, EV_WRITE);
  2414. bufferevent_enable(evcon->bufev, EV_READ);
  2415. evcon->state = EVCON_READING_FIRSTLINE;
  2416. /* Reset the bufferevent callbacks */
  2417. bufferevent_setcb(evcon->bufev,
  2418. evhttp_read_cb,
  2419. evhttp_write_cb,
  2420. evhttp_error_cb,
  2421. evcon);
  2422. /* If there's still data pending, process it next time through the
  2423. * loop. Don't do it now; that could get recusive. */
  2424. if (evbuffer_get_length(bufferevent_get_input(evcon->bufev))) {
  2425. event_deferred_cb_schedule_(get_deferred_queue(evcon),
  2426. &evcon->read_more_deferred_cb);
  2427. }
  2428. }
  2429. void
  2430. evhttp_start_write_(struct evhttp_connection *evcon)
  2431. {
  2432. bufferevent_disable(evcon->bufev, EV_WRITE);
  2433. bufferevent_enable(evcon->bufev, EV_READ);
  2434. evcon->state = EVCON_WRITING;
  2435. evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
  2436. }
  2437. static void
  2438. evhttp_send_done(struct evhttp_connection *evcon, void *arg)
  2439. {
  2440. int need_close;
  2441. struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
  2442. TAILQ_REMOVE(&evcon->requests, req, next);
  2443. if (req->on_complete_cb != NULL) {
  2444. req->on_complete_cb(req, req->on_complete_cb_arg);
  2445. }
  2446. need_close =
  2447. (REQ_VERSION_BEFORE(req, 1, 1) &&
  2448. !evhttp_is_connection_keepalive(req->input_headers)) ||
  2449. evhttp_is_request_connection_close(req);
  2450. EVUTIL_ASSERT(req->flags & EVHTTP_REQ_OWN_CONNECTION);
  2451. evhttp_request_free(req);
  2452. if (need_close) {
  2453. evhttp_connection_free(evcon);
  2454. return;
  2455. }
  2456. /* we have a persistent connection; try to accept another request. */
  2457. if (evhttp_associate_new_request_with_connection(evcon) == -1) {
  2458. evhttp_connection_free(evcon);
  2459. }
  2460. }
  2461. /*
  2462. * Returns an error page.
  2463. */
  2464. void
  2465. evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
  2466. {
  2467. #define ERR_FORMAT "<HTML><HEAD>\n" \
  2468. "<TITLE>%d %s</TITLE>\n" \
  2469. "</HEAD><BODY>\n" \
  2470. "<H1>%s</H1>\n" \
  2471. "</BODY></HTML>\n"
  2472. struct evbuffer *buf = evbuffer_new();
  2473. if (buf == NULL) {
  2474. /* if we cannot allocate memory; we just drop the connection */
  2475. evhttp_connection_free(req->evcon);
  2476. return;
  2477. }
  2478. if (reason == NULL) {
  2479. reason = evhttp_response_phrase_internal(error);
  2480. }
  2481. evhttp_response_code_(req, error, reason);
  2482. evbuffer_add_printf(buf, ERR_FORMAT, error, reason, reason);
  2483. evhttp_send_page_(req, buf);
  2484. evbuffer_free(buf);
  2485. #undef ERR_FORMAT
  2486. }
  2487. /* Requires that headers and response code are already set up */
  2488. static inline void
  2489. evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
  2490. {
  2491. struct evhttp_connection *evcon = req->evcon;
  2492. if (evcon == NULL) {
  2493. evhttp_request_free(req);
  2494. return;
  2495. }
  2496. EVUTIL_ASSERT(TAILQ_FIRST(&evcon->requests) == req);
  2497. /* we expect no more calls form the user on this request */
  2498. req->userdone = 1;
  2499. /* xxx: not sure if we really should expose the data buffer this way */
  2500. if (databuf != NULL)
  2501. evbuffer_add_buffer(req->output_buffer, databuf);
  2502. /* Adds headers to the response */
  2503. evhttp_make_header(evcon, req);
  2504. evhttp_write_buffer(evcon, evhttp_send_done, NULL);
  2505. }
  2506. void
  2507. evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
  2508. struct evbuffer *databuf)
  2509. {
  2510. evhttp_response_code_(req, code, reason);
  2511. evhttp_send(req, databuf);
  2512. }
  2513. void
  2514. evhttp_send_reply_start(struct evhttp_request *req, int code,
  2515. const char *reason)
  2516. {
  2517. evhttp_response_code_(req, code, reason);
  2518. if (req->evcon == NULL)
  2519. return;
  2520. if (evhttp_find_header(req->output_headers, "Content-Length") == NULL &&
  2521. REQ_VERSION_ATLEAST(req, 1, 1) &&
  2522. evhttp_response_needs_body(req)) {
  2523. /*
  2524. * prefer HTTP/1.1 chunked encoding to closing the connection;
  2525. * note RFC 2616 section 4.4 forbids it with Content-Length:
  2526. * and it's not necessary then anyway.
  2527. */
  2528. evhttp_add_header(req->output_headers, "Transfer-Encoding",
  2529. "chunked");
  2530. req->chunked = 1;
  2531. } else {
  2532. req->chunked = 0;
  2533. }
  2534. evhttp_make_header(req->evcon, req);
  2535. evhttp_write_buffer(req->evcon, NULL, NULL);
  2536. }
  2537. void
  2538. evhttp_send_reply_chunk_with_cb(struct evhttp_request *req, struct evbuffer *databuf,
  2539. void (*cb)(struct evhttp_connection *, void *), void *arg)
  2540. {
  2541. struct evhttp_connection *evcon = req->evcon;
  2542. struct evbuffer *output;
  2543. if (evcon == NULL)
  2544. return;
  2545. output = bufferevent_get_output(evcon->bufev);
  2546. if (evbuffer_get_length(databuf) == 0)
  2547. return;
  2548. if (!evhttp_response_needs_body(req))
  2549. return;
  2550. if (req->chunked) {
  2551. evbuffer_add_printf(output, "%x\r\n",
  2552. (unsigned)evbuffer_get_length(databuf));
  2553. }
  2554. evbuffer_add_buffer(output, databuf);
  2555. if (req->chunked) {
  2556. evbuffer_add(output, "\r\n", 2);
  2557. }
  2558. evhttp_write_buffer(evcon, cb, arg);
  2559. }
  2560. void
  2561. evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
  2562. {
  2563. evhttp_send_reply_chunk_with_cb(req, databuf, NULL, NULL);
  2564. }
  2565. void
  2566. evhttp_send_reply_end(struct evhttp_request *req)
  2567. {
  2568. struct evhttp_connection *evcon = req->evcon;
  2569. struct evbuffer *output;
  2570. if (evcon == NULL) {
  2571. evhttp_request_free(req);
  2572. return;
  2573. }
  2574. output = bufferevent_get_output(evcon->bufev);
  2575. /* we expect no more calls form the user on this request */
  2576. req->userdone = 1;
  2577. if (req->chunked) {
  2578. evbuffer_add(output, "0\r\n\r\n", 5);
  2579. evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
  2580. req->chunked = 0;
  2581. } else if (evbuffer_get_length(output) == 0) {
  2582. /* let the connection know that we are done with the request */
  2583. evhttp_send_done(evcon, NULL);
  2584. } else {
  2585. /* make the callback execute after all data has been written */
  2586. evcon->cb = evhttp_send_done;
  2587. evcon->cb_arg = NULL;
  2588. }
  2589. }
  2590. static const char *informational_phrases[] = {
  2591. /* 100 */ "Continue",
  2592. /* 101 */ "Switching Protocols"
  2593. };
  2594. static const char *success_phrases[] = {
  2595. /* 200 */ "OK",
  2596. /* 201 */ "Created",
  2597. /* 202 */ "Accepted",
  2598. /* 203 */ "Non-Authoritative Information",
  2599. /* 204 */ "No Content",
  2600. /* 205 */ "Reset Content",
  2601. /* 206 */ "Partial Content"
  2602. };
  2603. static const char *redirection_phrases[] = {
  2604. /* 300 */ "Multiple Choices",
  2605. /* 301 */ "Moved Permanently",
  2606. /* 302 */ "Found",
  2607. /* 303 */ "See Other",
  2608. /* 304 */ "Not Modified",
  2609. /* 305 */ "Use Proxy",
  2610. /* 307 */ "Temporary Redirect"
  2611. };
  2612. static const char *client_error_phrases[] = {
  2613. /* 400 */ "Bad Request",
  2614. /* 401 */ "Unauthorized",
  2615. /* 402 */ "Payment Required",
  2616. /* 403 */ "Forbidden",
  2617. /* 404 */ "Not Found",
  2618. /* 405 */ "Method Not Allowed",
  2619. /* 406 */ "Not Acceptable",
  2620. /* 407 */ "Proxy Authentication Required",
  2621. /* 408 */ "Request Time-out",
  2622. /* 409 */ "Conflict",
  2623. /* 410 */ "Gone",
  2624. /* 411 */ "Length Required",
  2625. /* 412 */ "Precondition Failed",
  2626. /* 413 */ "Request Entity Too Large",
  2627. /* 414 */ "Request-URI Too Large",
  2628. /* 415 */ "Unsupported Media Type",
  2629. /* 416 */ "Requested range not satisfiable",
  2630. /* 417 */ "Expectation Failed"
  2631. };
  2632. static const char *server_error_phrases[] = {
  2633. /* 500 */ "Internal Server Error",
  2634. /* 501 */ "Not Implemented",
  2635. /* 502 */ "Bad Gateway",
  2636. /* 503 */ "Service Unavailable",
  2637. /* 504 */ "Gateway Time-out",
  2638. /* 505 */ "HTTP Version not supported"
  2639. };
  2640. struct response_class {
  2641. const char *name;
  2642. size_t num_responses;
  2643. const char **responses;
  2644. };
  2645. #ifndef MEMBERSOF
  2646. #define MEMBERSOF(x) (sizeof(x)/sizeof(x[0]))
  2647. #endif
  2648. static const struct response_class response_classes[] = {
  2649. /* 1xx */ { "Informational", MEMBERSOF(informational_phrases), informational_phrases },
  2650. /* 2xx */ { "Success", MEMBERSOF(success_phrases), success_phrases },
  2651. /* 3xx */ { "Redirection", MEMBERSOF(redirection_phrases), redirection_phrases },
  2652. /* 4xx */ { "Client Error", MEMBERSOF(client_error_phrases), client_error_phrases },
  2653. /* 5xx */ { "Server Error", MEMBERSOF(server_error_phrases), server_error_phrases }
  2654. };
  2655. static const char *
  2656. evhttp_response_phrase_internal(int code)
  2657. {
  2658. int klass = code / 100 - 1;
  2659. int subcode = code % 100;
  2660. /* Unknown class - can't do any better here */
  2661. if (klass < 0 || klass >= (int) MEMBERSOF(response_classes))
  2662. return "Unknown Status Class";
  2663. /* Unknown sub-code, return class name at least */
  2664. if (subcode >= (int) response_classes[klass].num_responses)
  2665. return response_classes[klass].name;
  2666. return response_classes[klass].responses[subcode];
  2667. }
  2668. void
  2669. evhttp_response_code_(struct evhttp_request *req, int code, const char *reason)
  2670. {
  2671. req->kind = EVHTTP_RESPONSE;
  2672. req->response_code = code;
  2673. if (req->response_code_line != NULL)
  2674. mm_free(req->response_code_line);
  2675. if (reason == NULL)
  2676. reason = evhttp_response_phrase_internal(code);
  2677. req->response_code_line = mm_strdup(reason);
  2678. if (req->response_code_line == NULL) {
  2679. event_warn("%s: strdup", __func__);
  2680. /* XXX what else can we do? */
  2681. }
  2682. }
  2683. void
  2684. evhttp_send_page_(struct evhttp_request *req, struct evbuffer *databuf)
  2685. {
  2686. if (!req->major || !req->minor) {
  2687. req->major = 1;
  2688. req->minor = 1;
  2689. }
  2690. if (req->kind != EVHTTP_RESPONSE)
  2691. evhttp_response_code_(req, 200, "OK");
  2692. evhttp_clear_headers(req->output_headers);
  2693. evhttp_add_header(req->output_headers, "Content-Type", "text/html");
  2694. evhttp_add_header(req->output_headers, "Connection", "close");
  2695. evhttp_send(req, databuf);
  2696. }
  2697. static const char uri_chars[256] = {
  2698. /* 0 */
  2699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
  2702. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
  2703. /* 64 */
  2704. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2705. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
  2706. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2707. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0,
  2708. /* 128 */
  2709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2713. /* 192 */
  2714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2718. };
  2719. #define CHAR_IS_UNRESERVED(c) \
  2720. (uri_chars[(unsigned char)(c)])
  2721. /*
  2722. * Helper functions to encode/decode a string for inclusion in a URI.
  2723. * The returned string must be freed by the caller.
  2724. */
  2725. char *
  2726. evhttp_uriencode(const char *uri, ev_ssize_t len, int space_as_plus)
  2727. {
  2728. struct evbuffer *buf = evbuffer_new();
  2729. const char *p, *end;
  2730. char *result = NULL;
  2731. if (!buf) {
  2732. goto out;
  2733. }
  2734. if (len >= 0) {
  2735. if (uri + len < uri) {
  2736. goto out;
  2737. }
  2738. end = uri + len;
  2739. } else {
  2740. size_t slen = strlen(uri);
  2741. if (slen >= EV_SSIZE_MAX) {
  2742. /* we don't want to mix signed and unsigned */
  2743. goto out;
  2744. }
  2745. if (uri + slen < uri) {
  2746. goto out;
  2747. }
  2748. end = uri + slen;
  2749. }
  2750. for (p = uri; p < end; p++) {
  2751. if (CHAR_IS_UNRESERVED(*p)) {
  2752. evbuffer_add(buf, p, 1);
  2753. } else if (*p == ' ' && space_as_plus) {
  2754. evbuffer_add(buf, "+", 1);
  2755. } else {
  2756. evbuffer_add_printf(buf, "%%%02X", (unsigned char)(*p));
  2757. }
  2758. }
  2759. evbuffer_add(buf, "", 1); /* NUL-terminator. */
  2760. result = mm_malloc(evbuffer_get_length(buf));
  2761. if (result)
  2762. evbuffer_remove(buf, result, evbuffer_get_length(buf));
  2763. out:
  2764. if (buf)
  2765. evbuffer_free(buf);
  2766. return result;
  2767. }
  2768. char *
  2769. evhttp_encode_uri(const char *str)
  2770. {
  2771. return evhttp_uriencode(str, -1, 0);
  2772. }
  2773. /*
  2774. * @param decode_plus_ctl: if 1, we decode plus into space. If 0, we don't.
  2775. * If -1, when true we transform plus to space only after we've seen
  2776. * a ?. -1 is deprecated.
  2777. * @return the number of bytes written to 'ret'.
  2778. */
  2779. int
  2780. evhttp_decode_uri_internal(
  2781. const char *uri, size_t length, char *ret, int decode_plus_ctl)
  2782. {
  2783. char c;
  2784. int j;
  2785. int decode_plus = (decode_plus_ctl == 1) ? 1: 0;
  2786. unsigned i;
  2787. for (i = j = 0; i < length; i++) {
  2788. c = uri[i];
  2789. if (c == '?') {
  2790. if (decode_plus_ctl < 0)
  2791. decode_plus = 1;
  2792. } else if (c == '+' && decode_plus) {
  2793. c = ' ';
  2794. } else if ((i + 2) < length && c == '%' &&
  2795. EVUTIL_ISXDIGIT_(uri[i+1]) && EVUTIL_ISXDIGIT_(uri[i+2])) {
  2796. char tmp[3];
  2797. tmp[0] = uri[i+1];
  2798. tmp[1] = uri[i+2];
  2799. tmp[2] = '\0';
  2800. c = (char)strtol(tmp, NULL, 16);
  2801. i += 2;
  2802. }
  2803. ret[j++] = c;
  2804. }
  2805. ret[j] = '\0';
  2806. return (j);
  2807. }
  2808. /* deprecated */
  2809. char *
  2810. evhttp_decode_uri(const char *uri)
  2811. {
  2812. char *ret;
  2813. if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
  2814. event_warn("%s: malloc(%lu)", __func__,
  2815. (unsigned long)(strlen(uri) + 1));
  2816. return (NULL);
  2817. }
  2818. evhttp_decode_uri_internal(uri, strlen(uri),
  2819. ret, -1 /*always_decode_plus*/);
  2820. return (ret);
  2821. }
  2822. char *
  2823. evhttp_uridecode(const char *uri, int decode_plus, size_t *size_out)
  2824. {
  2825. char *ret;
  2826. int n;
  2827. if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
  2828. event_warn("%s: malloc(%lu)", __func__,
  2829. (unsigned long)(strlen(uri) + 1));
  2830. return (NULL);
  2831. }
  2832. n = evhttp_decode_uri_internal(uri, strlen(uri),
  2833. ret, !!decode_plus/*always_decode_plus*/);
  2834. if (size_out) {
  2835. EVUTIL_ASSERT(n >= 0);
  2836. *size_out = (size_t)n;
  2837. }
  2838. return (ret);
  2839. }
  2840. /*
  2841. * Helper function to parse out arguments in a query.
  2842. * The arguments are separated by key and value.
  2843. */
  2844. static int
  2845. evhttp_parse_query_impl(const char *str, struct evkeyvalq *headers,
  2846. int is_whole_uri)
  2847. {
  2848. char *line=NULL;
  2849. char *argument;
  2850. char *p;
  2851. const char *query_part;
  2852. int result = -1;
  2853. struct evhttp_uri *uri=NULL;
  2854. TAILQ_INIT(headers);
  2855. if (is_whole_uri) {
  2856. uri = evhttp_uri_parse(str);
  2857. if (!uri)
  2858. goto error;
  2859. query_part = evhttp_uri_get_query(uri);
  2860. } else {
  2861. query_part = str;
  2862. }
  2863. /* No arguments - we are done */
  2864. if (!query_part || !strlen(query_part)) {
  2865. result = 0;
  2866. goto done;
  2867. }
  2868. if ((line = mm_strdup(query_part)) == NULL) {
  2869. event_warn("%s: strdup", __func__);
  2870. goto error;
  2871. }
  2872. p = argument = line;
  2873. while (p != NULL && *p != '\0') {
  2874. char *key, *value, *decoded_value;
  2875. int err;
  2876. argument = strsep(&p, "&");
  2877. value = argument;
  2878. key = strsep(&value, "=");
  2879. if (value == NULL || *key == '\0') {
  2880. goto error;
  2881. }
  2882. if ((decoded_value = mm_malloc(strlen(value) + 1)) == NULL) {
  2883. event_warn("%s: mm_malloc", __func__);
  2884. goto error;
  2885. }
  2886. evhttp_decode_uri_internal(value, strlen(value),
  2887. decoded_value, 1 /*always_decode_plus*/);
  2888. event_debug(("Query Param: %s -> %s\n", key, decoded_value));
  2889. err = evhttp_add_header_internal(headers, key, decoded_value);
  2890. mm_free(decoded_value);
  2891. if (err)
  2892. goto error;
  2893. }
  2894. result = 0;
  2895. goto done;
  2896. error:
  2897. evhttp_clear_headers(headers);
  2898. done:
  2899. if (line)
  2900. mm_free(line);
  2901. if (uri)
  2902. evhttp_uri_free(uri);
  2903. return result;
  2904. }
  2905. int
  2906. evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
  2907. {
  2908. return evhttp_parse_query_impl(uri, headers, 1);
  2909. }
  2910. int
  2911. evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers)
  2912. {
  2913. return evhttp_parse_query_impl(uri, headers, 0);
  2914. }
  2915. static struct evhttp_cb *
  2916. evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req, int chunked)
  2917. {
  2918. struct evhttp_cb *cb;
  2919. size_t offset = 0;
  2920. char *translated;
  2921. const char *path;
  2922. /* Test for different URLs */
  2923. path = evhttp_uri_get_path(req->uri_elems);
  2924. offset = strlen(path);
  2925. if ((translated = mm_malloc(offset + 1)) == NULL)
  2926. return (NULL);
  2927. evhttp_decode_uri_internal(path, offset, translated,
  2928. 0 /* decode_plus */);
  2929. TAILQ_FOREACH(cb, callbacks, next) {
  2930. if (!strcmp(cb->what, translated)) {
  2931. if (chunked < 0) {
  2932. mm_free(translated);
  2933. return (cb);
  2934. } else if (chunked == cb->chunked) {
  2935. mm_free(translated);
  2936. return (cb);
  2937. }
  2938. }
  2939. }
  2940. mm_free(translated);
  2941. return (NULL);
  2942. }
  2943. static int
  2944. prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
  2945. {
  2946. char c;
  2947. while (1) {
  2948. switch (c = *pattern++) {
  2949. case '\0':
  2950. return *name == '\0';
  2951. case '*':
  2952. while (*name != '\0') {
  2953. if (prefix_suffix_match(pattern, name,
  2954. ignorecase))
  2955. return (1);
  2956. ++name;
  2957. }
  2958. return (0);
  2959. default:
  2960. if (c != *name) {
  2961. if (!ignorecase ||
  2962. EVUTIL_TOLOWER_(c) != EVUTIL_TOLOWER_(*name))
  2963. return (0);
  2964. }
  2965. ++name;
  2966. }
  2967. }
  2968. /* NOTREACHED */
  2969. }
  2970. /*
  2971. Search the vhost hierarchy beginning with http for a server alias
  2972. matching hostname. If a match is found, and outhttp is non-null,
  2973. outhttp is set to the matching http object and 1 is returned.
  2974. */
  2975. static int
  2976. evhttp_find_alias(struct evhttp *http, struct evhttp **outhttp,
  2977. const char *hostname)
  2978. {
  2979. struct evhttp_server_alias *alias;
  2980. struct evhttp *vhost;
  2981. TAILQ_FOREACH(alias, &http->aliases, next) {
  2982. /* XXX Do we need to handle IP addresses? */
  2983. if (!evutil_ascii_strcasecmp(alias->alias, hostname)) {
  2984. if (outhttp)
  2985. *outhttp = http;
  2986. return 1;
  2987. }
  2988. }
  2989. /* XXX It might be good to avoid recursion here, but I don't
  2990. see a way to do that w/o a list. */
  2991. TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
  2992. if (evhttp_find_alias(vhost, outhttp, hostname))
  2993. return 1;
  2994. }
  2995. return 0;
  2996. }
  2997. /*
  2998. Attempts to find the best http object to handle a request for a hostname.
  2999. All aliases for the root http object and vhosts are searched for an exact
  3000. match. Then, the vhost hierarchy is traversed again for a matching
  3001. pattern.
  3002. If an alias or vhost is matched, 1 is returned, and outhttp, if non-null,
  3003. is set with the best matching http object. If there are no matches, the
  3004. root http object is stored in outhttp and 0 is returned.
  3005. */
  3006. static int
  3007. evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
  3008. const char *hostname)
  3009. {
  3010. struct evhttp *vhost;
  3011. struct evhttp *oldhttp;
  3012. int match_found = 0;
  3013. if (evhttp_find_alias(http, outhttp, hostname))
  3014. return 1;
  3015. do {
  3016. oldhttp = http;
  3017. TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
  3018. if (prefix_suffix_match(vhost->vhost_pattern,
  3019. hostname, 1 /* ignorecase */)) {
  3020. http = vhost;
  3021. match_found = 1;
  3022. break;
  3023. }
  3024. }
  3025. } while (oldhttp != http);
  3026. if (outhttp)
  3027. *outhttp = http;
  3028. return match_found;
  3029. }
  3030. static void
  3031. evhttp_handle_request(struct evhttp_request *req, void *arg)
  3032. {
  3033. struct evhttp *http = arg;
  3034. struct evhttp_cb *cb = NULL;
  3035. const char *hostname;
  3036. /* we have a new request on which the user needs to take action */
  3037. req->userdone = 0;
  3038. bufferevent_disable(req->evcon->bufev, EV_READ);
  3039. if (req->type == 0 || req->uri == NULL) {
  3040. evhttp_send_error(req, req->response_code, NULL);
  3041. return;
  3042. }
  3043. if ((http->allowed_methods & req->type) == 0) {
  3044. event_debug(("Rejecting disallowed method %x (allowed: %x)\n",
  3045. (unsigned)req->type, (unsigned)http->allowed_methods));
  3046. evhttp_send_error(req, HTTP_NOTIMPLEMENTED, NULL);
  3047. return;
  3048. }
  3049. /* handle potential virtual hosts */
  3050. hostname = evhttp_request_get_host(req);
  3051. if (hostname != NULL) {
  3052. evhttp_find_vhost(http, &http, hostname);
  3053. }
  3054. if ((cb = evhttp_dispatch_callback(&http->callbacks, req, -1)) != NULL) {
  3055. (*cb->cb)(req, cb->cbarg);
  3056. return;
  3057. }
  3058. /* Generic call back */
  3059. if (http->gencb) {
  3060. (*http->gencb)(req, http->gencbarg);
  3061. return;
  3062. } else {
  3063. /* We need to send a 404 here */
  3064. #define ERR_FORMAT "<html><head>" \
  3065. "<title>404 Not Found</title>" \
  3066. "</head><body>" \
  3067. "<h1>Not Found</h1>" \
  3068. "<p>The requested URL %s was not found on this server.</p>"\
  3069. "</body></html>\n"
  3070. char *escaped_html;
  3071. struct evbuffer *buf;
  3072. if ((escaped_html = evhttp_htmlescape(req->uri)) == NULL) {
  3073. evhttp_connection_free(req->evcon);
  3074. return;
  3075. }
  3076. if ((buf = evbuffer_new()) == NULL) {
  3077. mm_free(escaped_html);
  3078. evhttp_connection_free(req->evcon);
  3079. return;
  3080. }
  3081. evhttp_response_code_(req, HTTP_NOTFOUND, "Not Found");
  3082. evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
  3083. mm_free(escaped_html);
  3084. evhttp_send_page_(req, buf);
  3085. evbuffer_free(buf);
  3086. #undef ERR_FORMAT
  3087. }
  3088. }
  3089. /* Listener callback when a connection arrives at a server. */
  3090. static void
  3091. accept_socket_cb(struct evconnlistener *listener, evutil_socket_t nfd, struct sockaddr *peer_sa, int peer_socklen, void *arg)
  3092. {
  3093. struct evhttp *http = arg;
  3094. evhttp_get_request(http, nfd, peer_sa, peer_socklen);
  3095. }
  3096. int
  3097. evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port)
  3098. {
  3099. struct evhttp_bound_socket *bound =
  3100. evhttp_bind_socket_with_handle(http, address, port);
  3101. if (bound == NULL)
  3102. return (-1);
  3103. return (0);
  3104. }
  3105. struct evhttp_bound_socket *
  3106. evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port)
  3107. {
  3108. evutil_socket_t fd;
  3109. struct evhttp_bound_socket *bound;
  3110. int serrno;
  3111. if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
  3112. return (NULL);
  3113. if (listen(fd, 128) == -1) {
  3114. serrno = EVUTIL_SOCKET_ERROR();
  3115. event_sock_warn(fd, "%s: listen", __func__);
  3116. evutil_closesocket(fd);
  3117. EVUTIL_SET_SOCKET_ERROR(serrno);
  3118. return (NULL);
  3119. }
  3120. bound = evhttp_accept_socket_with_handle(http, fd);
  3121. if (bound != NULL) {
  3122. event_debug(("Bound to port %d - Awaiting connections ... ",
  3123. port));
  3124. return (bound);
  3125. }
  3126. return (NULL);
  3127. }
  3128. int
  3129. evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
  3130. {
  3131. struct evhttp_bound_socket *bound =
  3132. evhttp_accept_socket_with_handle(http, fd);
  3133. if (bound == NULL)
  3134. return (-1);
  3135. return (0);
  3136. }
  3137. void
  3138. evhttp_foreach_bound_socket(struct evhttp *http,
  3139. evhttp_bound_socket_foreach_fn *function,
  3140. void *argument)
  3141. {
  3142. struct evhttp_bound_socket *bound;
  3143. TAILQ_FOREACH(bound, &http->sockets, next)
  3144. function(bound, argument);
  3145. }
  3146. struct evhttp_bound_socket *
  3147. evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
  3148. {
  3149. struct evhttp_bound_socket *bound;
  3150. struct evconnlistener *listener;
  3151. const int flags =
  3152. LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_CLOSE_ON_FREE;
  3153. listener = evconnlistener_new(http->base, NULL, NULL,
  3154. flags,
  3155. 0, /* Backlog is '0' because we already said 'listen' */
  3156. fd);
  3157. if (!listener)
  3158. return (NULL);
  3159. bound = evhttp_bind_listener(http, listener);
  3160. if (!bound) {
  3161. evconnlistener_free(listener);
  3162. return (NULL);
  3163. }
  3164. return (bound);
  3165. }
  3166. struct evhttp_bound_socket *
  3167. evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener)
  3168. {
  3169. struct evhttp_bound_socket *bound;
  3170. bound = mm_malloc(sizeof(struct evhttp_bound_socket));
  3171. if (bound == NULL)
  3172. return (NULL);
  3173. bound->listener = listener;
  3174. TAILQ_INSERT_TAIL(&http->sockets, bound, next);
  3175. evconnlistener_set_cb(listener, accept_socket_cb, http);
  3176. return bound;
  3177. }
  3178. evutil_socket_t
  3179. evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound)
  3180. {
  3181. return evconnlistener_get_fd(bound->listener);
  3182. }
  3183. struct evconnlistener *
  3184. evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound)
  3185. {
  3186. return bound->listener;
  3187. }
  3188. void
  3189. evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound)
  3190. {
  3191. TAILQ_REMOVE(&http->sockets, bound, next);
  3192. evconnlistener_free(bound->listener);
  3193. mm_free(bound);
  3194. }
  3195. static struct evhttp*
  3196. evhttp_new_object(void)
  3197. {
  3198. struct evhttp *http = NULL;
  3199. if ((http = mm_calloc(1, sizeof(struct evhttp))) == NULL) {
  3200. event_warn("%s: calloc", __func__);
  3201. return (NULL);
  3202. }
  3203. evutil_timerclear(&http->timeout);
  3204. evhttp_set_max_headers_size(http, EV_SIZE_MAX);
  3205. evhttp_set_max_body_size(http, EV_SIZE_MAX);
  3206. evhttp_set_default_content_type(http, "text/html; charset=ISO-8859-1");
  3207. evhttp_set_allowed_methods(http,
  3208. EVHTTP_REQ_GET |
  3209. EVHTTP_REQ_POST |
  3210. EVHTTP_REQ_HEAD |
  3211. EVHTTP_REQ_PUT |
  3212. EVHTTP_REQ_DELETE);
  3213. TAILQ_INIT(&http->sockets);
  3214. TAILQ_INIT(&http->callbacks);
  3215. TAILQ_INIT(&http->connections);
  3216. TAILQ_INIT(&http->virtualhosts);
  3217. TAILQ_INIT(&http->aliases);
  3218. return (http);
  3219. }
  3220. struct evhttp *
  3221. evhttp_new(struct event_base *base)
  3222. {
  3223. struct evhttp *http = NULL;
  3224. http = evhttp_new_object();
  3225. if (http == NULL)
  3226. return (NULL);
  3227. http->base = base;
  3228. return (http);
  3229. }
  3230. /*
  3231. * Start a web server on the specified address and port.
  3232. */
  3233. struct evhttp *
  3234. evhttp_start(const char *address, ev_uint16_t port)
  3235. {
  3236. struct evhttp *http = NULL;
  3237. http = evhttp_new_object();
  3238. if (http == NULL)
  3239. return (NULL);
  3240. if (evhttp_bind_socket(http, address, port) == -1) {
  3241. mm_free(http);
  3242. return (NULL);
  3243. }
  3244. return (http);
  3245. }
  3246. void
  3247. evhttp_free(struct evhttp* http)
  3248. {
  3249. struct evhttp_cb *http_cb;
  3250. struct evhttp_connection *evcon;
  3251. struct evhttp_bound_socket *bound;
  3252. struct evhttp* vhost;
  3253. struct evhttp_server_alias *alias;
  3254. /* Remove the accepting part */
  3255. while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
  3256. TAILQ_REMOVE(&http->sockets, bound, next);
  3257. evconnlistener_free(bound->listener);
  3258. mm_free(bound);
  3259. }
  3260. while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
  3261. /* evhttp_connection_free removes the connection */
  3262. evhttp_connection_free(evcon);
  3263. }
  3264. while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
  3265. TAILQ_REMOVE(&http->callbacks, http_cb, next);
  3266. mm_free(http_cb->what);
  3267. mm_free(http_cb);
  3268. }
  3269. while ((vhost = TAILQ_FIRST(&http->virtualhosts)) != NULL) {
  3270. TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
  3271. evhttp_free(vhost);
  3272. }
  3273. if (http->vhost_pattern != NULL)
  3274. mm_free(http->vhost_pattern);
  3275. while ((alias = TAILQ_FIRST(&http->aliases)) != NULL) {
  3276. TAILQ_REMOVE(&http->aliases, alias, next);
  3277. mm_free(alias->alias);
  3278. mm_free(alias);
  3279. }
  3280. mm_free(http);
  3281. }
  3282. int
  3283. evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
  3284. struct evhttp* vhost)
  3285. {
  3286. /* a vhost can only be a vhost once and should not have bound sockets */
  3287. if (vhost->vhost_pattern != NULL ||
  3288. TAILQ_FIRST(&vhost->sockets) != NULL)
  3289. return (-1);
  3290. vhost->vhost_pattern = mm_strdup(pattern);
  3291. if (vhost->vhost_pattern == NULL)
  3292. return (-1);
  3293. TAILQ_INSERT_TAIL(&http->virtualhosts, vhost, next_vhost);
  3294. return (0);
  3295. }
  3296. int
  3297. evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost)
  3298. {
  3299. if (vhost->vhost_pattern == NULL)
  3300. return (-1);
  3301. TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
  3302. mm_free(vhost->vhost_pattern);
  3303. vhost->vhost_pattern = NULL;
  3304. return (0);
  3305. }
  3306. int
  3307. evhttp_add_server_alias(struct evhttp *http, const char *alias)
  3308. {
  3309. struct evhttp_server_alias *evalias;
  3310. evalias = mm_calloc(1, sizeof(*evalias));
  3311. if (!evalias)
  3312. return -1;
  3313. evalias->alias = mm_strdup(alias);
  3314. if (!evalias->alias) {
  3315. mm_free(evalias);
  3316. return -1;
  3317. }
  3318. TAILQ_INSERT_TAIL(&http->aliases, evalias, next);
  3319. return 0;
  3320. }
  3321. int
  3322. evhttp_remove_server_alias(struct evhttp *http, const char *alias)
  3323. {
  3324. struct evhttp_server_alias *evalias;
  3325. TAILQ_FOREACH(evalias, &http->aliases, next) {
  3326. if (evutil_ascii_strcasecmp(evalias->alias, alias) == 0) {
  3327. TAILQ_REMOVE(&http->aliases, evalias, next);
  3328. mm_free(evalias->alias);
  3329. mm_free(evalias);
  3330. return 0;
  3331. }
  3332. }
  3333. return -1;
  3334. }
  3335. void
  3336. evhttp_set_timeout(struct evhttp* http, int timeout_in_secs)
  3337. {
  3338. if (timeout_in_secs == -1) {
  3339. evhttp_set_timeout_tv(http, NULL);
  3340. } else {
  3341. struct timeval tv;
  3342. tv.tv_sec = timeout_in_secs;
  3343. tv.tv_usec = 0;
  3344. evhttp_set_timeout_tv(http, &tv);
  3345. }
  3346. }
  3347. void
  3348. evhttp_set_timeout_tv(struct evhttp* http, const struct timeval* tv)
  3349. {
  3350. if (tv) {
  3351. http->timeout = *tv;
  3352. } else {
  3353. evutil_timerclear(&http->timeout);
  3354. }
  3355. }
  3356. int evhttp_set_flags(struct evhttp *http, int flags)
  3357. {
  3358. int avail_flags = 0;
  3359. avail_flags |= EVHTTP_SERVER_LINGERING_CLOSE;
  3360. if (flags & ~avail_flags)
  3361. return 1;
  3362. http->flags &= ~avail_flags;
  3363. http->flags |= flags;
  3364. return 0;
  3365. }
  3366. void
  3367. evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size)
  3368. {
  3369. if (max_headers_size < 0)
  3370. http->default_max_headers_size = EV_SIZE_MAX;
  3371. else
  3372. http->default_max_headers_size = max_headers_size;
  3373. }
  3374. void
  3375. evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size)
  3376. {
  3377. if (max_body_size < 0)
  3378. http->default_max_body_size = EV_UINT64_MAX;
  3379. else
  3380. http->default_max_body_size = max_body_size;
  3381. }
  3382. void
  3383. evhttp_set_default_content_type(struct evhttp *http,
  3384. const char *content_type) {
  3385. http->default_content_type = content_type;
  3386. }
  3387. void
  3388. evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods)
  3389. {
  3390. http->allowed_methods = methods;
  3391. }
  3392. int
  3393. evhttp_set_cb_internal(struct evhttp *http, const char *uri,
  3394. void (*cb)(struct evhttp_request *, void *), void *cbarg, int chunked)
  3395. {
  3396. struct evhttp_cb *http_cb;
  3397. TAILQ_FOREACH(http_cb, &http->callbacks, next) {
  3398. if (strcmp(http_cb->what, uri) == 0)
  3399. return (-1);
  3400. }
  3401. if ((http_cb = mm_calloc(1, sizeof(struct evhttp_cb))) == NULL) {
  3402. event_warn("%s: calloc", __func__);
  3403. return (-2);
  3404. }
  3405. http_cb->what = mm_strdup(uri);
  3406. if (http_cb->what == NULL) {
  3407. event_warn("%s: strdup", __func__);
  3408. mm_free(http_cb);
  3409. return (-3);
  3410. }
  3411. http_cb->cb = cb;
  3412. http_cb->cbarg = cbarg;
  3413. http_cb->chunked = chunked;
  3414. TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
  3415. return (0);
  3416. }
  3417. int
  3418. evhttp_set_cb(struct evhttp *http, const char *uri,
  3419. void (*cb)(struct evhttp_request *, void *), void *cbarg)
  3420. {
  3421. return evhttp_set_cb_internal(http, uri, cb, cbarg, 0);
  3422. }
  3423. int evhttp_set_chunk_cb(struct evhttp *http, const char *path,
  3424. void (*chunk_cb)(struct evhttp_request *, void *), void *cb_arg)
  3425. {
  3426. return evhttp_set_cb_internal(http, path, chunk_cb, cb_arg, 1);
  3427. }
  3428. int
  3429. evhttp_del_cb(struct evhttp *http, const char *uri)
  3430. {
  3431. struct evhttp_cb *http_cb;
  3432. TAILQ_FOREACH(http_cb, &http->callbacks, next) {
  3433. if (strcmp(http_cb->what, uri) == 0)
  3434. break;
  3435. }
  3436. if (http_cb == NULL)
  3437. return (-1);
  3438. TAILQ_REMOVE(&http->callbacks, http_cb, next);
  3439. mm_free(http_cb->what);
  3440. mm_free(http_cb);
  3441. return (0);
  3442. }
  3443. void
  3444. evhttp_set_gencb(struct evhttp *http,
  3445. void (*cb)(struct evhttp_request *, void *), void *cbarg)
  3446. {
  3447. http->gencb = cb;
  3448. http->gencbarg = cbarg;
  3449. }
  3450. void
  3451. evhttp_set_bevcb(struct evhttp *http,
  3452. struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
  3453. {
  3454. http->bevcb = cb;
  3455. http->bevcbarg = cbarg;
  3456. }
  3457. /*
  3458. * Request related functions
  3459. */
  3460. struct evhttp_request *
  3461. evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
  3462. {
  3463. struct evhttp_request *req = NULL;
  3464. /* Allocate request structure */
  3465. if ((req = mm_calloc(1, sizeof(struct evhttp_request))) == NULL) {
  3466. event_warn("%s: calloc", __func__);
  3467. goto error;
  3468. }
  3469. req->headers_size = 0;
  3470. req->body_size = 0;
  3471. req->kind = EVHTTP_RESPONSE;
  3472. req->input_headers = mm_calloc(1, sizeof(struct evkeyvalq));
  3473. if (req->input_headers == NULL) {
  3474. event_warn("%s: calloc", __func__);
  3475. goto error;
  3476. }
  3477. TAILQ_INIT(req->input_headers);
  3478. req->output_headers = mm_calloc(1, sizeof(struct evkeyvalq));
  3479. if (req->output_headers == NULL) {
  3480. event_warn("%s: calloc", __func__);
  3481. goto error;
  3482. }
  3483. TAILQ_INIT(req->output_headers);
  3484. if ((req->input_buffer = evbuffer_new()) == NULL) {
  3485. event_warn("%s: evbuffer_new", __func__);
  3486. goto error;
  3487. }
  3488. if ((req->output_buffer = evbuffer_new()) == NULL) {
  3489. event_warn("%s: evbuffer_new", __func__);
  3490. goto error;
  3491. }
  3492. req->cb = cb;
  3493. req->cb_arg = arg;
  3494. return (req);
  3495. error:
  3496. if (req != NULL)
  3497. evhttp_request_free(req);
  3498. return (NULL);
  3499. }
  3500. void
  3501. evhttp_request_free(struct evhttp_request *req)
  3502. {
  3503. if ((req->flags & EVHTTP_REQ_DEFER_FREE) != 0) {
  3504. req->flags |= EVHTTP_REQ_NEEDS_FREE;
  3505. return;
  3506. }
  3507. if (req->remote_host != NULL)
  3508. mm_free(req->remote_host);
  3509. if (req->uri != NULL)
  3510. mm_free(req->uri);
  3511. if (req->uri_elems != NULL)
  3512. evhttp_uri_free(req->uri_elems);
  3513. if (req->response_code_line != NULL)
  3514. mm_free(req->response_code_line);
  3515. if (req->host_cache != NULL)
  3516. mm_free(req->host_cache);
  3517. evhttp_clear_headers(req->input_headers);
  3518. mm_free(req->input_headers);
  3519. evhttp_clear_headers(req->output_headers);
  3520. mm_free(req->output_headers);
  3521. if (req->input_buffer != NULL)
  3522. evbuffer_free(req->input_buffer);
  3523. if (req->output_buffer != NULL)
  3524. evbuffer_free(req->output_buffer);
  3525. mm_free(req);
  3526. }
  3527. void
  3528. evhttp_request_own(struct evhttp_request *req)
  3529. {
  3530. req->flags |= EVHTTP_USER_OWNED;
  3531. }
  3532. int
  3533. evhttp_request_is_owned(struct evhttp_request *req)
  3534. {
  3535. return (req->flags & EVHTTP_USER_OWNED) != 0;
  3536. }
  3537. struct evhttp_connection *
  3538. evhttp_request_get_connection(struct evhttp_request *req)
  3539. {
  3540. return req->evcon;
  3541. }
  3542. struct event_base *
  3543. evhttp_connection_get_base(struct evhttp_connection *conn)
  3544. {
  3545. return conn->base;
  3546. }
  3547. void
  3548. evhttp_request_set_chunked_cb(struct evhttp_request *req,
  3549. void (*cb)(struct evhttp_request *, void *), void *arg)
  3550. {
  3551. req->chunk_cb = cb;
  3552. req->chunk_cb_arg = arg;
  3553. }
  3554. void
  3555. evhttp_request_set_header_cb(struct evhttp_request *req,
  3556. int (*cb)(struct evhttp_request *, void *))
  3557. {
  3558. req->header_cb = cb;
  3559. }
  3560. void
  3561. evhttp_request_set_error_cb(struct evhttp_request *req,
  3562. void (*cb)(enum evhttp_request_error, void *))
  3563. {
  3564. req->error_cb = cb;
  3565. }
  3566. void
  3567. evhttp_request_set_on_complete_cb(struct evhttp_request *req,
  3568. void (*cb)(struct evhttp_request *, void *), void *cb_arg)
  3569. {
  3570. req->on_complete_cb = cb;
  3571. req->on_complete_cb_arg = cb_arg;
  3572. }
  3573. /*
  3574. * Allows for inspection of the request URI
  3575. */
  3576. const char *
  3577. evhttp_request_get_uri(const struct evhttp_request *req) {
  3578. if (req->uri == NULL)
  3579. event_debug(("%s: request %p has no uri\n", __func__, req));
  3580. return (req->uri);
  3581. }
  3582. const struct evhttp_uri *
  3583. evhttp_request_get_evhttp_uri(const struct evhttp_request *req) {
  3584. if (req->uri_elems == NULL)
  3585. event_debug(("%s: request %p has no uri elems\n",
  3586. __func__, req));
  3587. return (req->uri_elems);
  3588. }
  3589. const char *
  3590. evhttp_request_get_host(struct evhttp_request *req)
  3591. {
  3592. const char *host = NULL;
  3593. if (req->host_cache)
  3594. return req->host_cache;
  3595. if (req->uri_elems)
  3596. host = evhttp_uri_get_host(req->uri_elems);
  3597. if (!host && req->input_headers) {
  3598. const char *p;
  3599. size_t len;
  3600. host = evhttp_find_header(req->input_headers, "Host");
  3601. /* The Host: header may include a port. Remove it here
  3602. to be consistent with uri_elems case above. */
  3603. if (host) {
  3604. p = host + strlen(host) - 1;
  3605. while (p > host && EVUTIL_ISDIGIT_(*p))
  3606. --p;
  3607. if (p > host && *p == ':') {
  3608. len = p - host;
  3609. req->host_cache = mm_malloc(len + 1);
  3610. if (!req->host_cache) {
  3611. event_warn("%s: malloc", __func__);
  3612. return NULL;
  3613. }
  3614. memcpy(req->host_cache, host, len);
  3615. req->host_cache[len] = '\0';
  3616. host = req->host_cache;
  3617. }
  3618. }
  3619. }
  3620. return host;
  3621. }
  3622. enum evhttp_cmd_type
  3623. evhttp_request_get_command(const struct evhttp_request *req) {
  3624. return (req->type);
  3625. }
  3626. int
  3627. evhttp_request_get_response_code(const struct evhttp_request *req)
  3628. {
  3629. return req->response_code;
  3630. }
  3631. const char *
  3632. evhttp_request_get_response_code_line(const struct evhttp_request *req)
  3633. {
  3634. return req->response_code_line;
  3635. }
  3636. /** Returns the input headers */
  3637. struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req)
  3638. {
  3639. return (req->input_headers);
  3640. }
  3641. /** Returns the output headers */
  3642. struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req)
  3643. {
  3644. return (req->output_headers);
  3645. }
  3646. /** Returns the input buffer */
  3647. struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req)
  3648. {
  3649. return (req->input_buffer);
  3650. }
  3651. /** Returns the output buffer */
  3652. struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req)
  3653. {
  3654. return (req->output_buffer);
  3655. }
  3656. /*
  3657. * Takes a file descriptor to read a request from.
  3658. * The callback is executed once the whole request has been read.
  3659. */
  3660. static struct evhttp_connection*
  3661. evhttp_get_request_connection(
  3662. struct evhttp* http,
  3663. evutil_socket_t fd, struct sockaddr *sa, ev_socklen_t salen)
  3664. {
  3665. struct evhttp_connection *evcon;
  3666. char *hostname = NULL, *portname = NULL;
  3667. struct bufferevent* bev = NULL;
  3668. #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
  3669. if (sa->sa_family == AF_UNIX) {
  3670. struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
  3671. sa_un->sun_path[0] = '\0';
  3672. }
  3673. #endif
  3674. name_from_addr(sa, salen, &hostname, &portname);
  3675. if (hostname == NULL || portname == NULL) {
  3676. if (hostname) mm_free(hostname);
  3677. if (portname) mm_free(portname);
  3678. return (NULL);
  3679. }
  3680. event_debug(("%s: new request from %s:%s on "EV_SOCK_FMT"\n",
  3681. __func__, hostname, portname, EV_SOCK_ARG(fd)));
  3682. /* we need a connection object to put the http request on */
  3683. if (http->bevcb != NULL) {
  3684. bev = (*http->bevcb)(http->base, http->bevcbarg);
  3685. }
  3686. evcon = evhttp_connection_base_bufferevent_new(
  3687. http->base, NULL, bev, hostname, atoi(portname));
  3688. mm_free(hostname);
  3689. mm_free(portname);
  3690. if (evcon == NULL)
  3691. return (NULL);
  3692. evcon->max_headers_size = http->default_max_headers_size;
  3693. evcon->max_body_size = http->default_max_body_size;
  3694. if (http->flags & EVHTTP_SERVER_LINGERING_CLOSE)
  3695. evcon->flags |= EVHTTP_CON_LINGERING_CLOSE;
  3696. evcon->flags |= EVHTTP_CON_INCOMING;
  3697. evcon->state = EVCON_READING_FIRSTLINE;
  3698. evcon->fd = fd;
  3699. if (bufferevent_setfd(evcon->bufev, fd))
  3700. goto err;
  3701. if (bufferevent_enable(evcon->bufev, EV_READ))
  3702. goto err;
  3703. if (bufferevent_disable(evcon->bufev, EV_WRITE))
  3704. goto err;
  3705. bufferevent_socket_set_conn_address_(evcon->bufev, sa, salen);
  3706. return (evcon);
  3707. err:
  3708. evhttp_connection_free(evcon);
  3709. return (NULL);
  3710. }
  3711. static int
  3712. evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
  3713. {
  3714. struct evhttp *http = evcon->http_server;
  3715. struct evhttp_request *req;
  3716. if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
  3717. return (-1);
  3718. if ((req->remote_host = mm_strdup(evcon->address)) == NULL) {
  3719. event_warn("%s: strdup", __func__);
  3720. evhttp_request_free(req);
  3721. return (-1);
  3722. }
  3723. req->remote_port = evcon->port;
  3724. req->evcon = evcon; /* the request ends up owning the connection */
  3725. req->flags |= EVHTTP_REQ_OWN_CONNECTION;
  3726. /* We did not present the request to the user user yet, so treat it as
  3727. * if the user was done with the request. This allows us to free the
  3728. * request on a persistent connection if the client drops it without
  3729. * sending a request.
  3730. */
  3731. req->userdone = 1;
  3732. TAILQ_INSERT_TAIL(&evcon->requests, req, next);
  3733. req->kind = EVHTTP_REQUEST;
  3734. evhttp_start_read_(evcon);
  3735. return (0);
  3736. }
  3737. static void
  3738. evhttp_get_request(struct evhttp *http, evutil_socket_t fd,
  3739. struct sockaddr *sa, ev_socklen_t salen)
  3740. {
  3741. struct evhttp_connection *evcon;
  3742. evcon = evhttp_get_request_connection(http, fd, sa, salen);
  3743. if (evcon == NULL) {
  3744. event_sock_warn(fd, "%s: cannot get connection on "EV_SOCK_FMT,
  3745. __func__, EV_SOCK_ARG(fd));
  3746. evutil_closesocket(fd);
  3747. return;
  3748. }
  3749. /* the timeout can be used by the server to close idle connections */
  3750. if (evutil_timerisset(&http->timeout))
  3751. evhttp_connection_set_timeout_tv(evcon, &http->timeout);
  3752. /*
  3753. * if we want to accept more than one request on a connection,
  3754. * we need to know which http server it belongs to.
  3755. */
  3756. evcon->http_server = http;
  3757. TAILQ_INSERT_TAIL(&http->connections, evcon, next);
  3758. if (evhttp_associate_new_request_with_connection(evcon) == -1)
  3759. evhttp_connection_free(evcon);
  3760. }
  3761. /*
  3762. * Network helper functions that we do not want to export to the rest of
  3763. * the world.
  3764. */
  3765. static void
  3766. name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
  3767. char **phost, char **pport)
  3768. {
  3769. char ntop[NI_MAXHOST];
  3770. char strport[NI_MAXSERV];
  3771. int ni_result;
  3772. #ifdef EVENT__HAVE_GETNAMEINFO
  3773. ni_result = getnameinfo(sa, salen,
  3774. ntop, sizeof(ntop), strport, sizeof(strport),
  3775. NI_NUMERICHOST|NI_NUMERICSERV);
  3776. if (ni_result != 0) {
  3777. #ifdef EAI_SYSTEM
  3778. /* Windows doesn't have an EAI_SYSTEM. */
  3779. if (ni_result == EAI_SYSTEM)
  3780. event_err(1, "getnameinfo failed");
  3781. else
  3782. #endif
  3783. event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
  3784. return;
  3785. }
  3786. #else
  3787. ni_result = fake_getnameinfo(sa, salen,
  3788. ntop, sizeof(ntop), strport, sizeof(strport),
  3789. NI_NUMERICHOST|NI_NUMERICSERV);
  3790. if (ni_result != 0)
  3791. return;
  3792. #endif
  3793. *phost = mm_strdup(ntop);
  3794. *pport = mm_strdup(strport);
  3795. }
  3796. /* Create a non-blocking socket and bind it */
  3797. static evutil_socket_t
  3798. create_bind_socket_nonblock(struct evutil_addrinfo *ai, int reuse)
  3799. {
  3800. evutil_socket_t fd;
  3801. int on = 1, r;
  3802. int serrno;
  3803. /* Create listen socket */
  3804. fd = evutil_socket_(ai ? ai->ai_family : AF_INET,
  3805. SOCK_STREAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
  3806. if (fd == -1) {
  3807. event_sock_warn(-1, "socket");
  3808. return (-1);
  3809. }
  3810. #if defined IPV6_V6ONLY
  3811. int v6opt = 1;
  3812. if (ai->ai_family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &v6opt, sizeof(v6opt)) < 0)
  3813. goto out;
  3814. #endif
  3815. if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on))<0)
  3816. goto out;
  3817. if (reuse) {
  3818. if (evutil_make_listen_socket_reuseable(fd) < 0)
  3819. goto out;
  3820. }
  3821. if (ai != NULL) {
  3822. r = bind(fd, ai->ai_addr, (ev_socklen_t)ai->ai_addrlen);
  3823. if (r == -1)
  3824. goto out;
  3825. }
  3826. return (fd);
  3827. out:
  3828. serrno = EVUTIL_SOCKET_ERROR();
  3829. evutil_closesocket(fd);
  3830. EVUTIL_SET_SOCKET_ERROR(serrno);
  3831. return (-1);
  3832. }
  3833. static struct evutil_addrinfo *
  3834. make_addrinfo(const char *address, ev_uint16_t port)
  3835. {
  3836. struct evutil_addrinfo *ai = NULL;
  3837. struct evutil_addrinfo hints;
  3838. char strport[NI_MAXSERV];
  3839. int ai_result;
  3840. static const char* names[] = {
  3841. "127.0.0.1",
  3842. "::1",
  3843. "0.0.0.0",
  3844. "::",
  3845. "localhost",
  3846. "localhost.localdomain",
  3847. "localhost6",
  3848. "localhost6.localdomain6",
  3849. NULL
  3850. };
  3851. const char **name_ptr = names;
  3852. int name_exists = 0;
  3853. memset(&hints, 0, sizeof(hints));
  3854. hints.ai_family = AF_UNSPEC;
  3855. hints.ai_socktype = SOCK_STREAM;
  3856. /* turn NULL hostname into INADDR_ANY, and skip looking up any address
  3857. * types we don't have an interface to connect to. */
  3858. hints.ai_flags = EVUTIL_AI_PASSIVE;
  3859. while (*name_ptr) {
  3860. const char* tmp = *name_ptr++;
  3861. if (evutil_ascii_strcasecmp(tmp, address) == 0) {
  3862. name_exists = 1;
  3863. break;
  3864. }
  3865. }
  3866. if (!name_exists)
  3867. hints.ai_flags |= EVUTIL_AI_ADDRCONFIG;
  3868. evutil_snprintf(strport, sizeof(strport), "%d", port);
  3869. if ((ai_result = evutil_getaddrinfo(address, strport, &hints, &ai))
  3870. != 0) {
  3871. if (ai_result == EVUTIL_EAI_SYSTEM)
  3872. event_warn("getaddrinfo");
  3873. else
  3874. event_warnx("getaddrinfo: %s",
  3875. evutil_gai_strerror(ai_result));
  3876. return (NULL);
  3877. }
  3878. return (ai);
  3879. }
  3880. static evutil_socket_t
  3881. bind_socket(const char *address, ev_uint16_t port, int reuse)
  3882. {
  3883. evutil_socket_t fd;
  3884. struct evutil_addrinfo *aitop = NULL;
  3885. /* just create an unbound socket */
  3886. if (address == NULL && port == 0)
  3887. return create_bind_socket_nonblock(NULL, 0);
  3888. aitop = make_addrinfo(address, port);
  3889. if (aitop == NULL)
  3890. return (-1);
  3891. fd = create_bind_socket_nonblock(aitop, reuse);
  3892. evutil_freeaddrinfo(aitop);
  3893. return (fd);
  3894. }
  3895. struct evhttp_uri {
  3896. unsigned flags;
  3897. char *scheme; /* scheme; e.g http, ftp etc */
  3898. char *userinfo; /* userinfo (typically username:pass), or NULL */
  3899. char *host; /* hostname, IP address, or NULL */
  3900. int port; /* port, or zero */
  3901. char *path; /* path, or "". */
  3902. char *query; /* query, or NULL */
  3903. char *fragment; /* fragment or NULL */
  3904. };
  3905. struct evhttp_uri *
  3906. evhttp_uri_new(void)
  3907. {
  3908. struct evhttp_uri *uri = mm_calloc(sizeof(struct evhttp_uri), 1);
  3909. if (uri)
  3910. uri->port = -1;
  3911. return uri;
  3912. }
  3913. void
  3914. evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags)
  3915. {
  3916. uri->flags = flags;
  3917. }
  3918. /* Return true if the string starting at s and ending immediately before eos
  3919. * is a valid URI scheme according to RFC3986
  3920. */
  3921. static int
  3922. scheme_ok(const char *s, const char *eos)
  3923. {
  3924. /* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
  3925. EVUTIL_ASSERT(eos >= s);
  3926. if (s == eos)
  3927. return 0;
  3928. if (!EVUTIL_ISALPHA_(*s))
  3929. return 0;
  3930. while (++s < eos) {
  3931. if (! EVUTIL_ISALNUM_(*s) &&
  3932. *s != '+' && *s != '-' && *s != '.')
  3933. return 0;
  3934. }
  3935. return 1;
  3936. }
  3937. #define SUBDELIMS "!$&'()*+,;="
  3938. /* Return true iff [s..eos) is a valid userinfo */
  3939. static int
  3940. userinfo_ok(const char *s, const char *eos)
  3941. {
  3942. while (s < eos) {
  3943. if (CHAR_IS_UNRESERVED(*s) ||
  3944. strchr(SUBDELIMS, *s) ||
  3945. *s == ':')
  3946. ++s;
  3947. else if (*s == '%' && s+2 < eos &&
  3948. EVUTIL_ISXDIGIT_(s[1]) &&
  3949. EVUTIL_ISXDIGIT_(s[2]))
  3950. s += 3;
  3951. else
  3952. return 0;
  3953. }
  3954. return 1;
  3955. }
  3956. static int
  3957. regname_ok(const char *s, const char *eos)
  3958. {
  3959. while (s && s<eos) {
  3960. if (CHAR_IS_UNRESERVED(*s) ||
  3961. strchr(SUBDELIMS, *s))
  3962. ++s;
  3963. else if (*s == '%' &&
  3964. EVUTIL_ISXDIGIT_(s[1]) &&
  3965. EVUTIL_ISXDIGIT_(s[2]))
  3966. s += 3;
  3967. else
  3968. return 0;
  3969. }
  3970. return 1;
  3971. }
  3972. static int
  3973. parse_port(const char *s, const char *eos)
  3974. {
  3975. int portnum = 0;
  3976. while (s < eos) {
  3977. if (! EVUTIL_ISDIGIT_(*s))
  3978. return -1;
  3979. portnum = (portnum * 10) + (*s - '0');
  3980. if (portnum < 0)
  3981. return -1;
  3982. if (portnum > 65535)
  3983. return -1;
  3984. ++s;
  3985. }
  3986. return portnum;
  3987. }
  3988. /* returns 0 for bad, 1 for ipv6, 2 for IPvFuture */
  3989. static int
  3990. bracket_addr_ok(const char *s, const char *eos)
  3991. {
  3992. if (s + 3 > eos || *s != '[' || *(eos-1) != ']')
  3993. return 0;
  3994. if (s[1] == 'v') {
  3995. /* IPvFuture, or junk.
  3996. "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
  3997. */
  3998. s += 2; /* skip [v */
  3999. --eos;
  4000. if (!EVUTIL_ISXDIGIT_(*s)) /*require at least one*/
  4001. return 0;
  4002. while (s < eos && *s != '.') {
  4003. if (EVUTIL_ISXDIGIT_(*s))
  4004. ++s;
  4005. else
  4006. return 0;
  4007. }
  4008. if (*s != '.')
  4009. return 0;
  4010. ++s;
  4011. while (s < eos) {
  4012. if (CHAR_IS_UNRESERVED(*s) ||
  4013. strchr(SUBDELIMS, *s) ||
  4014. *s == ':')
  4015. ++s;
  4016. else
  4017. return 0;
  4018. }
  4019. return 2;
  4020. } else {
  4021. /* IPv6, or junk */
  4022. char buf[64];
  4023. ev_ssize_t n_chars = eos-s-2;
  4024. struct in6_addr in6;
  4025. if (n_chars >= 64) /* way too long */
  4026. return 0;
  4027. memcpy(buf, s+1, n_chars);
  4028. buf[n_chars]='\0';
  4029. return (evutil_inet_pton(AF_INET6,buf,&in6)==1) ? 1 : 0;
  4030. }
  4031. }
  4032. static int
  4033. parse_authority(struct evhttp_uri *uri, char *s, char *eos)
  4034. {
  4035. char *cp, *port;
  4036. EVUTIL_ASSERT(eos);
  4037. if (eos == s) {
  4038. uri->host = mm_strdup("");
  4039. if (uri->host == NULL) {
  4040. event_warn("%s: strdup", __func__);
  4041. return -1;
  4042. }
  4043. return 0;
  4044. }
  4045. /* Optionally, we start with "userinfo@" */
  4046. cp = strchr(s, '@');
  4047. if (cp && cp < eos) {
  4048. if (! userinfo_ok(s,cp))
  4049. return -1;
  4050. *cp++ = '\0';
  4051. uri->userinfo = mm_strdup(s);
  4052. if (uri->userinfo == NULL) {
  4053. event_warn("%s: strdup", __func__);
  4054. return -1;
  4055. }
  4056. } else {
  4057. cp = s;
  4058. }
  4059. /* Optionally, we end with ":port" */
  4060. for (port=eos-1; port >= cp && EVUTIL_ISDIGIT_(*port); --port)
  4061. ;
  4062. if (port >= cp && *port == ':') {
  4063. if (port+1 == eos) /* Leave port unspecified; the RFC allows a
  4064. * nil port */
  4065. uri->port = -1;
  4066. else if ((uri->port = parse_port(port+1, eos))<0)
  4067. return -1;
  4068. eos = port;
  4069. }
  4070. /* Now, cp..eos holds the "host" port, which can be an IPv4Address,
  4071. * an IP-Literal, or a reg-name */
  4072. EVUTIL_ASSERT(eos >= cp);
  4073. if (*cp == '[' && eos >= cp+2 && *(eos-1) == ']') {
  4074. /* IPv6address, IP-Literal, or junk. */
  4075. if (! bracket_addr_ok(cp, eos))
  4076. return -1;
  4077. } else {
  4078. /* Make sure the host part is ok. */
  4079. if (! regname_ok(cp,eos)) /* Match IPv4Address or reg-name */
  4080. return -1;
  4081. }
  4082. uri->host = mm_malloc(eos-cp+1);
  4083. if (uri->host == NULL) {
  4084. event_warn("%s: malloc", __func__);
  4085. return -1;
  4086. }
  4087. memcpy(uri->host, cp, eos-cp);
  4088. uri->host[eos-cp] = '\0';
  4089. return 0;
  4090. }
  4091. static char *
  4092. end_of_authority(char *cp)
  4093. {
  4094. while (*cp) {
  4095. if (*cp == '?' || *cp == '#' || *cp == '/')
  4096. return cp;
  4097. ++cp;
  4098. }
  4099. return cp;
  4100. }
  4101. enum uri_part {
  4102. PART_PATH,
  4103. PART_QUERY,
  4104. PART_FRAGMENT
  4105. };
  4106. /* Return the character after the longest prefix of 'cp' that matches...
  4107. * *pchar / "/" if allow_qchars is false, or
  4108. * *(pchar / "/" / "?") if allow_qchars is true.
  4109. */
  4110. static char *
  4111. end_of_path(char *cp, enum uri_part part, unsigned flags)
  4112. {
  4113. if (flags & EVHTTP_URI_NONCONFORMANT) {
  4114. /* If NONCONFORMANT:
  4115. * Path is everything up to a # or ? or nul.
  4116. * Query is everything up a # or nul
  4117. * Fragment is everything up to a nul.
  4118. */
  4119. switch (part) {
  4120. case PART_PATH:
  4121. while (*cp && *cp != '#' && *cp != '?')
  4122. ++cp;
  4123. break;
  4124. case PART_QUERY:
  4125. while (*cp && *cp != '#')
  4126. ++cp;
  4127. break;
  4128. case PART_FRAGMENT:
  4129. cp += strlen(cp);
  4130. break;
  4131. };
  4132. return cp;
  4133. }
  4134. while (*cp) {
  4135. if (CHAR_IS_UNRESERVED(*cp) ||
  4136. strchr(SUBDELIMS, *cp) ||
  4137. *cp == ':' || *cp == '@' || *cp == '/')
  4138. ++cp;
  4139. else if (*cp == '%' && EVUTIL_ISXDIGIT_(cp[1]) &&
  4140. EVUTIL_ISXDIGIT_(cp[2]))
  4141. cp += 3;
  4142. else if (*cp == '?' && part != PART_PATH)
  4143. ++cp;
  4144. else
  4145. return cp;
  4146. }
  4147. return cp;
  4148. }
  4149. static int
  4150. path_matches_noscheme(const char *cp)
  4151. {
  4152. while (*cp) {
  4153. if (*cp == ':')
  4154. return 0;
  4155. else if (*cp == '/')
  4156. return 1;
  4157. ++cp;
  4158. }
  4159. return 1;
  4160. }
  4161. struct evhttp_uri *
  4162. evhttp_uri_parse(const char *source_uri)
  4163. {
  4164. return evhttp_uri_parse_with_flags(source_uri, 0);
  4165. }
  4166. struct evhttp_uri *
  4167. evhttp_uri_parse_with_flags(const char *source_uri, unsigned flags)
  4168. {
  4169. char *readbuf = NULL, *readp = NULL, *token = NULL, *query = NULL;
  4170. char *path = NULL, *fragment = NULL;
  4171. int got_authority = 0;
  4172. struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
  4173. if (uri == NULL) {
  4174. event_warn("%s: calloc", __func__);
  4175. goto err;
  4176. }
  4177. uri->port = -1;
  4178. uri->flags = flags;
  4179. readbuf = mm_strdup(source_uri);
  4180. if (readbuf == NULL) {
  4181. event_warn("%s: strdup", __func__);
  4182. goto err;
  4183. }
  4184. readp = readbuf;
  4185. token = NULL;
  4186. /* We try to follow RFC3986 here as much as we can, and match
  4187. the productions
  4188. URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
  4189. relative-ref = relative-part [ "?" query ] [ "#" fragment ]
  4190. */
  4191. /* 1. scheme: */
  4192. token = strchr(readp, ':');
  4193. if (token && scheme_ok(readp,token)) {
  4194. *token = '\0';
  4195. uri->scheme = mm_strdup(readp);
  4196. if (uri->scheme == NULL) {
  4197. event_warn("%s: strdup", __func__);
  4198. goto err;
  4199. }
  4200. readp = token+1; /* eat : */
  4201. }
  4202. /* 2. Optionally, "//" then an 'authority' part. */
  4203. if (readp[0]=='/' && readp[1] == '/') {
  4204. char *authority;
  4205. readp += 2;
  4206. authority = readp;
  4207. path = end_of_authority(readp);
  4208. if (parse_authority(uri, authority, path) < 0)
  4209. goto err;
  4210. readp = path;
  4211. got_authority = 1;
  4212. }
  4213. /* 3. Query: path-abempty, path-absolute, path-rootless, or path-empty
  4214. */
  4215. path = readp;
  4216. readp = end_of_path(path, PART_PATH, flags);
  4217. /* Query */
  4218. if (*readp == '?') {
  4219. *readp = '\0';
  4220. ++readp;
  4221. query = readp;
  4222. readp = end_of_path(readp, PART_QUERY, flags);
  4223. }
  4224. /* fragment */
  4225. if (*readp == '#') {
  4226. *readp = '\0';
  4227. ++readp;
  4228. fragment = readp;
  4229. readp = end_of_path(readp, PART_FRAGMENT, flags);
  4230. }
  4231. if (*readp != '\0') {
  4232. goto err;
  4233. }
  4234. /* These next two cases may be unreachable; I'm leaving them
  4235. * in to be defensive. */
  4236. /* If you didn't get an authority, the path can't begin with "//" */
  4237. if (!got_authority && path[0]=='/' && path[1]=='/')
  4238. goto err;
  4239. /* If you did get an authority, the path must begin with "/" or be
  4240. * empty. */
  4241. if (got_authority && path[0] != '/' && path[0] != '\0')
  4242. goto err;
  4243. /* (End of maybe-unreachable cases) */
  4244. /* If there was no scheme, the first part of the path (if any) must
  4245. * have no colon in it. */
  4246. if (! uri->scheme && !path_matches_noscheme(path))
  4247. goto err;
  4248. EVUTIL_ASSERT(path);
  4249. uri->path = mm_strdup(path);
  4250. if (uri->path == NULL) {
  4251. event_warn("%s: strdup", __func__);
  4252. goto err;
  4253. }
  4254. if (query) {
  4255. uri->query = mm_strdup(query);
  4256. if (uri->query == NULL) {
  4257. event_warn("%s: strdup", __func__);
  4258. goto err;
  4259. }
  4260. }
  4261. if (fragment) {
  4262. uri->fragment = mm_strdup(fragment);
  4263. if (uri->fragment == NULL) {
  4264. event_warn("%s: strdup", __func__);
  4265. goto err;
  4266. }
  4267. }
  4268. mm_free(readbuf);
  4269. return uri;
  4270. err:
  4271. if (uri)
  4272. evhttp_uri_free(uri);
  4273. if (readbuf)
  4274. mm_free(readbuf);
  4275. return NULL;
  4276. }
  4277. static struct evhttp_uri *
  4278. evhttp_uri_parse_authority(char *source_uri)
  4279. {
  4280. struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
  4281. char *end;
  4282. if (uri == NULL) {
  4283. event_warn("%s: calloc", __func__);
  4284. goto err;
  4285. }
  4286. uri->port = -1;
  4287. uri->flags = 0;
  4288. end = end_of_authority(source_uri);
  4289. if (parse_authority(uri, source_uri, end) < 0)
  4290. goto err;
  4291. uri->path = mm_strdup("");
  4292. if (uri->path == NULL) {
  4293. event_warn("%s: strdup", __func__);
  4294. goto err;
  4295. }
  4296. return uri;
  4297. err:
  4298. if (uri)
  4299. evhttp_uri_free(uri);
  4300. return NULL;
  4301. }
  4302. void
  4303. evhttp_uri_free(struct evhttp_uri *uri)
  4304. {
  4305. #define URI_FREE_STR_(f) \
  4306. if (uri->f) { \
  4307. mm_free(uri->f); \
  4308. }
  4309. URI_FREE_STR_(scheme);
  4310. URI_FREE_STR_(userinfo);
  4311. URI_FREE_STR_(host);
  4312. URI_FREE_STR_(path);
  4313. URI_FREE_STR_(query);
  4314. URI_FREE_STR_(fragment);
  4315. mm_free(uri);
  4316. #undef URI_FREE_STR_
  4317. }
  4318. char *
  4319. evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
  4320. {
  4321. struct evbuffer *tmp = 0;
  4322. size_t joined_size = 0;
  4323. char *output = NULL;
  4324. #define URI_ADD_(f) evbuffer_add(tmp, uri->f, strlen(uri->f))
  4325. if (!uri || !buf || !limit)
  4326. return NULL;
  4327. tmp = evbuffer_new();
  4328. if (!tmp)
  4329. return NULL;
  4330. if (uri->scheme) {
  4331. URI_ADD_(scheme);
  4332. evbuffer_add(tmp, ":", 1);
  4333. }
  4334. if (uri->host) {
  4335. evbuffer_add(tmp, "//", 2);
  4336. if (uri->userinfo)
  4337. evbuffer_add_printf(tmp,"%s@", uri->userinfo);
  4338. URI_ADD_(host);
  4339. if (uri->port >= 0)
  4340. evbuffer_add_printf(tmp,":%d", uri->port);
  4341. if (uri->path && uri->path[0] != '/' && uri->path[0] != '\0')
  4342. goto err;
  4343. }
  4344. if (uri->path)
  4345. URI_ADD_(path);
  4346. if (uri->query) {
  4347. evbuffer_add(tmp, "?", 1);
  4348. URI_ADD_(query);
  4349. }
  4350. if (uri->fragment) {
  4351. evbuffer_add(tmp, "#", 1);
  4352. URI_ADD_(fragment);
  4353. }
  4354. evbuffer_add(tmp, "\0", 1); /* NUL */
  4355. joined_size = evbuffer_get_length(tmp);
  4356. if (joined_size > limit) {
  4357. /* It doesn't fit. */
  4358. evbuffer_free(tmp);
  4359. return NULL;
  4360. }
  4361. evbuffer_remove(tmp, buf, joined_size);
  4362. output = buf;
  4363. err:
  4364. evbuffer_free(tmp);
  4365. return output;
  4366. #undef URI_ADD_
  4367. }
  4368. const char *
  4369. evhttp_uri_get_scheme(const struct evhttp_uri *uri)
  4370. {
  4371. return uri->scheme;
  4372. }
  4373. const char *
  4374. evhttp_uri_get_userinfo(const struct evhttp_uri *uri)
  4375. {
  4376. return uri->userinfo;
  4377. }
  4378. const char *
  4379. evhttp_uri_get_host(const struct evhttp_uri *uri)
  4380. {
  4381. return uri->host;
  4382. }
  4383. int
  4384. evhttp_uri_get_port(const struct evhttp_uri *uri)
  4385. {
  4386. return uri->port;
  4387. }
  4388. const char *
  4389. evhttp_uri_get_path(const struct evhttp_uri *uri)
  4390. {
  4391. return uri->path;
  4392. }
  4393. const char *
  4394. evhttp_uri_get_query(const struct evhttp_uri *uri)
  4395. {
  4396. return uri->query;
  4397. }
  4398. const char *
  4399. evhttp_uri_get_fragment(const struct evhttp_uri *uri)
  4400. {
  4401. return uri->fragment;
  4402. }
  4403. #define URI_SET_STR_(f) do { \
  4404. if (uri->f) \
  4405. mm_free(uri->f); \
  4406. if (f) { \
  4407. if ((uri->f = mm_strdup(f)) == NULL) { \
  4408. event_warn("%s: strdup()", __func__); \
  4409. return -1; \
  4410. } \
  4411. } else { \
  4412. uri->f = NULL; \
  4413. } \
  4414. } while(0)
  4415. int
  4416. evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
  4417. {
  4418. if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
  4419. return -1;
  4420. URI_SET_STR_(scheme);
  4421. return 0;
  4422. }
  4423. int
  4424. evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
  4425. {
  4426. if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
  4427. return -1;
  4428. URI_SET_STR_(userinfo);
  4429. return 0;
  4430. }
  4431. int
  4432. evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
  4433. {
  4434. if (host) {
  4435. if (host[0] == '[') {
  4436. if (! bracket_addr_ok(host, host+strlen(host)))
  4437. return -1;
  4438. } else {
  4439. if (! regname_ok(host, host+strlen(host)))
  4440. return -1;
  4441. }
  4442. }
  4443. URI_SET_STR_(host);
  4444. return 0;
  4445. }
  4446. int
  4447. evhttp_uri_set_port(struct evhttp_uri *uri, int port)
  4448. {
  4449. if (port < -1)
  4450. return -1;
  4451. uri->port = port;
  4452. return 0;
  4453. }
  4454. #define end_of_cpath(cp,p,f) \
  4455. ((const char*)(end_of_path(((char*)(cp)), (p), (f))))
  4456. int
  4457. evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
  4458. {
  4459. if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
  4460. return -1;
  4461. URI_SET_STR_(path);
  4462. return 0;
  4463. }
  4464. int
  4465. evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
  4466. {
  4467. if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
  4468. return -1;
  4469. URI_SET_STR_(query);
  4470. return 0;
  4471. }
  4472. int
  4473. evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
  4474. {
  4475. if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
  4476. return -1;
  4477. URI_SET_STR_(fragment);
  4478. return 0;
  4479. }