civetweb.c 194 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086
  1. // Copyright (c) 2004-2013 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #if !defined(_CRT_SECURE_NO_WARNINGS)
  22. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  23. #endif
  24. #else
  25. #ifdef __linux__
  26. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  27. #endif
  28. #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
  29. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  30. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  31. #endif
  32. #if defined (_MSC_VER)
  33. // 'type cast' : conversion from 'int' to 'HANDLE' of greater size
  34. #pragma warning (disable : 4306 )
  35. // conditional expression is constant: introduced by FD_SET(..)
  36. #pragma warning (disable : 4127)
  37. // non-constant aggregate initializer: issued due to missing C99 support
  38. #pragma warning (disable : 4204)
  39. #endif
  40. // Disable WIN32_LEAN_AND_MEAN.
  41. // This makes windows.h always include winsock2.h
  42. #if defined(WIN32_LEAN_AND_MEAN) && (_MSC_VER <= 1400)
  43. #undef WIN32_LEAN_AND_MEAN
  44. #endif
  45. #if defined USE_IPV6 && defined(_WIN32)
  46. #include <ws2tcpip.h>
  47. #endif
  48. #if defined(__SYMBIAN32__)
  49. #define NO_SSL // SSL is not supported
  50. #define NO_CGI // CGI is not supported
  51. #define PATH_MAX FILENAME_MAX
  52. #endif // __SYMBIAN32__
  53. #ifndef IGNORE_UNUSED_RESULT
  54. #define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
  55. #endif
  56. #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
  57. #include <sys/types.h>
  58. #include <sys/stat.h>
  59. #include <errno.h>
  60. #include <signal.h>
  61. #include <fcntl.h>
  62. #endif // !_WIN32_WCE
  63. #include <time.h>
  64. #include <stdlib.h>
  65. #include <stdarg.h>
  66. #include <assert.h>
  67. #include <string.h>
  68. #include <ctype.h>
  69. #include <limits.h>
  70. #include <stddef.h>
  71. #include <stdio.h>
  72. #define MAX_WORKER_THREADS 1024
  73. #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
  74. #if defined(_MSC_VER) && _MSC_VER <= 1400
  75. #undef _WIN32_WINNT
  76. #define _WIN32_WINNT 0x0400 // To make it link in VS2005
  77. #endif
  78. #include <windows.h>
  79. #ifndef PATH_MAX
  80. #define PATH_MAX MAX_PATH
  81. #endif
  82. #ifndef _WIN32_WCE
  83. #include <process.h>
  84. #include <direct.h>
  85. #include <io.h>
  86. #else // _WIN32_WCE
  87. #define NO_CGI // WinCE has no pipes
  88. typedef long off_t;
  89. #define errno GetLastError()
  90. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  91. #endif // _WIN32_WCE
  92. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  93. ((uint64_t)((uint32_t)(hi))) << 32))
  94. #define RATE_DIFF 10000000 // 100 nsecs
  95. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  96. #define SYS2UNIX_TIME(lo, hi) \
  97. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  98. // Visual Studio 6 does not know __func__ or __FUNCTION__
  99. // The rest of MS compilers use __FUNCTION__, not C99 __func__
  100. // Also use _strtoui64 on modern M$ compilers
  101. #if defined(_MSC_VER) && _MSC_VER < 1300
  102. #define STRX(x) #x
  103. #define STR(x) STRX(x)
  104. #define __func__ __FILE__ ":" STR(__LINE__)
  105. #define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
  106. #define strtoll(x, y, z) _atoi64(x)
  107. #else
  108. #define __func__ __FUNCTION__
  109. #define strtoull(x, y, z) _strtoui64(x, y, z)
  110. #define strtoll(x, y, z) _strtoi64(x, y, z)
  111. #endif // _MSC_VER
  112. #define ERRNO GetLastError()
  113. #define NO_SOCKLEN_T
  114. #define SSL_LIB "ssleay32.dll"
  115. #define CRYPTO_LIB "libeay32.dll"
  116. #define O_NONBLOCK 0
  117. #if !defined(EWOULDBLOCK)
  118. #define EWOULDBLOCK WSAEWOULDBLOCK
  119. #endif // !EWOULDBLOCK
  120. #define _POSIX_
  121. #define INT64_FMT "I64d"
  122. #define WINCDECL __cdecl
  123. #define SHUT_WR 1
  124. #define snprintf _snprintf
  125. #define vsnprintf _vsnprintf
  126. #define mg_sleep(x) Sleep(x)
  127. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  128. #ifndef popen
  129. #define popen(x, y) _popen(x, y)
  130. #endif
  131. #ifndef pclose
  132. #define pclose(x) _pclose(x)
  133. #endif
  134. #define close(x) _close(x)
  135. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  136. #define RTLD_LAZY 0
  137. #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  138. #define fdopen(x, y) _fdopen((x), (y))
  139. #define write(x, y, z) _write((x), (y), (unsigned) z)
  140. #define read(x, y, z) _read((x), (y), (unsigned) z)
  141. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  142. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  143. #define sleep(x) Sleep((x) * 1000)
  144. #define rmdir(x) _rmdir(x)
  145. #if !defined(va_copy)
  146. #define va_copy(x, y) x = y
  147. #endif // !va_copy MINGW #defines va_copy
  148. #if !defined(fileno)
  149. #define fileno(x) _fileno(x)
  150. #endif // !fileno MINGW #defines fileno
  151. typedef HANDLE pthread_mutex_t;
  152. typedef HANDLE pthread_t;
  153. typedef struct {
  154. CRITICAL_SECTION threadIdSec;
  155. int waitingthreadcount; // The amount of worker threads.
  156. pthread_t *waitingthreadids;// The worker thread IDs.
  157. } pthread_cond_t;
  158. #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
  159. static int pthread_mutex_lock(pthread_mutex_t *);
  160. static int pthread_mutex_unlock(pthread_mutex_t *);
  161. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  162. struct file;
  163. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  164. #if defined(HAVE_STDINT)
  165. #include <stdint.h>
  166. #else
  167. typedef unsigned int uint32_t;
  168. typedef unsigned short uint16_t;
  169. typedef unsigned __int64 uint64_t;
  170. typedef __int64 int64_t;
  171. #define INT64_MAX 9223372036854775807
  172. #endif // HAVE_STDINT
  173. // POSIX dirent interface
  174. struct dirent {
  175. char d_name[PATH_MAX];
  176. };
  177. typedef struct DIR {
  178. HANDLE handle;
  179. WIN32_FIND_DATAW info;
  180. struct dirent result;
  181. } DIR;
  182. #if !defined(USE_IPV6) && defined(_WIN32)
  183. #ifndef HAVE_POLL
  184. struct pollfd {
  185. SOCKET fd;
  186. short events;
  187. short revents;
  188. };
  189. #define POLLIN 1
  190. #endif
  191. #endif
  192. // Mark required libraries
  193. #ifdef _MSC_VER
  194. #pragma comment(lib, "Ws2_32.lib")
  195. #endif
  196. #else // UNIX specific
  197. #include <sys/wait.h>
  198. #include <sys/socket.h>
  199. #include <sys/poll.h>
  200. #include <netinet/in.h>
  201. #include <arpa/inet.h>
  202. #include <sys/time.h>
  203. #include <stdint.h>
  204. #include <inttypes.h>
  205. #include <netdb.h>
  206. #include <pwd.h>
  207. #include <unistd.h>
  208. #include <dirent.h>
  209. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  210. #include <dlfcn.h>
  211. #endif
  212. #include <pthread.h>
  213. #if defined(__MACH__)
  214. #define SSL_LIB "libssl.dylib"
  215. #define CRYPTO_LIB "libcrypto.dylib"
  216. #else
  217. #if !defined(SSL_LIB)
  218. #define SSL_LIB "libssl.so"
  219. #endif
  220. #if !defined(CRYPTO_LIB)
  221. #define CRYPTO_LIB "libcrypto.so"
  222. #endif
  223. #endif
  224. #ifndef O_BINARY
  225. #define O_BINARY 0
  226. #endif // O_BINARY
  227. #define closesocket(a) close(a)
  228. #define mg_mkdir(x, y) mkdir(x, y)
  229. #define mg_remove(x) remove(x)
  230. #define mg_sleep(x) usleep((x) * 1000)
  231. #define ERRNO errno
  232. #define INVALID_SOCKET (-1)
  233. #define INT64_FMT PRId64
  234. typedef int SOCKET;
  235. #define WINCDECL
  236. #endif // End of Windows and UNIX specific includes
  237. #include "civetweb.h"
  238. #define CIVETWEB_VERSION "1.5"
  239. #define PASSWORDS_FILE_NAME ".htpasswd"
  240. #define CGI_ENVIRONMENT_SIZE 4096
  241. #define MAX_CGI_ENVIR_VARS 64
  242. #define MG_BUF_LEN 8192
  243. #ifndef MAX_REQUEST_SIZE
  244. #define MAX_REQUEST_SIZE 16384
  245. #endif
  246. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  247. #ifdef _WIN32
  248. static CRITICAL_SECTION global_log_file_lock;
  249. static DWORD pthread_self(void)
  250. {
  251. return GetCurrentThreadId();
  252. }
  253. #endif // _WIN32
  254. #define MD5_STATIC static
  255. #include "md5.inl"
  256. #ifdef DEBUG_TRACE
  257. #undef DEBUG_TRACE
  258. #define DEBUG_TRACE(x)
  259. #else
  260. #if defined(DEBUG)
  261. #define DEBUG_TRACE(x) do { \
  262. flockfile(stdout); \
  263. printf("*** %lu.%p.%s.%d: ", \
  264. (unsigned long) time(NULL), (void *) pthread_self(), \
  265. __func__, __LINE__); \
  266. printf x; \
  267. putchar('\n'); \
  268. fflush(stdout); \
  269. funlockfile(stdout); \
  270. } while (0)
  271. #else
  272. #define DEBUG_TRACE(x)
  273. #endif // DEBUG
  274. #endif // DEBUG_TRACE
  275. // Darwin prior to 7.0 and Win32 do not have socklen_t
  276. #ifdef NO_SOCKLEN_T
  277. typedef int socklen_t;
  278. #endif // NO_SOCKLEN_T
  279. #define _DARWIN_UNLIMITED_SELECT
  280. #define IP_ADDR_STR_LEN 50 // IPv6 hex string is 46 chars
  281. #if !defined(MSG_NOSIGNAL)
  282. #define MSG_NOSIGNAL 0
  283. #endif
  284. #if !defined(SOMAXCONN)
  285. #define SOMAXCONN 100
  286. #endif
  287. #if !defined(PATH_MAX)
  288. #define PATH_MAX 4096
  289. #endif
  290. // Size of the accepted socket queue
  291. #if !defined(MGSQLEN)
  292. #define MGSQLEN 20
  293. #endif
  294. static const char *http_500_error = "Internal Server Error";
  295. #if defined(NO_SSL_DL)
  296. #include <openssl/ssl.h>
  297. #include <openssl/err.h>
  298. #else
  299. // SSL loaded dynamically from DLL.
  300. // I put the prototypes here to be independent from OpenSSL source installation.
  301. typedef struct ssl_st SSL;
  302. typedef struct ssl_method_st SSL_METHOD;
  303. typedef struct ssl_ctx_st SSL_CTX;
  304. struct ssl_func {
  305. const char *name; // SSL function name
  306. void (*ptr)(void); // Function pointer
  307. };
  308. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  309. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  310. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  311. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  312. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  313. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  314. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  315. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  316. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  317. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  318. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  319. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  320. const char *, int)) ssl_sw[11].ptr)
  321. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  322. const char *, int)) ssl_sw[12].ptr)
  323. #define SSL_CTX_set_default_passwd_cb \
  324. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  325. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  326. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  327. #define SSL_CTX_use_certificate_chain_file \
  328. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  329. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  330. #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
  331. #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
  332. #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
  333. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  334. #define CRYPTO_set_locking_callback \
  335. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  336. #define CRYPTO_set_id_callback \
  337. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  338. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  339. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  340. // set_ssl_option() function updates this array.
  341. // It loads SSL library dynamically and changes NULLs to the actual addresses
  342. // of respective functions. The macros above (like SSL_connect()) are really
  343. // just calling these functions indirectly via the pointer.
  344. static struct ssl_func ssl_sw[] = {
  345. {"SSL_free", NULL},
  346. {"SSL_accept", NULL},
  347. {"SSL_connect", NULL},
  348. {"SSL_read", NULL},
  349. {"SSL_write", NULL},
  350. {"SSL_get_error", NULL},
  351. {"SSL_set_fd", NULL},
  352. {"SSL_new", NULL},
  353. {"SSL_CTX_new", NULL},
  354. {"SSLv23_server_method", NULL},
  355. {"SSL_library_init", NULL},
  356. {"SSL_CTX_use_PrivateKey_file", NULL},
  357. {"SSL_CTX_use_certificate_file",NULL},
  358. {"SSL_CTX_set_default_passwd_cb",NULL},
  359. {"SSL_CTX_free", NULL},
  360. {"SSL_load_error_strings", NULL},
  361. {"SSL_CTX_use_certificate_chain_file", NULL},
  362. {"SSLv23_client_method", NULL},
  363. {"SSL_pending", NULL},
  364. {"SSL_CTX_set_verify", NULL},
  365. {"SSL_shutdown", NULL},
  366. {NULL, NULL}
  367. };
  368. // Similar array as ssl_sw. These functions could be located in different lib.
  369. #if !defined(NO_SSL)
  370. static struct ssl_func crypto_sw[] = {
  371. {"CRYPTO_num_locks", NULL},
  372. {"CRYPTO_set_locking_callback", NULL},
  373. {"CRYPTO_set_id_callback", NULL},
  374. {"ERR_get_error", NULL},
  375. {"ERR_error_string", NULL},
  376. {NULL, NULL}
  377. };
  378. #endif // NO_SSL
  379. #endif // NO_SSL_DL
  380. static const char *month_names[] = {
  381. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  382. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  383. };
  384. // Unified socket address. For IPv6 support, add IPv6 address structure
  385. // in the union u.
  386. union usa {
  387. struct sockaddr sa;
  388. struct sockaddr_in sin;
  389. #if defined(USE_IPV6)
  390. struct sockaddr_in6 sin6;
  391. #endif
  392. };
  393. // Describes a string (chunk of memory).
  394. struct vec {
  395. const char *ptr;
  396. size_t len;
  397. };
  398. struct file {
  399. int is_directory;
  400. time_t modification_time;
  401. int64_t size;
  402. FILE *fp;
  403. const char *membuf; // Non-NULL if file data is in memory
  404. // set to 1 if the content is gzipped
  405. // in which case we need a content-encoding: gzip header
  406. int gzipped;
  407. };
  408. #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
  409. // Describes listening socket, or socket which was accept()-ed by the master
  410. // thread and queued for future handling by the worker thread.
  411. struct socket {
  412. SOCKET sock; // Listening socket
  413. union usa lsa; // Local socket address
  414. union usa rsa; // Remote socket address
  415. unsigned is_ssl:1; // Is port SSL-ed
  416. unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port
  417. };
  418. // NOTE(lsm): this enum shoulds be in sync with the config_options below.
  419. enum {
  420. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  421. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  422. ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  423. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  424. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  425. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
  426. NUM_OPTIONS
  427. };
  428. static const char *config_options[] = {
  429. "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  430. "cgi_environment", NULL,
  431. "put_delete_auth_file", NULL,
  432. "cgi_interpreter", NULL,
  433. "protect_uri", NULL,
  434. "authentication_domain", "mydomain.com",
  435. "ssi_pattern", "**.shtml$|**.shtm$",
  436. "throttle", NULL,
  437. "access_log_file", NULL,
  438. "enable_directory_listing", "yes",
  439. "error_log_file", NULL,
  440. "global_auth_file", NULL,
  441. "index_files",
  442. "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",
  443. "enable_keep_alive", "no",
  444. "access_control_list", NULL,
  445. "extra_mime_types", NULL,
  446. "listening_ports", "8080",
  447. "document_root", NULL,
  448. "ssl_certificate", NULL,
  449. "num_threads", "50",
  450. "run_as_user", NULL,
  451. "url_rewrite_patterns", NULL,
  452. "hide_files_patterns", NULL,
  453. "request_timeout_ms", "30000",
  454. NULL
  455. };
  456. struct mg_request_handler_info {
  457. char *uri;
  458. size_t uri_len;
  459. mg_request_handler handler;
  460. void *cbdata;
  461. struct mg_request_handler_info *next;
  462. };
  463. struct mg_context {
  464. volatile int stop_flag; // Should we stop event loop
  465. void *ssllib_dll_handle; // Store the ssl library handle.
  466. void *cryptolib_dll_handle; // Store the crypto library handle.
  467. SSL_CTX *ssl_ctx; // SSL context
  468. char *config[NUM_OPTIONS]; // Civetweb configuration parameters
  469. struct mg_callbacks callbacks; // User-defined callback function
  470. void *user_data; // User-defined data
  471. struct socket *listening_sockets;
  472. int num_listening_sockets;
  473. volatile int num_threads; // Number of threads
  474. pthread_mutex_t mutex; // Protects (max|num)_threads
  475. pthread_cond_t cond; // Condvar for tracking workers terminations
  476. struct socket queue[MGSQLEN]; // Accepted sockets
  477. volatile int sq_head; // Head of the socket queue
  478. volatile int sq_tail; // Tail of the socket queue
  479. pthread_cond_t sq_full; // Signaled when socket is produced
  480. pthread_cond_t sq_empty; // Signaled when socket is consumed
  481. pthread_t masterthreadid; // The master thread ID.
  482. int workerthreadcount; // The amount of worker threads.
  483. pthread_t *workerthreadids;// The worker thread IDs.
  484. // linked list of uri handlers
  485. struct mg_request_handler_info *request_handlers;
  486. };
  487. struct mg_connection {
  488. struct mg_request_info request_info;
  489. struct mg_context *ctx;
  490. SSL *ssl; // SSL descriptor
  491. SSL_CTX *client_ssl_ctx; // SSL context for client connections
  492. struct socket client; // Connected client
  493. time_t birth_time; // Time when request was received
  494. int64_t num_bytes_sent; // Total bytes sent to client
  495. int64_t content_len; // Content-Length header value
  496. int64_t consumed_content; // How many bytes of content have been read
  497. char *buf; // Buffer for received data
  498. char *path_info; // PATH_INFO part of the URL
  499. int must_close; // 1 if connection must be closed
  500. int buf_size; // Buffer size
  501. int request_len; // Size of the request + headers in a buffer
  502. int data_len; // Total size of data in a buffer
  503. int status_code; // HTTP reply status code, e.g. 200
  504. int throttle; // Throttling, bytes/sec. <= 0 means no throttle
  505. time_t last_throttle_time; // Last time throttled data was sent
  506. int64_t last_throttle_bytes;// Bytes sent this second
  507. pthread_mutex_t mutex; // Used by mg_lock/mg_unlock to ensure atomic transmissions for websockets
  508. };
  509. // Directory entry
  510. struct de {
  511. struct mg_connection *conn;
  512. char *file_name;
  513. struct file file;
  514. };
  515. const char **mg_get_valid_option_names(void)
  516. {
  517. return config_options;
  518. }
  519. static int is_file_in_memory(struct mg_connection *conn, const char *path,
  520. struct file *filep)
  521. {
  522. size_t size = 0;
  523. if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
  524. conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  525. // NOTE: override filep->size only on success. Otherwise, it might break
  526. // constructs like if (!mg_stat() || !mg_fopen()) ...
  527. filep->size = size;
  528. }
  529. return filep->membuf != NULL;
  530. }
  531. static int is_file_opened(const struct file *filep)
  532. {
  533. return filep->membuf != NULL || filep->fp != NULL;
  534. }
  535. static int mg_fopen(struct mg_connection *conn, const char *path,
  536. const char *mode, struct file *filep)
  537. {
  538. if (!is_file_in_memory(conn, path, filep)) {
  539. #ifdef _WIN32
  540. wchar_t wbuf[PATH_MAX], wmode[20];
  541. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  542. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  543. filep->fp = _wfopen(wbuf, wmode);
  544. #else
  545. filep->fp = fopen(path, mode);
  546. #endif
  547. }
  548. return is_file_opened(filep);
  549. }
  550. static void mg_fclose(struct file *filep)
  551. {
  552. if (filep != NULL && filep->fp != NULL) {
  553. fclose(filep->fp);
  554. }
  555. }
  556. static int get_option_index(const char *name)
  557. {
  558. int i;
  559. for (i = 0; config_options[i * 2] != NULL; i++) {
  560. if (strcmp(config_options[i * 2], name) == 0) {
  561. return i;
  562. }
  563. }
  564. return -1;
  565. }
  566. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  567. {
  568. int i;
  569. if ((i = get_option_index(name)) == -1) {
  570. return NULL;
  571. } else if (ctx->config[i] == NULL) {
  572. return "";
  573. } else {
  574. return ctx->config[i];
  575. }
  576. }
  577. static void sockaddr_to_string(char *buf, size_t len,
  578. const union usa *usa)
  579. {
  580. buf[0] = '\0';
  581. #if defined(USE_IPV6)
  582. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  583. (void *) &usa->sin.sin_addr :
  584. (void *) &usa->sin6.sin6_addr, buf, len);
  585. #elif defined(_WIN32)
  586. // Only Windoze Vista (and newer) have inet_ntop()
  587. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  588. #else
  589. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  590. #endif
  591. }
  592. // Print error message to the opened error log stream.
  593. void mg_cry(struct mg_connection *conn, const char *fmt, ...)
  594. {
  595. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  596. va_list ap;
  597. FILE *fp;
  598. time_t timestamp;
  599. va_start(ap, fmt);
  600. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  601. va_end(ap);
  602. // Do not lock when getting the callback value, here and below.
  603. // I suppose this is fine, since function cannot disappear in the
  604. // same way string option can.
  605. if (conn->ctx->callbacks.log_message == NULL ||
  606. conn->ctx->callbacks.log_message(conn, buf) == 0) {
  607. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  608. fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  609. if (fp != NULL) {
  610. flockfile(fp);
  611. timestamp = time(NULL);
  612. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  613. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  614. src_addr);
  615. if (conn->request_info.request_method != NULL) {
  616. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  617. conn->request_info.uri);
  618. }
  619. fprintf(fp, "%s", buf);
  620. fputc('\n', fp);
  621. funlockfile(fp);
  622. fclose(fp);
  623. }
  624. }
  625. }
  626. // Return fake connection structure. Used for logging, if connection
  627. // is not applicable at the moment of logging.
  628. static struct mg_connection *fc(struct mg_context *ctx)
  629. {
  630. static struct mg_connection fake_connection;
  631. fake_connection.ctx = ctx;
  632. return &fake_connection;
  633. }
  634. const char *mg_version(void)
  635. {
  636. return CIVETWEB_VERSION;
  637. }
  638. struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
  639. {
  640. return &conn->request_info;
  641. }
  642. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  643. {
  644. for (; *src != '\0' && n > 1; n--) {
  645. *dst++ = *src++;
  646. }
  647. *dst = '\0';
  648. }
  649. static int lowercase(const char *s)
  650. {
  651. return tolower(* (const unsigned char *) s);
  652. }
  653. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  654. {
  655. int diff = 0;
  656. if (len > 0)
  657. do {
  658. diff = lowercase(s1++) - lowercase(s2++);
  659. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  660. return diff;
  661. }
  662. static int mg_strcasecmp(const char *s1, const char *s2)
  663. {
  664. int diff;
  665. do {
  666. diff = lowercase(s1++) - lowercase(s2++);
  667. } while (diff == 0 && s1[-1] != '\0');
  668. return diff;
  669. }
  670. static char * mg_strndup(const char *ptr, size_t len)
  671. {
  672. char *p;
  673. if ((p = (char *) malloc(len + 1)) != NULL) {
  674. mg_strlcpy(p, ptr, len + 1);
  675. }
  676. return p;
  677. }
  678. static char * mg_strdup(const char *str)
  679. {
  680. return mg_strndup(str, strlen(str));
  681. }
  682. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  683. {
  684. int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
  685. for (i = 0; i <= big_len - small_len; i++) {
  686. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  687. return big_str + i;
  688. }
  689. }
  690. return NULL;
  691. }
  692. // Like snprintf(), but never returns negative value, or a value
  693. // that is larger than a supplied buffer.
  694. // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  695. // in his audit report.
  696. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  697. const char *fmt, va_list ap)
  698. {
  699. int n;
  700. if (buflen == 0)
  701. return 0;
  702. n = vsnprintf(buf, buflen, fmt, ap);
  703. if (n < 0) {
  704. mg_cry(conn, "vsnprintf error");
  705. n = 0;
  706. } else if (n >= (int) buflen) {
  707. mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
  708. n > 200 ? 200 : n, buf);
  709. n = (int) buflen - 1;
  710. }
  711. buf[n] = '\0';
  712. return n;
  713. }
  714. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  715. PRINTF_FORMAT_STRING(const char *fmt), ...)
  716. PRINTF_ARGS(4, 5);
  717. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  718. const char *fmt, ...)
  719. {
  720. va_list ap;
  721. int n;
  722. va_start(ap, fmt);
  723. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  724. va_end(ap);
  725. return n;
  726. }
  727. // Skip the characters until one of the delimiters characters found.
  728. // 0-terminate resulting word. Skip the delimiter and following whitespaces.
  729. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  730. // Delimiters can be quoted with quotechar.
  731. static char *skip_quoted(char **buf, const char *delimiters,
  732. const char *whitespace, char quotechar)
  733. {
  734. char *p, *begin_word, *end_word, *end_whitespace;
  735. begin_word = *buf;
  736. end_word = begin_word + strcspn(begin_word, delimiters);
  737. // Check for quotechar
  738. if (end_word > begin_word) {
  739. p = end_word - 1;
  740. while (*p == quotechar) {
  741. // If there is anything beyond end_word, copy it
  742. if (*end_word == '\0') {
  743. *p = '\0';
  744. break;
  745. } else {
  746. size_t end_off = strcspn(end_word + 1, delimiters);
  747. memmove (p, end_word, end_off + 1);
  748. p += end_off; // p must correspond to end_word - 1
  749. end_word += end_off + 1;
  750. }
  751. }
  752. for (p++; p < end_word; p++) {
  753. *p = '\0';
  754. }
  755. }
  756. if (*end_word == '\0') {
  757. *buf = end_word;
  758. } else {
  759. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  760. for (p = end_word; p < end_whitespace; p++) {
  761. *p = '\0';
  762. }
  763. *buf = end_whitespace;
  764. }
  765. return begin_word;
  766. }
  767. // Simplified version of skip_quoted without quote char
  768. // and whitespace == delimiters
  769. static char *skip(char **buf, const char *delimiters)
  770. {
  771. return skip_quoted(buf, delimiters, delimiters, 0);
  772. }
  773. // Return HTTP header value, or NULL if not found.
  774. static const char *get_header(const struct mg_request_info *ri,
  775. const char *name)
  776. {
  777. int i;
  778. for (i = 0; i < ri->num_headers; i++)
  779. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  780. return ri->http_headers[i].value;
  781. return NULL;
  782. }
  783. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  784. {
  785. return get_header(&conn->request_info, name);
  786. }
  787. // A helper function for traversing a comma separated list of values.
  788. // It returns a list pointer shifted to the next value, or NULL if the end
  789. // of the list found.
  790. // Value is stored in val vector. If value has form "x=y", then eq_val
  791. // vector is initialized to point to the "y" part, and val vector length
  792. // is adjusted to point only to "x".
  793. static const char *next_option(const char *list, struct vec *val,
  794. struct vec *eq_val)
  795. {
  796. if (list == NULL || *list == '\0') {
  797. // End of the list
  798. list = NULL;
  799. } else {
  800. val->ptr = list;
  801. if ((list = strchr(val->ptr, ',')) != NULL) {
  802. // Comma found. Store length and shift the list ptr
  803. val->len = list - val->ptr;
  804. list++;
  805. } else {
  806. // This value is the last one
  807. list = val->ptr + strlen(val->ptr);
  808. val->len = list - val->ptr;
  809. }
  810. if (eq_val != NULL) {
  811. // Value has form "x=y", adjust pointers and lengths
  812. // so that val points to "x", and eq_val points to "y".
  813. eq_val->len = 0;
  814. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  815. if (eq_val->ptr != NULL) {
  816. eq_val->ptr++; // Skip over '=' character
  817. eq_val->len = val->ptr + val->len - eq_val->ptr;
  818. val->len = (eq_val->ptr - val->ptr) - 1;
  819. }
  820. }
  821. }
  822. return list;
  823. }
  824. // Perform case-insensitive match of string against pattern
  825. static int match_prefix(const char *pattern, int pattern_len, const char *str)
  826. {
  827. const char *or_str;
  828. int i, j, len, res;
  829. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  830. res = match_prefix(pattern, (int)(or_str - pattern), str);
  831. return res > 0 ? res :
  832. match_prefix(or_str + 1, (int)((pattern + pattern_len) - (or_str + 1)), str);
  833. }
  834. i = j = 0;
  835. res = -1;
  836. for (; i < pattern_len; i++, j++) {
  837. if (pattern[i] == '?' && str[j] != '\0') {
  838. continue;
  839. } else if (pattern[i] == '$') {
  840. return str[j] == '\0' ? j : -1;
  841. } else if (pattern[i] == '*') {
  842. i++;
  843. if (pattern[i] == '*') {
  844. i++;
  845. len = (int) strlen(str + j);
  846. } else {
  847. len = (int) strcspn(str + j, "/");
  848. }
  849. if (i == pattern_len) {
  850. return j + len;
  851. }
  852. do {
  853. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  854. } while (res == -1 && len-- > 0);
  855. return res == -1 ? -1 : j + res + len;
  856. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  857. return -1;
  858. }
  859. }
  860. return j;
  861. }
  862. // HTTP 1.1 assumes keep alive if "Connection:" header is not set
  863. // This function must tolerate situations when connection info is not
  864. // set up, for example if request parsing failed.
  865. static int should_keep_alive(const struct mg_connection *conn)
  866. {
  867. const char *http_version = conn->request_info.http_version;
  868. const char *header = mg_get_header(conn, "Connection");
  869. if (conn->must_close ||
  870. conn->status_code == 401 ||
  871. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  872. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  873. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  874. return 0;
  875. }
  876. return 1;
  877. }
  878. static const char *suggest_connection_header(const struct mg_connection *conn)
  879. {
  880. return should_keep_alive(conn) ? "keep-alive" : "close";
  881. }
  882. static void send_http_error(struct mg_connection *, int, const char *,
  883. PRINTF_FORMAT_STRING(const char *fmt), ...)
  884. PRINTF_ARGS(4, 5);
  885. static void send_http_error(struct mg_connection *conn, int status,
  886. const char *reason, const char *fmt, ...)
  887. {
  888. char buf[MG_BUF_LEN];
  889. va_list ap;
  890. int len = 0;
  891. conn->status_code = status;
  892. if (conn->ctx->callbacks.http_error == NULL ||
  893. conn->ctx->callbacks.http_error(conn, status)) {
  894. buf[0] = '\0';
  895. // Errors 1xx, 204 and 304 MUST NOT send a body
  896. if (status > 199 && status != 204 && status != 304) {
  897. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  898. buf[len++] = '\n';
  899. va_start(ap, fmt);
  900. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  901. va_end(ap);
  902. }
  903. DEBUG_TRACE(("[%s]", buf));
  904. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  905. "Content-Length: %d\r\n"
  906. "Connection: %s\r\n\r\n", status, reason, len,
  907. suggest_connection_header(conn));
  908. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  909. }
  910. }
  911. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  912. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  913. {
  914. (void) unused;
  915. *mutex = CreateMutex(NULL, FALSE, NULL);
  916. return *mutex == NULL ? -1 : 0;
  917. }
  918. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  919. {
  920. return CloseHandle(*mutex) == 0 ? -1 : 0;
  921. }
  922. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  923. {
  924. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  925. }
  926. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  927. {
  928. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  929. }
  930. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  931. {
  932. (void) unused;
  933. InitializeCriticalSection(&cv->threadIdSec);
  934. cv->waitingthreadcount = 0;
  935. cv->waitingthreadids = calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  936. return (cv->waitingthreadids!=NULL) ? 0 : -1;
  937. }
  938. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  939. {
  940. EnterCriticalSection(&cv->threadIdSec);
  941. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  942. cv->waitingthreadids[cv->waitingthreadcount] = OpenThread(THREAD_SUSPEND_RESUME, FALSE, GetCurrentThreadId());
  943. cv->waitingthreadcount++;
  944. LeaveCriticalSection(&cv->threadIdSec);
  945. pthread_mutex_unlock(mutex); /* if the thread is preempted here, ResumeThread will return 0 */
  946. SuspendThread(GetCurrentThread()); /* if the thread reached this point, ResumeThread will return 1 */
  947. pthread_mutex_lock(mutex);
  948. return 0;
  949. }
  950. static int pthread_cond_signal(pthread_cond_t *cv)
  951. {
  952. int i,j;
  953. DWORD susCnt;
  954. HANDLE wkup = NULL;
  955. EnterCriticalSection(&cv->threadIdSec);
  956. if (cv->waitingthreadcount) {
  957. for (;;) {
  958. for (j=0; j<cv->waitingthreadcount; j++) {
  959. wkup = cv->waitingthreadids[j];
  960. susCnt = ResumeThread(wkup);
  961. assert(susCnt<2);
  962. if (susCnt==1) {
  963. CloseHandle(wkup);
  964. for (i=1;i<cv->waitingthreadcount;i++) {
  965. cv->waitingthreadids[i-1] = cv->waitingthreadids[i];
  966. }
  967. cv->waitingthreadcount--;
  968. break;
  969. }
  970. }
  971. if (wkup) {
  972. break;
  973. } else {
  974. /* All theads between enqueue and suspend */
  975. Sleep(1);
  976. }
  977. }
  978. }
  979. LeaveCriticalSection(&cv->threadIdSec);
  980. return 0;
  981. }
  982. static int pthread_cond_broadcast(pthread_cond_t *cv)
  983. {
  984. EnterCriticalSection(&cv->threadIdSec);
  985. while (cv->waitingthreadcount) {
  986. pthread_cond_signal(cv);
  987. }
  988. LeaveCriticalSection(&cv->threadIdSec);
  989. return 0;
  990. }
  991. static int pthread_cond_destroy(pthread_cond_t *cv)
  992. {
  993. EnterCriticalSection(&cv->threadIdSec);
  994. assert(cv->waitingthreadcount==0);
  995. cv->waitingthreadids = 0;
  996. free(cv->waitingthreadids);
  997. LeaveCriticalSection(&cv->threadIdSec);
  998. DeleteCriticalSection(&cv->threadIdSec);
  999. return 0;
  1000. }
  1001. // For Windows, change all slashes to backslashes in path names.
  1002. static void change_slashes_to_backslashes(char *path)
  1003. {
  1004. int i;
  1005. for (i = 0; path[i] != '\0'; i++) {
  1006. if (path[i] == '/')
  1007. path[i] = '\\';
  1008. // i > 0 check is to preserve UNC paths, like \\server\file.txt
  1009. if (path[i] == '\\' && i > 0)
  1010. while (path[i + 1] == '\\' || path[i + 1] == '/')
  1011. (void) memmove(path + i + 1,
  1012. path + i + 2, strlen(path + i + 1));
  1013. }
  1014. }
  1015. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1016. // wbuf and wbuf_len is a target buffer and its length.
  1017. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  1018. {
  1019. char buf[PATH_MAX], buf2[PATH_MAX];
  1020. mg_strlcpy(buf, path, sizeof(buf));
  1021. change_slashes_to_backslashes(buf);
  1022. // Convert to Unicode and back. If doubly-converted string does not
  1023. // match the original, something is fishy, reject.
  1024. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1025. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1026. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1027. NULL, NULL);
  1028. if (strcmp(buf, buf2) != 0) {
  1029. wbuf[0] = L'\0';
  1030. }
  1031. }
  1032. #if defined(_WIN32_WCE)
  1033. static time_t time(time_t *ptime)
  1034. {
  1035. time_t t;
  1036. SYSTEMTIME st;
  1037. FILETIME ft;
  1038. GetSystemTime(&st);
  1039. SystemTimeToFileTime(&st, &ft);
  1040. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1041. if (ptime != NULL) {
  1042. *ptime = t;
  1043. }
  1044. return t;
  1045. }
  1046. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  1047. {
  1048. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  1049. FILETIME ft, lft;
  1050. SYSTEMTIME st;
  1051. TIME_ZONE_INFORMATION tzinfo;
  1052. if (ptm == NULL) {
  1053. return NULL;
  1054. }
  1055. * (int64_t *) &ft = t;
  1056. FileTimeToLocalFileTime(&ft, &lft);
  1057. FileTimeToSystemTime(&lft, &st);
  1058. ptm->tm_year = st.wYear - 1900;
  1059. ptm->tm_mon = st.wMonth - 1;
  1060. ptm->tm_wday = st.wDayOfWeek;
  1061. ptm->tm_mday = st.wDay;
  1062. ptm->tm_hour = st.wHour;
  1063. ptm->tm_min = st.wMinute;
  1064. ptm->tm_sec = st.wSecond;
  1065. ptm->tm_yday = 0; // hope nobody uses this
  1066. ptm->tm_isdst =
  1067. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1068. return ptm;
  1069. }
  1070. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  1071. {
  1072. // FIXME(lsm): fix this.
  1073. return localtime(ptime, ptm);
  1074. }
  1075. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1076. const struct tm *tm)
  1077. {
  1078. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  1079. return 0;
  1080. }
  1081. #endif
  1082. // Windows happily opens files with some garbage at the end of file name.
  1083. // For example, fopen("a.cgi ", "r") on Windows successfully opens
  1084. // "a.cgi", despite one would expect an error back.
  1085. // This function returns non-0 if path ends with some garbage.
  1086. static int path_cannot_disclose_cgi(const char *path)
  1087. {
  1088. static const char *allowed_last_characters = "_-";
  1089. int last = path[strlen(path) - 1];
  1090. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  1091. }
  1092. static int mg_stat(struct mg_connection *conn, const char *path,
  1093. struct file *filep)
  1094. {
  1095. wchar_t wbuf[PATH_MAX];
  1096. WIN32_FILE_ATTRIBUTE_DATA info;
  1097. if (!is_file_in_memory(conn, path, filep)) {
  1098. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1099. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1100. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1101. filep->modification_time = SYS2UNIX_TIME(
  1102. info.ftLastWriteTime.dwLowDateTime,
  1103. info.ftLastWriteTime.dwHighDateTime);
  1104. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1105. // If file name is fishy, reset the file structure and return error.
  1106. // Note it is important to reset, not just return the error, cause
  1107. // functions like is_file_opened() check the struct.
  1108. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  1109. memset(filep, 0, sizeof(*filep));
  1110. }
  1111. }
  1112. }
  1113. return filep->membuf != NULL || filep->modification_time != 0;
  1114. }
  1115. static int mg_remove(const char *path)
  1116. {
  1117. wchar_t wbuf[PATH_MAX];
  1118. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1119. return DeleteFileW(wbuf) ? 0 : -1;
  1120. }
  1121. static int mg_mkdir(const char *path, int mode)
  1122. {
  1123. char buf[PATH_MAX];
  1124. wchar_t wbuf[PATH_MAX];
  1125. (void) mode;
  1126. mg_strlcpy(buf, path, sizeof(buf));
  1127. change_slashes_to_backslashes(buf);
  1128. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  1129. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1130. }
  1131. // Implementation of POSIX opendir/closedir/readdir for Windows.
  1132. static DIR * opendir(const char *name)
  1133. {
  1134. DIR *dir = NULL;
  1135. wchar_t wpath[PATH_MAX];
  1136. DWORD attrs;
  1137. if (name == NULL) {
  1138. SetLastError(ERROR_BAD_ARGUMENTS);
  1139. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  1140. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1141. } else {
  1142. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1143. attrs = GetFileAttributesW(wpath);
  1144. if (attrs != 0xFFFFFFFF &&
  1145. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1146. (void) wcscat(wpath, L"\\*");
  1147. dir->handle = FindFirstFileW(wpath, &dir->info);
  1148. dir->result.d_name[0] = '\0';
  1149. } else {
  1150. free(dir);
  1151. dir = NULL;
  1152. }
  1153. }
  1154. return dir;
  1155. }
  1156. static int closedir(DIR *dir)
  1157. {
  1158. int result = 0;
  1159. if (dir != NULL) {
  1160. if (dir->handle != INVALID_HANDLE_VALUE)
  1161. result = FindClose(dir->handle) ? 0 : -1;
  1162. free(dir);
  1163. } else {
  1164. result = -1;
  1165. SetLastError(ERROR_BAD_ARGUMENTS);
  1166. }
  1167. return result;
  1168. }
  1169. static struct dirent *readdir(DIR *dir)
  1170. {
  1171. struct dirent *result = 0;
  1172. if (dir) {
  1173. if (dir->handle != INVALID_HANDLE_VALUE) {
  1174. result = &dir->result;
  1175. (void) WideCharToMultiByte(CP_UTF8, 0,
  1176. dir->info.cFileName, -1, result->d_name,
  1177. sizeof(result->d_name), NULL, NULL);
  1178. if (!FindNextFileW(dir->handle, &dir->info)) {
  1179. (void) FindClose(dir->handle);
  1180. dir->handle = INVALID_HANDLE_VALUE;
  1181. }
  1182. } else {
  1183. SetLastError(ERROR_FILE_NOT_FOUND);
  1184. }
  1185. } else {
  1186. SetLastError(ERROR_BAD_ARGUMENTS);
  1187. }
  1188. return result;
  1189. }
  1190. #ifndef HAVE_POLL
  1191. static int poll(struct pollfd *pfd, int n, int milliseconds)
  1192. {
  1193. struct timeval tv;
  1194. fd_set set;
  1195. int i, result;
  1196. SOCKET maxfd = 0;
  1197. tv.tv_sec = milliseconds / 1000;
  1198. tv.tv_usec = (milliseconds % 1000) * 1000;
  1199. FD_ZERO(&set);
  1200. for (i = 0; i < n; i++) {
  1201. FD_SET((SOCKET) pfd[i].fd, &set);
  1202. pfd[i].revents = 0;
  1203. if (pfd[i].fd > maxfd) {
  1204. maxfd = pfd[i].fd;
  1205. }
  1206. }
  1207. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  1208. for (i = 0; i < n; i++) {
  1209. if (FD_ISSET(pfd[i].fd, &set)) {
  1210. pfd[i].revents = POLLIN;
  1211. }
  1212. }
  1213. }
  1214. return result;
  1215. }
  1216. #endif // HAVE_POLL
  1217. static void set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  1218. {
  1219. (void) conn; /* Unused. */
  1220. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  1221. }
  1222. int mg_start_thread(mg_thread_func_t f, void *p)
  1223. {
  1224. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1225. // Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  1226. return (long)_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == -1L ? -1 : 0;
  1227. #else
  1228. return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1229. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1230. }
  1231. /* Start a thread storing the thread context. */
  1232. static int mg_start_thread_with_id(unsigned (__stdcall *f)(void *), void *p,
  1233. pthread_t *threadidptr)
  1234. {
  1235. uintptr_t uip;
  1236. HANDLE threadhandle;
  1237. int result;
  1238. uip = _beginthreadex(NULL, 0, (unsigned (__stdcall *)(void *)) f, p, 0,
  1239. NULL);
  1240. threadhandle = (HANDLE) uip;
  1241. if (threadidptr != NULL) {
  1242. *threadidptr = threadhandle;
  1243. }
  1244. result = (threadhandle == NULL) ? -1 : 0;
  1245. return result;
  1246. }
  1247. /* Wait for a thread to finish. */
  1248. static int mg_join_thread(pthread_t threadid)
  1249. {
  1250. int result;
  1251. DWORD dwevent;
  1252. result = -1;
  1253. dwevent = WaitForSingleObject(threadid, INFINITE);
  1254. if (dwevent == WAIT_FAILED) {
  1255. int err;
  1256. err = GetLastError();
  1257. DEBUG_TRACE(("WaitForSingleObject() failed, error %d", err));
  1258. } else {
  1259. if (dwevent == WAIT_OBJECT_0) {
  1260. CloseHandle(threadid);
  1261. result = 0;
  1262. }
  1263. }
  1264. return result;
  1265. }
  1266. static HANDLE dlopen(const char *dll_name, int flags)
  1267. {
  1268. wchar_t wbuf[PATH_MAX];
  1269. (void) flags;
  1270. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1271. return LoadLibraryW(wbuf);
  1272. }
  1273. static int dlclose(void *handle)
  1274. {
  1275. int result;
  1276. if (FreeLibrary(handle) != 0) {
  1277. result = 0;
  1278. } else {
  1279. result = -1;
  1280. }
  1281. return result;
  1282. }
  1283. #if !defined(NO_CGI)
  1284. #define SIGKILL 0
  1285. static int kill(pid_t pid, int sig_num)
  1286. {
  1287. (void) TerminateProcess(pid, sig_num);
  1288. (void) CloseHandle(pid);
  1289. return 0;
  1290. }
  1291. static void trim_trailing_whitespaces(char *s)
  1292. {
  1293. char *e = s + strlen(s) - 1;
  1294. while (e > s && isspace(* (unsigned char *) e)) {
  1295. *e-- = '\0';
  1296. }
  1297. }
  1298. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1299. char *envblk, char *envp[], int fdin,
  1300. int fdout, const char *dir)
  1301. {
  1302. HANDLE me;
  1303. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  1304. cmdline[PATH_MAX], buf[PATH_MAX];
  1305. struct file file = STRUCT_FILE_INITIALIZER;
  1306. STARTUPINFOA si;
  1307. PROCESS_INFORMATION pi = { 0 };
  1308. (void) envp;
  1309. memset(&si, 0, sizeof(si));
  1310. si.cb = sizeof(si);
  1311. // TODO(lsm): redirect CGI errors to the error log file
  1312. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1313. si.wShowWindow = SW_HIDE;
  1314. me = GetCurrentProcess();
  1315. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
  1316. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1317. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
  1318. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1319. // If CGI file is a script, try to read the interpreter line
  1320. interp = conn->ctx->config[CGI_INTERPRETER];
  1321. if (interp == NULL) {
  1322. buf[0] = buf[1] = '\0';
  1323. // Read the first line of the script into the buffer
  1324. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1325. if (mg_fopen(conn, cmdline, "r", &file)) {
  1326. p = (char *) file.membuf;
  1327. mg_fgets(buf, sizeof(buf), &file, &p);
  1328. mg_fclose(&file);
  1329. buf[sizeof(buf) - 1] = '\0';
  1330. }
  1331. if (buf[0] == '#' && buf[1] == '!') {
  1332. trim_trailing_whitespaces(buf + 2);
  1333. } else {
  1334. buf[2] = '\0';
  1335. }
  1336. interp = buf + 2;
  1337. }
  1338. if (interp[0] != '\0') {
  1339. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  1340. interp = full_interp;
  1341. }
  1342. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  1343. mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
  1344. interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
  1345. DEBUG_TRACE(("Running [%s]", cmdline));
  1346. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1347. CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
  1348. mg_cry(conn, "%s: CreateProcess(%s): %ld",
  1349. __func__, cmdline, ERRNO);
  1350. pi.hProcess = (pid_t) -1;
  1351. }
  1352. (void) CloseHandle(si.hStdOutput);
  1353. (void) CloseHandle(si.hStdInput);
  1354. if (pi.hThread != NULL)
  1355. (void) CloseHandle(pi.hThread);
  1356. return (pid_t) pi.hProcess;
  1357. }
  1358. #endif // !NO_CGI
  1359. static int set_non_blocking_mode(SOCKET sock)
  1360. {
  1361. unsigned long on = 1;
  1362. return ioctlsocket(sock, FIONBIO, &on);
  1363. }
  1364. #else
  1365. static int mg_stat(struct mg_connection *conn, const char *path,
  1366. struct file *filep)
  1367. {
  1368. struct stat st;
  1369. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  1370. filep->size = st.st_size;
  1371. filep->modification_time = st.st_mtime;
  1372. filep->is_directory = S_ISDIR(st.st_mode);
  1373. } else {
  1374. filep->modification_time = (time_t) 0;
  1375. }
  1376. return filep->membuf != NULL || filep->modification_time != (time_t) 0;
  1377. }
  1378. static void set_close_on_exec(int fd, struct mg_connection *conn /* may be null */)
  1379. {
  1380. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  1381. if (conn)
  1382. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  1383. __func__, strerror(ERRNO));
  1384. }
  1385. }
  1386. int mg_start_thread(mg_thread_func_t func, void *param)
  1387. {
  1388. pthread_t thread_id;
  1389. pthread_attr_t attr;
  1390. int result;
  1391. (void) pthread_attr_init(&attr);
  1392. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1393. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1394. // Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  1395. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1396. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  1397. result = pthread_create(&thread_id, &attr, func, param);
  1398. pthread_attr_destroy(&attr);
  1399. return result;
  1400. }
  1401. /* Start a thread storing the thread context. */
  1402. static int mg_start_thread_with_id(mg_thread_func_t func, void *param,
  1403. pthread_t *threadidptr)
  1404. {
  1405. pthread_t thread_id;
  1406. pthread_attr_t attr;
  1407. int result;
  1408. (void) pthread_attr_init(&attr);
  1409. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  1410. // Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  1411. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1412. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  1413. result = pthread_create(&thread_id, &attr, func, param);
  1414. pthread_attr_destroy(&attr);
  1415. if (threadidptr != NULL) {
  1416. *threadidptr = thread_id;
  1417. }
  1418. return result;
  1419. }
  1420. /* Wait for a thread to finish. */
  1421. static int mg_join_thread(pthread_t threadid)
  1422. {
  1423. int result;
  1424. result = pthread_join(threadid, NULL);
  1425. return result;
  1426. }
  1427. #ifndef NO_CGI
  1428. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1429. char *envblk, char *envp[], int fdin,
  1430. int fdout, const char *dir)
  1431. {
  1432. pid_t pid;
  1433. const char *interp;
  1434. (void) envblk;
  1435. if ((pid = fork()) == -1) {
  1436. // Parent
  1437. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1438. } else if (pid == 0) {
  1439. // Child
  1440. if (chdir(dir) != 0) {
  1441. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1442. } else if (dup2(fdin, 0) == -1) {
  1443. mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  1444. } else if (dup2(fdout, 1) == -1) {
  1445. mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  1446. } else {
  1447. // Not redirecting stderr to stdout, to avoid output being littered
  1448. // with the error messages.
  1449. (void) close(fdin);
  1450. (void) close(fdout);
  1451. // After exec, all signal handlers are restored to their default values,
  1452. // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  1453. // implementation, SIGCHLD's handler will leave unchanged after exec
  1454. // if it was set to be ignored. Restore it to default action.
  1455. signal(SIGCHLD, SIG_DFL);
  1456. interp = conn->ctx->config[CGI_INTERPRETER];
  1457. if (interp == NULL) {
  1458. (void) execle(prog, prog, NULL, envp);
  1459. mg_cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1460. } else {
  1461. (void) execle(interp, interp, prog, NULL, envp);
  1462. mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1463. strerror(ERRNO));
  1464. }
  1465. }
  1466. exit(EXIT_FAILURE);
  1467. }
  1468. return pid;
  1469. }
  1470. #endif // !NO_CGI
  1471. static int set_non_blocking_mode(SOCKET sock)
  1472. {
  1473. int flags;
  1474. flags = fcntl(sock, F_GETFL, 0);
  1475. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1476. return 0;
  1477. }
  1478. #endif // _WIN32
  1479. // Write data to the IO channel - opened file descriptor, socket or SSL
  1480. // descriptor. Return number of bytes written.
  1481. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1482. int64_t len)
  1483. {
  1484. int64_t sent;
  1485. int n, k;
  1486. (void) ssl; // Get rid of warning
  1487. sent = 0;
  1488. while (sent < len) {
  1489. // How many bytes we send in this iteration
  1490. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1491. #ifndef NO_SSL
  1492. if (ssl != NULL) {
  1493. n = SSL_write(ssl, buf + sent, k);
  1494. } else
  1495. #endif
  1496. if (fp != NULL) {
  1497. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1498. if (ferror(fp))
  1499. n = -1;
  1500. } else {
  1501. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1502. }
  1503. if (n <= 0)
  1504. break;
  1505. sent += n;
  1506. }
  1507. return sent;
  1508. }
  1509. // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1510. // Return negative value on error, or number of bytes read on success.
  1511. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1512. {
  1513. int nread;
  1514. if (fp != NULL) {
  1515. // Use read() instead of fread(), because if we're reading from the CGI
  1516. // pipe, fread() may block until IO buffer is filled up. We cannot afford
  1517. // to block and must pass all read bytes immediately to the client.
  1518. nread = read(fileno(fp), buf, (size_t) len);
  1519. #ifndef NO_SSL
  1520. } else if (conn->ssl != NULL) {
  1521. nread = SSL_read(conn->ssl, buf, len);
  1522. #endif
  1523. } else {
  1524. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1525. }
  1526. return conn->ctx->stop_flag ? -1 : nread;
  1527. }
  1528. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  1529. {
  1530. int n, nread = 0;
  1531. while (len > 0 && conn->ctx->stop_flag == 0) {
  1532. n = pull(fp, conn, buf + nread, len);
  1533. if (n < 0) {
  1534. nread = n; // Propagate the error
  1535. break;
  1536. } else if (n == 0) {
  1537. break; // No more data to read
  1538. } else {
  1539. conn->consumed_content += n;
  1540. nread += n;
  1541. len -= n;
  1542. }
  1543. }
  1544. return nread;
  1545. }
  1546. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  1547. {
  1548. int n, buffered_len, nread;
  1549. const char *body;
  1550. // If Content-Length is not set, read until socket is closed
  1551. if (conn->consumed_content == 0 && conn->content_len == 0) {
  1552. conn->content_len = INT64_MAX;
  1553. conn->must_close = 1;
  1554. }
  1555. nread = 0;
  1556. if (conn->consumed_content < conn->content_len) {
  1557. // Adjust number of bytes to read.
  1558. int64_t to_read = conn->content_len - conn->consumed_content;
  1559. if (to_read < (int64_t) len) {
  1560. len = (size_t) to_read;
  1561. }
  1562. // Return buffered data
  1563. body = conn->buf + conn->request_len + conn->consumed_content;
  1564. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  1565. if (buffered_len > 0) {
  1566. if (len < (size_t) buffered_len) {
  1567. buffered_len = (int) len;
  1568. }
  1569. memcpy(buf, body, (size_t) buffered_len);
  1570. len -= buffered_len;
  1571. conn->consumed_content += buffered_len;
  1572. nread += buffered_len;
  1573. buf = (char *) buf + buffered_len;
  1574. }
  1575. // We have returned all buffered data. Read new data from the remote socket.
  1576. n = pull_all(NULL, conn, (char *) buf, (int) len);
  1577. nread = n >= 0 ? nread + n : n;
  1578. }
  1579. return nread;
  1580. }
  1581. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  1582. {
  1583. time_t now;
  1584. int64_t n, total, allowed;
  1585. if (conn->throttle > 0) {
  1586. if ((now = time(NULL)) != conn->last_throttle_time) {
  1587. conn->last_throttle_time = now;
  1588. conn->last_throttle_bytes = 0;
  1589. }
  1590. allowed = conn->throttle - conn->last_throttle_bytes;
  1591. if (allowed > (int64_t) len) {
  1592. allowed = len;
  1593. }
  1594. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1595. (int64_t) allowed)) == allowed) {
  1596. buf = (char *) buf + total;
  1597. conn->last_throttle_bytes += total;
  1598. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1599. allowed = conn->throttle > (int64_t) len - total ?
  1600. (int64_t) len - total : conn->throttle;
  1601. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1602. (int64_t) allowed)) != allowed) {
  1603. break;
  1604. }
  1605. sleep(1);
  1606. conn->last_throttle_bytes = allowed;
  1607. conn->last_throttle_time = time(NULL);
  1608. buf = (char *) buf + n;
  1609. total += n;
  1610. }
  1611. }
  1612. } else {
  1613. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1614. (int64_t) len);
  1615. }
  1616. return (int) total;
  1617. }
  1618. // Alternative alloc_vprintf() for non-compliant C runtimes
  1619. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  1620. {
  1621. va_list ap_copy;
  1622. int size = MG_BUF_LEN;
  1623. int len = -1;
  1624. *buf = NULL;
  1625. while (len == -1) {
  1626. if (*buf) free(*buf);
  1627. *buf = (char *)malloc(size *= 4);
  1628. if (!*buf) break;
  1629. va_copy(ap_copy, ap);
  1630. len = vsnprintf(*buf, size, fmt, ap_copy);
  1631. va_end(ap_copy);
  1632. }
  1633. return len;
  1634. }
  1635. // Print message to buffer. If buffer is large enough to hold the message,
  1636. // return buffer. If buffer is to small, allocate large enough buffer on heap,
  1637. // and return allocated buffer.
  1638. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  1639. {
  1640. va_list ap_copy;
  1641. int len;
  1642. // Windows is not standard-compliant, and vsnprintf() returns -1 if
  1643. // buffer is too small. Also, older versions of msvcrt.dll do not have
  1644. // _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  1645. // Therefore, we make two passes: on first pass, get required message length.
  1646. // On second pass, actually print the message.
  1647. va_copy(ap_copy, ap);
  1648. len = vsnprintf(NULL, 0, fmt, ap_copy);
  1649. va_end(ap_copy);
  1650. if (len < 0) {
  1651. // C runtime is not standard compliant, vsnprintf() returned -1.
  1652. // Switch to alternative code path that uses incremental allocations.
  1653. va_copy(ap_copy, ap);
  1654. len = alloc_vprintf2(buf, fmt, ap);
  1655. va_end(ap_copy);
  1656. } else if (len > (int) size &&
  1657. (size = len + 1) > 0 &&
  1658. (*buf = (char *) malloc(size)) == NULL) {
  1659. len = -1; // Allocation failed, mark failure
  1660. } else {
  1661. va_copy(ap_copy, ap);
  1662. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  1663. va_end(ap_copy);
  1664. }
  1665. return len;
  1666. }
  1667. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap);
  1668. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  1669. {
  1670. char mem[MG_BUF_LEN], *buf = mem;
  1671. int len;
  1672. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  1673. len = mg_write(conn, buf, (size_t) len);
  1674. }
  1675. if (buf != mem && buf != NULL) {
  1676. free(buf);
  1677. }
  1678. return len;
  1679. }
  1680. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  1681. {
  1682. va_list ap;
  1683. int result;
  1684. va_start(ap, fmt);
  1685. result = mg_vprintf(conn, fmt, ap);
  1686. va_end(ap);
  1687. return result;
  1688. }
  1689. int mg_url_decode(const char *src, int src_len, char *dst,
  1690. int dst_len, int is_form_url_encoded)
  1691. {
  1692. int i, j, a, b;
  1693. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1694. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1695. if (src[i] == '%' && i < src_len - 2 &&
  1696. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1697. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1698. a = tolower(* (const unsigned char *) (src + i + 1));
  1699. b = tolower(* (const unsigned char *) (src + i + 2));
  1700. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1701. i += 2;
  1702. } else if (is_form_url_encoded && src[i] == '+') {
  1703. dst[j] = ' ';
  1704. } else {
  1705. dst[j] = src[i];
  1706. }
  1707. }
  1708. dst[j] = '\0'; // Null-terminate the destination
  1709. return i >= src_len ? j : -1;
  1710. }
  1711. int mg_get_var(const char *data, size_t data_len, const char *name,
  1712. char *dst, size_t dst_len)
  1713. {
  1714. return mg_get_var2(data,data_len,name,dst,dst_len,0);
  1715. }
  1716. int mg_get_var2(const char *data, size_t data_len, const char *name,
  1717. char *dst, size_t dst_len, size_t occurrence)
  1718. {
  1719. const char *p, *e, *s;
  1720. size_t name_len;
  1721. int len;
  1722. if (dst == NULL || dst_len == 0) {
  1723. len = -2;
  1724. } else if (data == NULL || name == NULL || data_len == 0) {
  1725. len = -1;
  1726. dst[0] = '\0';
  1727. } else {
  1728. name_len = strlen(name);
  1729. e = data + data_len;
  1730. len = -1;
  1731. dst[0] = '\0';
  1732. // data is "var1=val1&var2=val2...". Find variable first
  1733. for (p = data; p + name_len < e; p++) {
  1734. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  1735. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  1736. // Point p to variable value
  1737. p += name_len + 1;
  1738. // Point s to the end of the value
  1739. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1740. if (s == NULL) {
  1741. s = e;
  1742. }
  1743. assert(s >= p);
  1744. // Decode variable into destination buffer
  1745. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  1746. // Redirect error code from -1 to -2 (destination buffer too small).
  1747. if (len == -1) {
  1748. len = -2;
  1749. }
  1750. break;
  1751. }
  1752. }
  1753. }
  1754. return len;
  1755. }
  1756. int mg_get_cookie(const char *cookie_header, const char *var_name,
  1757. char *dst, size_t dst_size)
  1758. {
  1759. const char *s, *p, *end;
  1760. int name_len, len = -1;
  1761. if (dst == NULL || dst_size == 0) {
  1762. len = -2;
  1763. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  1764. len = -1;
  1765. dst[0] = '\0';
  1766. } else {
  1767. name_len = (int) strlen(var_name);
  1768. end = s + strlen(s);
  1769. dst[0] = '\0';
  1770. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  1771. if (s[name_len] == '=') {
  1772. s += name_len + 1;
  1773. if ((p = strchr(s, ' ')) == NULL)
  1774. p = end;
  1775. if (p[-1] == ';')
  1776. p--;
  1777. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1778. s++;
  1779. p--;
  1780. }
  1781. if ((size_t) (p - s) < dst_size) {
  1782. len = (int)(p - s);
  1783. mg_strlcpy(dst, s, (size_t) len + 1);
  1784. } else {
  1785. len = -3;
  1786. }
  1787. break;
  1788. }
  1789. }
  1790. }
  1791. return len;
  1792. }
  1793. static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1794. size_t buf_len, struct file *filep)
  1795. {
  1796. struct vec a, b;
  1797. const char *rewrite, *uri = conn->request_info.uri,
  1798. *root = conn->ctx->config[DOCUMENT_ROOT];
  1799. char *p;
  1800. int match_len;
  1801. char gz_path[PATH_MAX];
  1802. char const* accept_encoding;
  1803. // Using buf_len - 1 because memmove() for PATH_INFO may shift part
  1804. // of the path one byte on the right.
  1805. // If document_root is NULL, leave the file empty.
  1806. mg_snprintf(conn, buf, buf_len - 1, "%s%s",
  1807. root == NULL ? "" : root,
  1808. root == NULL ? "" : uri);
  1809. rewrite = conn->ctx->config[REWRITE];
  1810. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1811. if ((match_len = match_prefix(a.ptr, (int) a.len, uri)) > 0) {
  1812. mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
  1813. uri + match_len);
  1814. break;
  1815. }
  1816. }
  1817. if (mg_stat(conn, buf, filep)) return;
  1818. // if we can't find the actual file, look for the file
  1819. // with the same name but a .gz extension. If we find it,
  1820. // use that and set the gzipped flag in the file struct
  1821. // to indicate that the response need to have the content-
  1822. // encoding: gzip header
  1823. // we can only do this if the browser declares support
  1824. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  1825. if (strstr(accept_encoding,"gzip") != NULL) {
  1826. snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
  1827. if (mg_stat(conn, gz_path, filep)) {
  1828. filep->gzipped = 1;
  1829. return;
  1830. }
  1831. }
  1832. }
  1833. // Support PATH_INFO for CGI scripts.
  1834. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1835. if (*p == '/') {
  1836. *p = '\0';
  1837. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1838. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1839. mg_stat(conn, buf, filep)) {
  1840. // Shift PATH_INFO block one character right, e.g.
  1841. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1842. // conn->path_info is pointing to the local variable "path" declared
  1843. // in handle_request(), so PATH_INFO is not valid after
  1844. // handle_request returns.
  1845. conn->path_info = p + 1;
  1846. memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0
  1847. p[1] = '/';
  1848. break;
  1849. } else {
  1850. *p = '/';
  1851. }
  1852. }
  1853. }
  1854. }
  1855. // Check whether full request is buffered. Return:
  1856. // -1 if request is malformed
  1857. // 0 if request is not yet fully buffered
  1858. // >0 actual request length, including last \r\n\r\n
  1859. static int get_request_len(const char *buf, int buflen)
  1860. {
  1861. const char *s, *e;
  1862. int len = 0;
  1863. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1864. // Control characters are not allowed but >=128 is.
  1865. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1866. *s != '\n' && * (const unsigned char *) s < 128) {
  1867. len = -1;
  1868. break; // [i_a] abort scan as soon as one malformed character is found;
  1869. // don't let subsequent \r\n\r\n win us over anyhow
  1870. } else if (s[0] == '\n' && s[1] == '\n') {
  1871. len = (int) (s - buf) + 2;
  1872. } else if (s[0] == '\n' && &s[1] < e &&
  1873. s[1] == '\r' && s[2] == '\n') {
  1874. len = (int) (s - buf) + 3;
  1875. }
  1876. return len;
  1877. }
  1878. // Convert month to the month number. Return -1 on error, or month number
  1879. static int get_month_index(const char *s)
  1880. {
  1881. size_t i;
  1882. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1883. if (!strcmp(s, month_names[i]))
  1884. return (int) i;
  1885. return -1;
  1886. }
  1887. static int num_leap_years(int year)
  1888. {
  1889. return year / 4 - year / 100 + year / 400;
  1890. }
  1891. // Parse UTC date-time string, and return the corresponding time_t value.
  1892. static time_t parse_date_string(const char *datetime)
  1893. {
  1894. static const unsigned short days_before_month[] = {
  1895. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1896. };
  1897. char month_str[32];
  1898. int second, minute, hour, day, month, year, leap_days, days;
  1899. time_t result = (time_t) 0;
  1900. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1901. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1902. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1903. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1904. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1905. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1906. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1907. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1908. year > 1970 &&
  1909. (month = get_month_index(month_str)) != -1) {
  1910. leap_days = num_leap_years(year) - num_leap_years(1970);
  1911. year -= 1970;
  1912. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1913. result = (time_t) days * 24 * 3600 + (time_t) hour * 3600 +
  1914. minute * 60 + second;
  1915. }
  1916. return result;
  1917. }
  1918. // Protect against directory disclosure attack by removing '..',
  1919. // excessive '/' and '\' characters
  1920. static void remove_double_dots_and_double_slashes(char *s)
  1921. {
  1922. char *p = s;
  1923. while (*s != '\0') {
  1924. *p++ = *s++;
  1925. if (s[-1] == '/' || s[-1] == '\\') {
  1926. // Skip all following slashes, backslashes and double-dots
  1927. while (s[0] != '\0') {
  1928. if (s[0] == '/' || s[0] == '\\') {
  1929. s++;
  1930. } else if (s[0] == '.' && s[1] == '.') {
  1931. s += 2;
  1932. } else {
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. }
  1938. *p = '\0';
  1939. }
  1940. static const struct {
  1941. const char *extension;
  1942. size_t ext_len;
  1943. const char *mime_type;
  1944. } builtin_mime_types[] = {
  1945. // IANA registered MIME types (http://www.iana.org/assignments/media-types)
  1946. // application types
  1947. {".doc", 4, "application/msword"},
  1948. {".eps", 4, "application/postscript"},
  1949. {".exe", 4, "application/octet-stream"},
  1950. {".js", 3, "application/javascript"},
  1951. {".json", 5, "application/json"},
  1952. {".pdf", 4, "application/pdf"},
  1953. {".ps", 3, "application/postscript"},
  1954. {".rtf", 4, "application/rtf"},
  1955. {".xhtml", 6, "application/xhtml+xml"},
  1956. {".xsl", 4, "application/xml"},
  1957. {".xslt", 5, "application/xml"},
  1958. // audio
  1959. {".mp3", 4, "audio/mpeg"},
  1960. {".oga", 4, "audio/ogg"},
  1961. {".ogg", 4, "audio/ogg"},
  1962. // image
  1963. {".gif", 4, "image/gif"},
  1964. {".ief", 4, "image/ief"},
  1965. {".jpeg", 5, "image/jpeg"},
  1966. {".jpg", 4, "image/jpeg"},
  1967. {".jpm", 4, "image/jpm"},
  1968. {".jpx", 4, "image/jpx"},
  1969. {".png", 4, "image/png"},
  1970. {".svg", 4, "image/svg+xml"},
  1971. {".tif", 4, "image/tiff"},
  1972. {".tiff", 5, "image/tiff"},
  1973. // model
  1974. {".wrl", 4, "model/vrml"},
  1975. // text
  1976. {".css", 4, "text/css"},
  1977. {".csv", 4, "text/csv"},
  1978. {".htm", 4, "text/html"},
  1979. {".html", 5, "text/html"},
  1980. {".sgm", 4, "text/sgml"},
  1981. {".shtm", 5, "text/html"},
  1982. {".shtml", 6, "text/html"},
  1983. {".txt", 4, "text/plain"},
  1984. {".xml", 4, "text/xml"},
  1985. // video
  1986. {".mov", 4, "video/quicktime"},
  1987. {".mp4", 4, "video/mp4"},
  1988. {".mpeg", 5, "video/mpeg"},
  1989. {".mpg", 4, "video/mpeg"},
  1990. {".ogv", 4, "video/ogg"},
  1991. {".qt", 3, "video/quicktime"},
  1992. // not registered types (http://reference.sitepoint.com/html/mime-types-full, http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..)
  1993. {".arj", 4, "application/x-arj-compressed"},
  1994. {".gz", 3, "application/x-gunzip"},
  1995. {".rar", 4, "application/x-arj-compressed"},
  1996. {".swf", 4, "application/x-shockwave-flash"},
  1997. {".tar", 4, "application/x-tar"},
  1998. {".tgz", 4, "application/x-tar-gz"},
  1999. {".torrent", 8, "application/x-bittorrent"},
  2000. {".ppt", 4, "application/x-mspowerpoint"},
  2001. {".xls", 4, "application/x-msexcel"},
  2002. {".zip", 4, "application/x-zip-compressed"},
  2003. {".aac", 4, "audio/aac"}, // http://en.wikipedia.org/wiki/Advanced_Audio_Coding
  2004. {".aif", 4, "audio/x-aif"},
  2005. {".m3u", 4, "audio/x-mpegurl"},
  2006. {".mid", 4, "audio/x-midi"},
  2007. {".ra", 3, "audio/x-pn-realaudio"},
  2008. {".ram", 4, "audio/x-pn-realaudio"},
  2009. {".wav", 4, "audio/x-wav"},
  2010. {".bmp", 4, "image/bmp"},
  2011. {".ico", 4, "image/x-icon"},
  2012. {".pct", 4, "image/x-pct"},
  2013. {".pict", 5, "image/pict"},
  2014. {".rgb", 4, "image/x-rgb"},
  2015. {".webm", 5, "video/webm"}, // http://en.wikipedia.org/wiki/WebM
  2016. {".asf", 4, "video/x-ms-asf"},
  2017. {".avi", 4, "video/x-msvideo"},
  2018. {".m4v", 4, "video/x-m4v"},
  2019. {NULL, 0, NULL}
  2020. };
  2021. const char *mg_get_builtin_mime_type(const char *path)
  2022. {
  2023. const char *ext;
  2024. size_t i, path_len;
  2025. path_len = strlen(path);
  2026. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  2027. ext = path + (path_len - builtin_mime_types[i].ext_len);
  2028. if (path_len > builtin_mime_types[i].ext_len &&
  2029. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  2030. return builtin_mime_types[i].mime_type;
  2031. }
  2032. }
  2033. return "text/plain";
  2034. }
  2035. // Look at the "path" extension and figure what mime type it has.
  2036. // Store mime type in the vector.
  2037. static void get_mime_type(struct mg_context *ctx, const char *path,
  2038. struct vec *vec)
  2039. {
  2040. struct vec ext_vec, mime_vec;
  2041. const char *list, *ext;
  2042. size_t path_len;
  2043. path_len = strlen(path);
  2044. // Scan user-defined mime types first, in case user wants to
  2045. // override default mime types.
  2046. list = ctx->config[EXTRA_MIME_TYPES];
  2047. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  2048. // ext now points to the path suffix
  2049. ext = path + path_len - ext_vec.len;
  2050. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  2051. *vec = mime_vec;
  2052. return;
  2053. }
  2054. }
  2055. vec->ptr = mg_get_builtin_mime_type(path);
  2056. vec->len = strlen(vec->ptr);
  2057. }
  2058. // Stringify binary data. Output buffer must be twice as big as input,
  2059. // because each byte takes 2 bytes in string representation
  2060. static void bin2str(char *to, const unsigned char *p, size_t len)
  2061. {
  2062. static const char *hex = "0123456789abcdef";
  2063. for (; len--; p++) {
  2064. *to++ = hex[p[0] >> 4];
  2065. *to++ = hex[p[0] & 0x0f];
  2066. }
  2067. *to = '\0';
  2068. }
  2069. // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  2070. char *mg_md5(char buf[33], ...)
  2071. {
  2072. md5_byte_t hash[16];
  2073. const char *p;
  2074. va_list ap;
  2075. md5_state_t ctx;
  2076. md5_init(&ctx);
  2077. va_start(ap, buf);
  2078. while ((p = va_arg(ap, const char *)) != NULL) {
  2079. md5_append(&ctx, (const md5_byte_t *) p, (int) strlen(p));
  2080. }
  2081. va_end(ap);
  2082. md5_finish(&ctx, hash);
  2083. bin2str(buf, hash, sizeof(hash));
  2084. return buf;
  2085. }
  2086. // Check the user's password, return 1 if OK
  2087. static int check_password(const char *method, const char *ha1, const char *uri,
  2088. const char *nonce, const char *nc, const char *cnonce,
  2089. const char *qop, const char *response)
  2090. {
  2091. char ha2[32 + 1], expected_response[32 + 1];
  2092. // Some of the parameters may be NULL
  2093. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  2094. qop == NULL || response == NULL) {
  2095. return 0;
  2096. }
  2097. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  2098. // TODO(lsm): check for authentication timeout
  2099. if (// strcmp(dig->uri, c->ouri) != 0 ||
  2100. strlen(response) != 32
  2101. // || now - strtoul(dig->nonce, NULL, 10) > 3600
  2102. ) {
  2103. return 0;
  2104. }
  2105. mg_md5(ha2, method, ":", uri, NULL);
  2106. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  2107. ":", cnonce, ":", qop, ":", ha2, NULL);
  2108. return mg_strcasecmp(response, expected_response) == 0;
  2109. }
  2110. // Use the global passwords file, if specified by auth_gpass option,
  2111. // or search for .htpasswd in the requested directory.
  2112. static void open_auth_file(struct mg_connection *conn, const char *path,
  2113. struct file *filep)
  2114. {
  2115. char name[PATH_MAX];
  2116. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  2117. struct file file = STRUCT_FILE_INITIALIZER;
  2118. if (gpass != NULL) {
  2119. // Use global passwords file
  2120. if (!mg_fopen(conn, gpass, "r", filep)) {
  2121. #ifdef DEBUG
  2122. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  2123. #endif
  2124. }
  2125. // Important: using local struct file to test path for is_directory flag.
  2126. // If filep is used, mg_stat() makes it appear as if auth file was opened.
  2127. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  2128. mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  2129. path, '/', PASSWORDS_FILE_NAME);
  2130. if (!mg_fopen(conn, name, "r", filep)) {
  2131. #ifdef DEBUG
  2132. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2133. #endif
  2134. }
  2135. } else {
  2136. // Try to find .htpasswd in requested directory.
  2137. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  2138. if (e[0] == '/')
  2139. break;
  2140. mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  2141. (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
  2142. if (!mg_fopen(conn, name, "r", filep)) {
  2143. #ifdef DEBUG
  2144. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  2145. #endif
  2146. }
  2147. }
  2148. }
  2149. // Parsed Authorization header
  2150. struct ah {
  2151. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  2152. };
  2153. // Return 1 on success. Always initializes the ah structure.
  2154. static int parse_auth_header(struct mg_connection *conn, char *buf,
  2155. size_t buf_size, struct ah *ah)
  2156. {
  2157. char *name, *value, *s;
  2158. const char *auth_header;
  2159. (void) memset(ah, 0, sizeof(*ah));
  2160. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  2161. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  2162. return 0;
  2163. }
  2164. // Make modifiable copy of the auth header
  2165. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  2166. s = buf;
  2167. // Parse authorization header
  2168. for (;;) {
  2169. // Gobble initial spaces
  2170. while (isspace(* (unsigned char *) s)) {
  2171. s++;
  2172. }
  2173. name = skip_quoted(&s, "=", " ", 0);
  2174. // Value is either quote-delimited, or ends at first comma or space.
  2175. if (s[0] == '\"') {
  2176. s++;
  2177. value = skip_quoted(&s, "\"", " ", '\\');
  2178. if (s[0] == ',') {
  2179. s++;
  2180. }
  2181. } else {
  2182. value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
  2183. }
  2184. if (*name == '\0') {
  2185. break;
  2186. }
  2187. if (!strcmp(name, "username")) {
  2188. ah->user = value;
  2189. } else if (!strcmp(name, "cnonce")) {
  2190. ah->cnonce = value;
  2191. } else if (!strcmp(name, "response")) {
  2192. ah->response = value;
  2193. } else if (!strcmp(name, "uri")) {
  2194. ah->uri = value;
  2195. } else if (!strcmp(name, "qop")) {
  2196. ah->qop = value;
  2197. } else if (!strcmp(name, "nc")) {
  2198. ah->nc = value;
  2199. } else if (!strcmp(name, "nonce")) {
  2200. ah->nonce = value;
  2201. }
  2202. }
  2203. // CGI needs it as REMOTE_USER
  2204. if (ah->user != NULL) {
  2205. conn->request_info.remote_user = mg_strdup(ah->user);
  2206. } else {
  2207. return 0;
  2208. }
  2209. return 1;
  2210. }
  2211. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  2212. {
  2213. char *eof;
  2214. size_t len;
  2215. char *memend;
  2216. if (filep->membuf != NULL && *p != NULL) {
  2217. memend = (char *) &filep->membuf[filep->size];
  2218. eof = (char *) memchr(*p, '\n', memend - *p); // Search for \n from p till the end of stream
  2219. if (eof != NULL) {
  2220. eof += 1; // Include \n
  2221. } else {
  2222. eof = memend; // Copy remaining data
  2223. }
  2224. len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
  2225. memcpy(buf, *p, len);
  2226. buf[len] = '\0';
  2227. *p += len;
  2228. return len ? eof : NULL;
  2229. } else if (filep->fp != NULL) {
  2230. return fgets(buf, (int)size, filep->fp);
  2231. } else {
  2232. return NULL;
  2233. }
  2234. }
  2235. // Authorize against the opened passwords file. Return 1 if authorized.
  2236. static int authorize(struct mg_connection *conn, struct file *filep)
  2237. {
  2238. struct ah ah;
  2239. char line[256], f_user[256] = "", ha1[256] = "", f_domain[256] = "", buf[MG_BUF_LEN], *p;
  2240. if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
  2241. return 0;
  2242. }
  2243. // Loop over passwords file
  2244. p = (char *) filep->membuf;
  2245. while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
  2246. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  2247. continue;
  2248. }
  2249. if (!strcmp(ah.user, f_user) &&
  2250. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
  2251. return check_password(conn->request_info.request_method, ha1, ah.uri,
  2252. ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
  2253. }
  2254. return 0;
  2255. }
  2256. // Return 1 if request is authorised, 0 otherwise.
  2257. static int check_authorization(struct mg_connection *conn, const char *path)
  2258. {
  2259. char fname[PATH_MAX];
  2260. struct vec uri_vec, filename_vec;
  2261. const char *list;
  2262. struct file file = STRUCT_FILE_INITIALIZER;
  2263. int authorized = 1;
  2264. list = conn->ctx->config[PROTECT_URI];
  2265. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2266. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2267. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2268. (int) filename_vec.len, filename_vec.ptr);
  2269. if (!mg_fopen(conn, fname, "r", &file)) {
  2270. mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2271. }
  2272. break;
  2273. }
  2274. }
  2275. if (!is_file_opened(&file)) {
  2276. open_auth_file(conn, path, &file);
  2277. }
  2278. if (is_file_opened(&file)) {
  2279. authorized = authorize(conn, &file);
  2280. mg_fclose(&file);
  2281. }
  2282. return authorized;
  2283. }
  2284. static void send_authorization_request(struct mg_connection *conn)
  2285. {
  2286. conn->status_code = 401;
  2287. mg_printf(conn,
  2288. "HTTP/1.1 401 Unauthorized\r\n"
  2289. "Content-Length: 0\r\n"
  2290. "WWW-Authenticate: Digest qop=\"auth\", "
  2291. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2292. conn->ctx->config[AUTHENTICATION_DOMAIN],
  2293. (unsigned long) time(NULL));
  2294. }
  2295. static int is_authorized_for_put(struct mg_connection *conn)
  2296. {
  2297. struct file file = STRUCT_FILE_INITIALIZER;
  2298. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  2299. int ret = 0;
  2300. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  2301. ret = authorize(conn, &file);
  2302. mg_fclose(&file);
  2303. }
  2304. return ret;
  2305. }
  2306. int mg_modify_passwords_file(const char *fname, const char *domain,
  2307. const char *user, const char *pass)
  2308. {
  2309. int found;
  2310. char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+1];
  2311. FILE *fp, *fp2;
  2312. found = 0;
  2313. fp = fp2 = NULL;
  2314. // Regard empty password as no password - remove user record.
  2315. if (pass != NULL && pass[0] == '\0') {
  2316. pass = NULL;
  2317. }
  2318. (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  2319. tmp[sizeof(tmp) - 1] = 0;
  2320. // Create the file if does not exist
  2321. if ((fp = fopen(fname, "a+")) != NULL) {
  2322. (void) fclose(fp);
  2323. }
  2324. // Open the given file and temporary file
  2325. if ((fp = fopen(fname, "r")) == NULL) {
  2326. return 0;
  2327. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  2328. fclose(fp);
  2329. return 0;
  2330. }
  2331. // Copy the stuff to temporary file
  2332. while (fgets(line, sizeof(line), fp) != NULL) {
  2333. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2334. continue;
  2335. }
  2336. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2337. found++;
  2338. if (pass != NULL) {
  2339. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2340. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2341. }
  2342. } else {
  2343. fprintf(fp2, "%s", line);
  2344. }
  2345. }
  2346. // If new user, just add it
  2347. if (!found && pass != NULL) {
  2348. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2349. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2350. }
  2351. // Close files
  2352. fclose(fp);
  2353. fclose(fp2);
  2354. // Put the temp file in place of real file
  2355. IGNORE_UNUSED_RESULT(remove(fname));
  2356. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  2357. return 1;
  2358. }
  2359. static SOCKET conn2(struct mg_context *ctx /* may be null */, const char *host, int port,
  2360. int use_ssl, char *ebuf, size_t ebuf_len)
  2361. {
  2362. struct sockaddr_in sain;
  2363. struct hostent *he;
  2364. SOCKET sock = INVALID_SOCKET;
  2365. if (host == NULL) {
  2366. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  2367. } else if (use_ssl && SSLv23_client_method == NULL) {
  2368. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  2369. // TODO(lsm): use something threadsafe instead of gethostbyname()
  2370. } else if ((he = gethostbyname(host)) == NULL) {
  2371. snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
  2372. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  2373. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  2374. } else {
  2375. set_close_on_exec(sock, fc(ctx));
  2376. memset(&sain, '\0', sizeof(sain));
  2377. sain.sin_family = AF_INET;
  2378. sain.sin_port = htons((uint16_t) port);
  2379. sain.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  2380. if (connect(sock, (struct sockaddr *) &sain, sizeof(sain)) != 0) {
  2381. snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
  2382. host, port, strerror(ERRNO));
  2383. closesocket(sock);
  2384. sock = INVALID_SOCKET;
  2385. }
  2386. }
  2387. return sock;
  2388. }
  2389. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  2390. {
  2391. static const char *dont_escape = "._-$,;~()";
  2392. static const char *hex = "0123456789abcdef";
  2393. char *pos = dst;
  2394. const char *end = dst + dst_len - 1;
  2395. for (; *src != '\0' && pos < end; src++, pos++) {
  2396. if (isalnum(*(const unsigned char *) src) ||
  2397. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2398. *pos = *src;
  2399. } else if (pos + 2 < end) {
  2400. pos[0] = '%';
  2401. pos[1] = hex[(* (const unsigned char *) src) >> 4];
  2402. pos[2] = hex[(* (const unsigned char *) src) & 0xf];
  2403. pos += 2;
  2404. } else {
  2405. return -1;
  2406. }
  2407. }
  2408. *pos = '\0';
  2409. return (*src == '\0') ? (int)(pos - dst) : -1;
  2410. }
  2411. static void print_dir_entry(struct de *de)
  2412. {
  2413. char size[64], mod[64], href[PATH_MAX];
  2414. struct tm *tm;
  2415. if (de->file.is_directory) {
  2416. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2417. } else {
  2418. // We use (signed) cast below because MSVC 6 compiler cannot
  2419. // convert unsigned __int64 to double. Sigh.
  2420. if (de->file.size < 1024) {
  2421. mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
  2422. } else if (de->file.size < 0x100000) {
  2423. mg_snprintf(de->conn, size, sizeof(size),
  2424. "%.1fk", (double) de->file.size / 1024.0);
  2425. } else if (de->file.size < 0x40000000) {
  2426. mg_snprintf(de->conn, size, sizeof(size),
  2427. "%.1fM", (double) de->file.size / 1048576);
  2428. } else {
  2429. mg_snprintf(de->conn, size, sizeof(size),
  2430. "%.1fG", (double) de->file.size / 1073741824);
  2431. }
  2432. }
  2433. tm = localtime(&de->file.modification_time);
  2434. if (tm != NULL) {
  2435. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  2436. } else {
  2437. strncpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  2438. mod[sizeof(mod) - 1] = '\0';
  2439. }
  2440. mg_url_encode(de->file_name, href, sizeof(href));
  2441. de->conn->num_bytes_sent += mg_printf(de->conn,
  2442. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2443. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2444. de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
  2445. de->file_name, de->file.is_directory ? "/" : "", mod, size);
  2446. }
  2447. // This function is called from send_directory() and used for
  2448. // sorting directory entries by size, or name, or modification time.
  2449. // On windows, __cdecl specification is needed in case if project is built
  2450. // with __stdcall convention. qsort always requires __cdels callback.
  2451. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  2452. {
  2453. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2454. const char *query_string = a->conn->request_info.query_string;
  2455. int cmp_result = 0;
  2456. if (query_string == NULL) {
  2457. query_string = "na";
  2458. }
  2459. if (a->file.is_directory && !b->file.is_directory) {
  2460. return -1; // Always put directories on top
  2461. } else if (!a->file.is_directory && b->file.is_directory) {
  2462. return 1; // Always put directories on top
  2463. } else if (*query_string == 'n') {
  2464. cmp_result = strcmp(a->file_name, b->file_name);
  2465. } else if (*query_string == 's') {
  2466. cmp_result = a->file.size == b->file.size ? 0 :
  2467. a->file.size > b->file.size ? 1 : -1;
  2468. } else if (*query_string == 'd') {
  2469. cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
  2470. a->file.modification_time > b->file.modification_time ? 1 : -1;
  2471. }
  2472. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2473. }
  2474. static int must_hide_file(struct mg_connection *conn, const char *path)
  2475. {
  2476. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2477. const char *pattern = conn->ctx->config[HIDE_FILES];
  2478. return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
  2479. (pattern != NULL && match_prefix(pattern, (int)strlen(pattern), path) > 0);
  2480. }
  2481. static int scan_directory(struct mg_connection *conn, const char *dir,
  2482. void *data, void (*cb)(struct de *, void *))
  2483. {
  2484. char path[PATH_MAX];
  2485. struct dirent *dp;
  2486. DIR *dirp;
  2487. struct de de;
  2488. if ((dirp = opendir(dir)) == NULL) {
  2489. return 0;
  2490. } else {
  2491. de.conn = conn;
  2492. while ((dp = readdir(dirp)) != NULL) {
  2493. // Do not show current dir and hidden files
  2494. if (!strcmp(dp->d_name, ".") ||
  2495. !strcmp(dp->d_name, "..") ||
  2496. must_hide_file(conn, dp->d_name)) {
  2497. continue;
  2498. }
  2499. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2500. // If we don't memset stat structure to zero, mtime will have
  2501. // garbage and strftime() will segfault later on in
  2502. // print_dir_entry(). memset is required only if mg_stat()
  2503. // fails. For more details, see
  2504. // http://code.google.com/p/mongoose/issues/detail?id=79
  2505. memset(&de.file, 0, sizeof(de.file));
  2506. if (!mg_stat(conn, path, &de.file)) {
  2507. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  2508. __func__, path, strerror(ERRNO));
  2509. }
  2510. de.file_name = dp->d_name;
  2511. cb(&de, data);
  2512. }
  2513. (void) closedir(dirp);
  2514. }
  2515. return 1;
  2516. }
  2517. static int remove_directory(struct mg_connection *conn, const char *dir)
  2518. {
  2519. char path[PATH_MAX];
  2520. struct dirent *dp;
  2521. DIR *dirp;
  2522. struct de de;
  2523. if ((dirp = opendir(dir)) == NULL) {
  2524. return 0;
  2525. } else {
  2526. de.conn = conn;
  2527. while ((dp = readdir(dirp)) != NULL) {
  2528. // Do not show current dir (but show hidden files as they will also be removed)
  2529. if (!strcmp(dp->d_name, ".") ||
  2530. !strcmp(dp->d_name, "..")) {
  2531. continue;
  2532. }
  2533. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2534. // If we don't memset stat structure to zero, mtime will have
  2535. // garbage and strftime() will segfault later on in
  2536. // print_dir_entry(). memset is required only if mg_stat()
  2537. // fails. For more details, see
  2538. // http://code.google.com/p/mongoose/issues/detail?id=79
  2539. memset(&de.file, 0, sizeof(de.file));
  2540. if (!mg_stat(conn, path, &de.file)) {
  2541. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  2542. __func__, path, strerror(ERRNO));
  2543. }
  2544. if(de.file.modification_time) {
  2545. if(de.file.is_directory) {
  2546. remove_directory(conn, path);
  2547. } else {
  2548. mg_remove(path);
  2549. }
  2550. }
  2551. }
  2552. (void) closedir(dirp);
  2553. IGNORE_UNUSED_RESULT(rmdir(dir));
  2554. }
  2555. return 1;
  2556. }
  2557. struct dir_scan_data {
  2558. struct de *entries;
  2559. int num_entries;
  2560. int arr_size;
  2561. };
  2562. // Behaves like realloc(), but frees original pointer on failure
  2563. static void *realloc2(void *ptr, size_t size)
  2564. {
  2565. void *new_ptr = realloc(ptr, size);
  2566. if (new_ptr == NULL) {
  2567. free(ptr);
  2568. }
  2569. return new_ptr;
  2570. }
  2571. static void dir_scan_callback(struct de *de, void *data)
  2572. {
  2573. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2574. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2575. dsd->arr_size *= 2;
  2576. dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
  2577. sizeof(dsd->entries[0]));
  2578. }
  2579. if (dsd->entries == NULL) {
  2580. // TODO(lsm): propagate an error to the caller
  2581. dsd->num_entries = 0;
  2582. } else {
  2583. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2584. dsd->entries[dsd->num_entries].file = de->file;
  2585. dsd->entries[dsd->num_entries].conn = de->conn;
  2586. dsd->num_entries++;
  2587. }
  2588. }
  2589. static void handle_directory_request(struct mg_connection *conn,
  2590. const char *dir)
  2591. {
  2592. int i, sort_direction;
  2593. struct dir_scan_data data = { NULL, 0, 128 };
  2594. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2595. send_http_error(conn, 500, "Cannot open directory",
  2596. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2597. return;
  2598. }
  2599. sort_direction = conn->request_info.query_string != NULL &&
  2600. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2601. conn->must_close = 1;
  2602. mg_printf(conn, "%s",
  2603. "HTTP/1.1 200 OK\r\n"
  2604. "Connection: close\r\n"
  2605. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2606. conn->num_bytes_sent += mg_printf(conn,
  2607. "<html><head><title>Index of %s</title>"
  2608. "<style>th {text-align: left;}</style></head>"
  2609. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2610. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2611. "<th><a href=\"?d%c\">Modified</a></th>"
  2612. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2613. "<tr><td colspan=\"3\"><hr></td></tr>",
  2614. conn->request_info.uri, conn->request_info.uri,
  2615. sort_direction, sort_direction, sort_direction);
  2616. // Print first entry - link to a parent directory
  2617. conn->num_bytes_sent += mg_printf(conn,
  2618. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2619. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2620. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2621. // Sort and print directory entries
  2622. if (data.entries != NULL) {
  2623. qsort(data.entries, (size_t) data.num_entries,
  2624. sizeof(data.entries[0]), compare_dir_entries);
  2625. for (i = 0; i < data.num_entries; i++) {
  2626. print_dir_entry(&data.entries[i]);
  2627. free(data.entries[i].file_name);
  2628. }
  2629. free(data.entries);
  2630. }
  2631. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2632. conn->status_code = 200;
  2633. }
  2634. // Send len bytes from the opened file to the client.
  2635. static void send_file_data(struct mg_connection *conn, struct file *filep,
  2636. int64_t offset, int64_t len)
  2637. {
  2638. char buf[MG_BUF_LEN];
  2639. int to_read, num_read, num_written;
  2640. // Sanity check the offset
  2641. offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
  2642. if (len > 0 && filep->membuf != NULL && filep->size > 0) {
  2643. if (len > filep->size - offset) {
  2644. len = filep->size - offset;
  2645. }
  2646. mg_write(conn, filep->membuf + offset, (size_t) len);
  2647. } else if (len > 0 && filep->fp != NULL) {
  2648. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  2649. mg_cry(conn, "%s: fseeko() failed: %s",
  2650. __func__, strerror(ERRNO));
  2651. }
  2652. while (len > 0) {
  2653. // Calculate how much to read from the file in the buffer
  2654. to_read = sizeof(buf);
  2655. if ((int64_t) to_read > len) {
  2656. to_read = (int) len;
  2657. }
  2658. // Read from file, exit the loop on error
  2659. if ((num_read = (int) fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
  2660. break;
  2661. }
  2662. // Send read bytes to the client, exit the loop on error
  2663. if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
  2664. break;
  2665. }
  2666. // Both read and were successful, adjust counters
  2667. conn->num_bytes_sent += num_written;
  2668. len -= num_written;
  2669. }
  2670. }
  2671. }
  2672. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  2673. {
  2674. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2675. }
  2676. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2677. {
  2678. struct tm *tm;
  2679. tm = gmtime(t);
  2680. if (tm != NULL) {
  2681. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2682. } else {
  2683. strncpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2684. buf[buf_len - 1] = '\0';
  2685. }
  2686. }
  2687. static void construct_etag(char *buf, size_t buf_len,
  2688. const struct file *filep)
  2689. {
  2690. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2691. (unsigned long) filep->modification_time, filep->size);
  2692. }
  2693. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  2694. {
  2695. if (filep != NULL && filep->fp != NULL) {
  2696. #ifdef _WIN32
  2697. (void) conn; /* Unused. */
  2698. #else
  2699. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  2700. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2701. __func__, strerror(ERRNO));
  2702. }
  2703. #endif
  2704. }
  2705. }
  2706. static void handle_file_request(struct mg_connection *conn, const char *path,
  2707. struct file *filep)
  2708. {
  2709. char date[64], lm[64], etag[64], range[64];
  2710. const char *msg = "OK", *hdr;
  2711. time_t curtime = time(NULL);
  2712. int64_t cl, r1, r2;
  2713. struct vec mime_vec;
  2714. int n;
  2715. char gz_path[PATH_MAX];
  2716. char const* encoding = "";
  2717. get_mime_type(conn->ctx, path, &mime_vec);
  2718. cl = filep->size;
  2719. conn->status_code = 200;
  2720. range[0] = '\0';
  2721. // if this file is in fact a pre-gzipped file, rewrite its filename
  2722. // it's important to rewrite the filename after resolving
  2723. // the mime type from it, to preserve the actual file's type
  2724. if (filep->gzipped) {
  2725. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  2726. path = gz_path;
  2727. encoding = "Content-Encoding: gzip\r\n";
  2728. }
  2729. if (!mg_fopen(conn, path, "rb", filep)) {
  2730. send_http_error(conn, 500, http_500_error,
  2731. "fopen(%s): %s", path, strerror(ERRNO));
  2732. return;
  2733. }
  2734. fclose_on_exec(filep, conn);
  2735. // If Range: header specified, act accordingly
  2736. r1 = r2 = 0;
  2737. hdr = mg_get_header(conn, "Range");
  2738. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  2739. r1 >= 0 && r2 >= 0) {
  2740. // actually, range requests don't play well with a pre-gzipped
  2741. // file (since the range is specified in the uncompressed space)
  2742. if (filep->gzipped) {
  2743. send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
  2744. mg_fclose(filep);
  2745. return;
  2746. }
  2747. conn->status_code = 206;
  2748. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
  2749. mg_snprintf(conn, range, sizeof(range),
  2750. "Content-Range: bytes "
  2751. "%" INT64_FMT "-%"
  2752. INT64_FMT "/%" INT64_FMT "\r\n",
  2753. r1, r1 + cl - 1, filep->size);
  2754. msg = "Partial Content";
  2755. }
  2756. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2757. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2758. gmt_time_string(date, sizeof(date), &curtime);
  2759. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  2760. construct_etag(etag, sizeof(etag), filep);
  2761. (void) mg_printf(conn,
  2762. "HTTP/1.1 %d %s\r\n"
  2763. "Date: %s\r\n"
  2764. "Last-Modified: %s\r\n"
  2765. "Etag: %s\r\n"
  2766. "Content-Type: %.*s\r\n"
  2767. "Content-Length: %" INT64_FMT "\r\n"
  2768. "Connection: %s\r\n"
  2769. "Accept-Ranges: bytes\r\n"
  2770. "%s%s\r\n",
  2771. conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
  2772. mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
  2773. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2774. send_file_data(conn, filep, r1, cl);
  2775. }
  2776. mg_fclose(filep);
  2777. }
  2778. void mg_send_file(struct mg_connection *conn, const char *path)
  2779. {
  2780. struct file file = STRUCT_FILE_INITIALIZER;
  2781. if (mg_stat(conn, path, &file)) {
  2782. handle_file_request(conn, path, &file);
  2783. } else {
  2784. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2785. }
  2786. }
  2787. // Parse HTTP headers from the given buffer, advance buffer to the point
  2788. // where parsing stopped.
  2789. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  2790. {
  2791. int i;
  2792. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2793. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2794. ri->http_headers[i].value = skip(buf, "\r\n");
  2795. if (ri->http_headers[i].name[0] == '\0')
  2796. break;
  2797. ri->num_headers = i + 1;
  2798. }
  2799. }
  2800. static int is_valid_http_method(const char *method)
  2801. {
  2802. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2803. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2804. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2805. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  2806. || !strcmp(method, "MKCOL")
  2807. ;
  2808. }
  2809. // Parse HTTP request, fill in mg_request_info structure.
  2810. // This function modifies the buffer by NUL-terminating
  2811. // HTTP request components, header names and header values.
  2812. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  2813. {
  2814. int is_request, request_length = get_request_len(buf, len);
  2815. if (request_length > 0) {
  2816. // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  2817. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2818. ri->num_headers = 0;
  2819. buf[request_length - 1] = '\0';
  2820. // RFC says that all initial whitespaces should be ingored
  2821. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2822. buf++;
  2823. }
  2824. ri->request_method = skip(&buf, " ");
  2825. ri->uri = skip(&buf, " ");
  2826. ri->http_version = skip(&buf, "\r\n");
  2827. // HTTP message could be either HTTP request or HTTP response, e.g.
  2828. // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
  2829. is_request = is_valid_http_method(ri->request_method);
  2830. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  2831. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  2832. request_length = -1;
  2833. } else {
  2834. if (is_request) {
  2835. ri->http_version += 5;
  2836. }
  2837. parse_http_headers(&buf, ri);
  2838. }
  2839. }
  2840. return request_length;
  2841. }
  2842. // Keep reading the input (either opened file descriptor fd, or socket sock,
  2843. // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2844. // buffer (which marks the end of HTTP request). Buffer buf may already
  2845. // have some data. The length of the data is stored in nread.
  2846. // Upon every read operation, increase nread by the number of bytes read.
  2847. static int read_request(FILE *fp, struct mg_connection *conn,
  2848. char *buf, int bufsiz, int *nread)
  2849. {
  2850. int request_len, n = 0;
  2851. request_len = get_request_len(buf, *nread);
  2852. while (conn->ctx->stop_flag == 0 &&
  2853. *nread < bufsiz && request_len == 0 &&
  2854. (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
  2855. *nread += n;
  2856. assert(*nread <= bufsiz);
  2857. request_len = get_request_len(buf, *nread);
  2858. }
  2859. return request_len <= 0 && n <= 0 ? -1 : request_len;
  2860. }
  2861. // For given directory path, substitute it to valid index file.
  2862. // Return 0 if index file has been found, -1 if not found.
  2863. // If the file is found, it's stats is returned in stp.
  2864. static int substitute_index_file(struct mg_connection *conn, char *path,
  2865. size_t path_len, struct file *filep)
  2866. {
  2867. const char *list = conn->ctx->config[INDEX_FILES];
  2868. struct file file = STRUCT_FILE_INITIALIZER;
  2869. struct vec filename_vec;
  2870. size_t n = strlen(path);
  2871. int found = 0;
  2872. // The 'path' given to us points to the directory. Remove all trailing
  2873. // directory separator characters from the end of the path, and
  2874. // then append single directory separator character.
  2875. while (n > 0 && path[n - 1] == '/') {
  2876. n--;
  2877. }
  2878. path[n] = '/';
  2879. // Traverse index files list. For each entry, append it to the given
  2880. // path and see if the file exists. If it exists, break the loop
  2881. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2882. // Ignore too long entries that may overflow path buffer
  2883. if (filename_vec.len > path_len - (n + 2))
  2884. continue;
  2885. // Prepare full path to the index file
  2886. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2887. // Does it exist?
  2888. if (mg_stat(conn, path, &file)) {
  2889. // Yes it does, break the loop
  2890. *filep = file;
  2891. found = 1;
  2892. break;
  2893. }
  2894. }
  2895. // If no index file exists, restore directory path
  2896. if (!found) {
  2897. path[n] = '\0';
  2898. }
  2899. return found;
  2900. }
  2901. // Return True if we should reply 304 Not Modified.
  2902. static int is_not_modified(const struct mg_connection *conn,
  2903. const struct file *filep)
  2904. {
  2905. char etag[64];
  2906. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2907. const char *inm = mg_get_header(conn, "If-None-Match");
  2908. construct_etag(etag, sizeof(etag), filep);
  2909. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2910. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  2911. }
  2912. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  2913. SOCKET sock, SSL *ssl)
  2914. {
  2915. const char *expect, *body;
  2916. char buf[MG_BUF_LEN];
  2917. int to_read, nread, buffered_len, success = 0;
  2918. expect = mg_get_header(conn, "Expect");
  2919. assert(fp != NULL);
  2920. if (conn->content_len == -1) {
  2921. send_http_error(conn, 411, "Length Required", "%s", "");
  2922. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2923. send_http_error(conn, 417, "Expectation Failed", "%s", "");
  2924. } else {
  2925. if (expect != NULL) {
  2926. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  2927. }
  2928. body = conn->buf + conn->request_len + conn->consumed_content;
  2929. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  2930. assert(buffered_len >= 0);
  2931. assert(conn->consumed_content == 0);
  2932. if (buffered_len > 0) {
  2933. if ((int64_t) buffered_len > conn->content_len) {
  2934. buffered_len = (int) conn->content_len;
  2935. }
  2936. push(fp, sock, ssl, body, (int64_t) buffered_len);
  2937. conn->consumed_content += buffered_len;
  2938. }
  2939. nread = 0;
  2940. while (conn->consumed_content < conn->content_len) {
  2941. to_read = sizeof(buf);
  2942. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  2943. to_read = (int) (conn->content_len - conn->consumed_content);
  2944. }
  2945. nread = pull(NULL, conn, buf, to_read);
  2946. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  2947. break;
  2948. }
  2949. conn->consumed_content += nread;
  2950. }
  2951. if (conn->consumed_content == conn->content_len) {
  2952. success = nread >= 0;
  2953. }
  2954. // Each error code path in this function must send an error
  2955. if (!success) {
  2956. send_http_error(conn, 577, http_500_error, "%s", "");
  2957. }
  2958. }
  2959. return success;
  2960. }
  2961. #if !defined(NO_CGI)
  2962. // This structure helps to create an environment for the spawned CGI program.
  2963. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2964. // last element must be NULL.
  2965. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2966. // strings must reside in a contiguous buffer. The end of the buffer is
  2967. // marked by two '\0' characters.
  2968. // We satisfy both worlds: we create an envp array (which is vars), all
  2969. // entries are actually pointers inside buf.
  2970. struct cgi_env_block {
  2971. struct mg_connection *conn;
  2972. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  2973. int len; // Space taken
  2974. char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
  2975. int nvars; // Number of variables
  2976. };
  2977. static char *addenv(struct cgi_env_block *block,
  2978. PRINTF_FORMAT_STRING(const char *fmt), ...)
  2979. PRINTF_ARGS(2, 3);
  2980. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2981. // pointer into the vars array.
  2982. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  2983. {
  2984. int n, space;
  2985. char *added;
  2986. va_list ap;
  2987. // Calculate how much space is left in the buffer
  2988. space = sizeof(block->buf) - block->len - 2;
  2989. assert(space >= 0);
  2990. // Make a pointer to the free space int the buffer
  2991. added = block->buf + block->len;
  2992. // Copy VARIABLE=VALUE\0 string into the free space
  2993. va_start(ap, fmt);
  2994. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2995. va_end(ap);
  2996. // Make sure we do not overflow buffer and the envp array
  2997. if (n > 0 && n + 1 < space &&
  2998. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2999. // Append a pointer to the added string into the envp array
  3000. block->vars[block->nvars++] = added;
  3001. // Bump up used length counter. Include \0 terminator
  3002. block->len += n + 1;
  3003. } else {
  3004. mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  3005. }
  3006. return added;
  3007. }
  3008. static void prepare_cgi_environment(struct mg_connection *conn,
  3009. const char *prog,
  3010. struct cgi_env_block *blk)
  3011. {
  3012. const char *s, *slash;
  3013. struct vec var_vec;
  3014. char *p, src_addr[IP_ADDR_STR_LEN];
  3015. int i;
  3016. blk->len = blk->nvars = 0;
  3017. blk->conn = conn;
  3018. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3019. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  3020. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3021. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  3022. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  3023. // Prepare the environment block
  3024. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  3025. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  3026. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  3027. // TODO(lsm): fix this for IPv6 case
  3028. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  3029. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  3030. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  3031. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  3032. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  3033. // SCRIPT_NAME
  3034. assert(conn->request_info.uri[0] == '/');
  3035. slash = strrchr(conn->request_info.uri, '/');
  3036. if ((s = strrchr(prog, '/')) == NULL)
  3037. s = prog;
  3038. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  3039. conn->request_info.uri, s);
  3040. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  3041. addenv(blk, "PATH_TRANSLATED=%s", prog);
  3042. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  3043. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  3044. addenv(blk, "CONTENT_TYPE=%s", s);
  3045. if (conn->request_info.query_string != NULL)
  3046. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  3047. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  3048. addenv(blk, "CONTENT_LENGTH=%s", s);
  3049. if ((s = getenv("PATH")) != NULL)
  3050. addenv(blk, "PATH=%s", s);
  3051. if (conn->path_info != NULL) {
  3052. addenv(blk, "PATH_INFO=%s", conn->path_info);
  3053. }
  3054. #if defined(_WIN32)
  3055. if ((s = getenv("COMSPEC")) != NULL) {
  3056. addenv(blk, "COMSPEC=%s", s);
  3057. }
  3058. if ((s = getenv("SYSTEMROOT")) != NULL) {
  3059. addenv(blk, "SYSTEMROOT=%s", s);
  3060. }
  3061. if ((s = getenv("SystemDrive")) != NULL) {
  3062. addenv(blk, "SystemDrive=%s", s);
  3063. }
  3064. if ((s = getenv("ProgramFiles")) != NULL) {
  3065. addenv(blk, "ProgramFiles=%s", s);
  3066. }
  3067. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  3068. addenv(blk, "ProgramFiles(x86)=%s", s);
  3069. }
  3070. #else
  3071. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  3072. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  3073. #endif // _WIN32
  3074. if ((s = getenv("PERLLIB")) != NULL)
  3075. addenv(blk, "PERLLIB=%s", s);
  3076. if (conn->request_info.remote_user != NULL) {
  3077. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  3078. addenv(blk, "%s", "AUTH_TYPE=Digest");
  3079. }
  3080. // Add all headers as HTTP_* variables
  3081. for (i = 0; i < conn->request_info.num_headers; i++) {
  3082. p = addenv(blk, "HTTP_%s=%s",
  3083. conn->request_info.http_headers[i].name,
  3084. conn->request_info.http_headers[i].value);
  3085. // Convert variable name into uppercase, and change - to _
  3086. for (; *p != '=' && *p != '\0'; p++) {
  3087. if (*p == '-')
  3088. *p = '_';
  3089. *p = (char) toupper(* (unsigned char *) p);
  3090. }
  3091. }
  3092. // Add user-specified variables
  3093. s = conn->ctx->config[CGI_ENVIRONMENT];
  3094. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  3095. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  3096. }
  3097. blk->vars[blk->nvars++] = NULL;
  3098. blk->buf[blk->len++] = '\0';
  3099. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  3100. assert(blk->len > 0);
  3101. assert(blk->len < (int) sizeof(blk->buf));
  3102. }
  3103. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  3104. {
  3105. char *buf;
  3106. size_t buflen;
  3107. int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
  3108. const char *status, *status_text, *connection_state;
  3109. char *pbuf, dir[PATH_MAX], *p;
  3110. struct mg_request_info ri;
  3111. struct cgi_env_block blk;
  3112. FILE *in = NULL, *out = NULL;
  3113. struct file fout = STRUCT_FILE_INITIALIZER;
  3114. pid_t pid = (pid_t) -1;
  3115. buf = NULL;
  3116. buflen = 16384;
  3117. prepare_cgi_environment(conn, prog, &blk);
  3118. // CGI must be executed in its own directory. 'dir' must point to the
  3119. // directory containing executable program, 'p' must point to the
  3120. // executable program name relative to 'dir'.
  3121. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  3122. if ((p = strrchr(dir, '/')) != NULL) {
  3123. *p++ = '\0';
  3124. } else {
  3125. dir[0] = '.', dir[1] = '\0';
  3126. p = (char *) prog;
  3127. }
  3128. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  3129. send_http_error(conn, 500, http_500_error,
  3130. "Cannot create CGI pipe: %s", strerror(ERRNO));
  3131. goto done;
  3132. }
  3133. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  3134. if (pid == (pid_t) -1) {
  3135. send_http_error(conn, 500, http_500_error,
  3136. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  3137. goto done;
  3138. }
  3139. // Make sure child closes all pipe descriptors. It must dup them to 0,1
  3140. set_close_on_exec(fdin[0], conn);
  3141. set_close_on_exec(fdin[1], conn);
  3142. set_close_on_exec(fdout[0], conn);
  3143. set_close_on_exec(fdout[1], conn);
  3144. // Parent closes only one side of the pipes.
  3145. // If we don't mark them as closed, close() attempt before
  3146. // return from this function throws an exception on Windows.
  3147. // Windows does not like when closed descriptor is closed again.
  3148. (void) close(fdin[0]);
  3149. (void) close(fdout[1]);
  3150. fdin[0] = fdout[1] = -1;
  3151. if ((in = fdopen(fdin[1], "wb")) == NULL ||
  3152. (out = fdopen(fdout[0], "rb")) == NULL) {
  3153. send_http_error(conn, 500, http_500_error,
  3154. "fopen: %s", strerror(ERRNO));
  3155. goto done;
  3156. }
  3157. setbuf(in, NULL);
  3158. setbuf(out, NULL);
  3159. fout.fp = out;
  3160. // Send POST data to the CGI process if needed
  3161. if (!strcmp(conn->request_info.request_method, "POST") &&
  3162. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  3163. goto done;
  3164. }
  3165. // Close so child gets an EOF.
  3166. fclose(in);
  3167. in = NULL;
  3168. fdin[1] = -1;
  3169. // Now read CGI reply into a buffer. We need to set correct
  3170. // status code, thus we need to see all HTTP headers first.
  3171. // Do not send anything back to client, until we buffer in all
  3172. // HTTP headers.
  3173. data_len = 0;
  3174. buf = malloc(buflen);
  3175. if (buf == NULL) {
  3176. send_http_error(conn, 500, http_500_error,
  3177. "Not enough memory for buffer (%u bytes)",
  3178. (unsigned int) buflen);
  3179. goto done;
  3180. }
  3181. headers_len = read_request(out, conn, buf, (int) buflen, &data_len);
  3182. if (headers_len <= 0) {
  3183. send_http_error(conn, 500, http_500_error,
  3184. "CGI program sent malformed or too big (>%u bytes) "
  3185. "HTTP headers: [%.*s]",
  3186. (unsigned) buflen, data_len, buf);
  3187. goto done;
  3188. }
  3189. pbuf = buf;
  3190. buf[headers_len - 1] = '\0';
  3191. parse_http_headers(&pbuf, &ri);
  3192. // Make up and send the status line
  3193. status_text = "OK";
  3194. if ((status = get_header(&ri, "Status")) != NULL) {
  3195. conn->status_code = atoi(status);
  3196. status_text = status;
  3197. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  3198. status_text++;
  3199. }
  3200. } else if (get_header(&ri, "Location") != NULL) {
  3201. conn->status_code = 302;
  3202. } else {
  3203. conn->status_code = 200;
  3204. }
  3205. connection_state = get_header(&ri, "Connection");
  3206. if (connection_state == NULL ||
  3207. mg_strcasecmp(connection_state, "keep-alive")) {
  3208. conn->must_close = 1;
  3209. }
  3210. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
  3211. status_text);
  3212. // Send headers
  3213. for (i = 0; i < ri.num_headers; i++) {
  3214. mg_printf(conn, "%s: %s\r\n",
  3215. ri.http_headers[i].name, ri.http_headers[i].value);
  3216. }
  3217. mg_write(conn, "\r\n", 2);
  3218. // Send chunk of data that may have been read after the headers
  3219. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  3220. (size_t)(data_len - headers_len));
  3221. // Read the rest of CGI output and send to the client
  3222. send_file_data(conn, &fout, 0, INT64_MAX);
  3223. done:
  3224. if (pid != (pid_t) -1) {
  3225. kill(pid, SIGKILL);
  3226. #if !defined(_WIN32)
  3227. {
  3228. int st;
  3229. while (waitpid(pid, &st, 0) != -1); // clean zombies
  3230. }
  3231. #endif
  3232. }
  3233. if (fdin[0] != -1) {
  3234. close(fdin[0]);
  3235. }
  3236. if (fdout[1] != -1) {
  3237. close(fdout[1]);
  3238. }
  3239. if (in != NULL) {
  3240. fclose(in);
  3241. } else if (fdin[1] != -1) {
  3242. close(fdin[1]);
  3243. }
  3244. if (out != NULL) {
  3245. fclose(out);
  3246. } else if (fdout[0] != -1) {
  3247. close(fdout[0]);
  3248. }
  3249. if (buf != NULL) {
  3250. free(buf);
  3251. }
  3252. }
  3253. #endif // !NO_CGI
  3254. // For a given PUT path, create all intermediate subdirectories
  3255. // for given path. Return 0 if the path itself is a directory,
  3256. // or -1 on error, 1 if OK.
  3257. static int put_dir(struct mg_connection *conn, const char *path)
  3258. {
  3259. char buf[PATH_MAX];
  3260. const char *s, *p;
  3261. struct file file = STRUCT_FILE_INITIALIZER;
  3262. int len, res = 1;
  3263. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  3264. len = (int)(p - path);
  3265. if (len >= (int) sizeof(buf)) {
  3266. res = -1;
  3267. break;
  3268. }
  3269. memcpy(buf, path, len);
  3270. buf[len] = '\0';
  3271. // Try to create intermediate directory
  3272. DEBUG_TRACE(("mkdir(%s)", buf));
  3273. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  3274. res = -1;
  3275. break;
  3276. }
  3277. // Is path itself a directory?
  3278. if (p[1] == '\0') {
  3279. res = 0;
  3280. }
  3281. }
  3282. return res;
  3283. }
  3284. static void mkcol(struct mg_connection *conn, const char *path)
  3285. {
  3286. int rc, body_len;
  3287. struct de de;
  3288. memset(&de.file, 0, sizeof(de.file));
  3289. if (!mg_stat(conn, path, &de.file)) {
  3290. mg_cry(conn, "%s: mg_stat(%s) failed: %s",
  3291. __func__, path, strerror(ERRNO));
  3292. }
  3293. if(de.file.modification_time) {
  3294. send_http_error(conn, 405, "Method Not Allowed",
  3295. "mkcol(%s): %s", path, strerror(ERRNO));
  3296. return;
  3297. }
  3298. body_len = conn->data_len - conn->request_len;
  3299. if(body_len > 0) {
  3300. send_http_error(conn, 415, "Unsupported media type",
  3301. "mkcol(%s): %s", path, strerror(ERRNO));
  3302. return;
  3303. }
  3304. rc = mg_mkdir(path, 0755);
  3305. if (rc == 0) {
  3306. conn->status_code = 201;
  3307. mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code);
  3308. } else if (rc == -1) {
  3309. if(errno == EEXIST)
  3310. send_http_error(conn, 405, "Method Not Allowed",
  3311. "mkcol(%s): %s", path, strerror(ERRNO));
  3312. else if(errno == EACCES)
  3313. send_http_error(conn, 403, "Forbidden",
  3314. "mkcol(%s): %s", path, strerror(ERRNO));
  3315. else if(errno == ENOENT)
  3316. send_http_error(conn, 409, "Conflict",
  3317. "mkcol(%s): %s", path, strerror(ERRNO));
  3318. else
  3319. send_http_error(conn, 500, http_500_error,
  3320. "fopen(%s): %s", path, strerror(ERRNO));
  3321. }
  3322. }
  3323. static void put_file(struct mg_connection *conn, const char *path)
  3324. {
  3325. struct file file = STRUCT_FILE_INITIALIZER;
  3326. const char *range;
  3327. int64_t r1, r2;
  3328. int rc;
  3329. conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
  3330. if ((rc = put_dir(conn, path)) == 0) {
  3331. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
  3332. } else if (rc == -1) {
  3333. send_http_error(conn, 500, http_500_error,
  3334. "put_dir(%s): %s", path, strerror(ERRNO));
  3335. } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  3336. mg_fclose(&file);
  3337. send_http_error(conn, 500, http_500_error,
  3338. "fopen(%s): %s", path, strerror(ERRNO));
  3339. } else {
  3340. fclose_on_exec(&file, conn);
  3341. range = mg_get_header(conn, "Content-Range");
  3342. r1 = r2 = 0;
  3343. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3344. conn->status_code = 206;
  3345. fseeko(file.fp, r1, SEEK_SET);
  3346. }
  3347. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  3348. conn->status_code = 500;
  3349. }
  3350. mg_printf(conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
  3351. conn->status_code);
  3352. mg_fclose(&file);
  3353. }
  3354. }
  3355. static void send_ssi_file(struct mg_connection *, const char *,
  3356. struct file *, int);
  3357. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3358. char *tag, int include_level)
  3359. {
  3360. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  3361. struct file file = STRUCT_FILE_INITIALIZER;
  3362. // sscanf() is safe here, since send_ssi_file() also uses buffer
  3363. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  3364. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  3365. // File name is relative to the webserver root
  3366. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  3367. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  3368. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  3369. // File name is relative to the webserver working directory
  3370. // or it is absolute system path
  3371. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  3372. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  3373. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  3374. // File name is relative to the currect document
  3375. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3376. if ((p = strrchr(path, '/')) != NULL) {
  3377. p[1] = '\0';
  3378. }
  3379. (void) mg_snprintf(conn, path + strlen(path),
  3380. sizeof(path) - strlen(path), "%s", file_name);
  3381. } else {
  3382. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  3383. return;
  3384. }
  3385. if (!mg_fopen(conn, path, "rb", &file)) {
  3386. mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3387. tag, path, strerror(ERRNO));
  3388. } else {
  3389. fclose_on_exec(&file, conn);
  3390. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3391. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3392. send_ssi_file(conn, path, &file, include_level + 1);
  3393. } else {
  3394. send_file_data(conn, &file, 0, INT64_MAX);
  3395. }
  3396. mg_fclose(&file);
  3397. }
  3398. }
  3399. #if !defined(NO_POPEN)
  3400. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  3401. {
  3402. char cmd[MG_BUF_LEN] = "";
  3403. struct file file = STRUCT_FILE_INITIALIZER;
  3404. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3405. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  3406. } else if ((file.fp = popen(cmd, "r")) == NULL) {
  3407. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3408. } else {
  3409. send_file_data(conn, &file, 0, INT64_MAX);
  3410. pclose(file.fp);
  3411. }
  3412. }
  3413. #endif // !NO_POPEN
  3414. static int mg_fgetc(struct file *filep, int offset)
  3415. {
  3416. if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
  3417. return ((unsigned char *) filep->membuf)[offset];
  3418. } else if (filep->fp != NULL) {
  3419. return fgetc(filep->fp);
  3420. } else {
  3421. return EOF;
  3422. }
  3423. }
  3424. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3425. struct file *filep, int include_level)
  3426. {
  3427. char buf[MG_BUF_LEN];
  3428. int ch, offset, len, in_ssi_tag;
  3429. if (include_level > 10) {
  3430. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  3431. return;
  3432. }
  3433. in_ssi_tag = len = offset = 0;
  3434. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  3435. if (in_ssi_tag && ch == '>') {
  3436. in_ssi_tag = 0;
  3437. buf[len++] = (char) ch;
  3438. buf[len] = '\0';
  3439. assert(len <= (int) sizeof(buf));
  3440. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3441. // Not an SSI tag, pass it
  3442. (void) mg_write(conn, buf, (size_t) len);
  3443. } else {
  3444. if (!memcmp(buf + 5, "include", 7)) {
  3445. do_ssi_include(conn, path, buf + 12, include_level);
  3446. #if !defined(NO_POPEN)
  3447. } else if (!memcmp(buf + 5, "exec", 4)) {
  3448. do_ssi_exec(conn, buf + 9);
  3449. #endif // !NO_POPEN
  3450. } else {
  3451. mg_cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3452. }
  3453. }
  3454. len = 0;
  3455. } else if (in_ssi_tag) {
  3456. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3457. // Not an SSI tag
  3458. in_ssi_tag = 0;
  3459. } else if (len == (int) sizeof(buf) - 2) {
  3460. mg_cry(conn, "%s: SSI tag is too large", path);
  3461. len = 0;
  3462. }
  3463. buf[len++] = ch & 0xff;
  3464. } else if (ch == '<') {
  3465. in_ssi_tag = 1;
  3466. if (len > 0) {
  3467. mg_write(conn, buf, (size_t) len);
  3468. }
  3469. len = 0;
  3470. buf[len++] = ch & 0xff;
  3471. } else {
  3472. buf[len++] = ch & 0xff;
  3473. if (len == (int) sizeof(buf)) {
  3474. mg_write(conn, buf, (size_t) len);
  3475. len = 0;
  3476. }
  3477. }
  3478. }
  3479. // Send the rest of buffered data
  3480. if (len > 0) {
  3481. mg_write(conn, buf, (size_t) len);
  3482. }
  3483. }
  3484. static void handle_ssi_file_request(struct mg_connection *conn,
  3485. const char *path)
  3486. {
  3487. struct file file = STRUCT_FILE_INITIALIZER;
  3488. if (!mg_fopen(conn, path, "rb", &file)) {
  3489. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  3490. strerror(ERRNO));
  3491. } else {
  3492. conn->must_close = 1;
  3493. fclose_on_exec(&file, conn);
  3494. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3495. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  3496. suggest_connection_header(conn));
  3497. send_ssi_file(conn, path, &file, 0);
  3498. mg_fclose(&file);
  3499. }
  3500. }
  3501. static void send_options(struct mg_connection *conn)
  3502. {
  3503. conn->status_code = 200;
  3504. mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  3505. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
  3506. "DAV: 1\r\n\r\n");
  3507. }
  3508. // Writes PROPFIND properties for a collection element
  3509. static void print_props(struct mg_connection *conn, const char* uri,
  3510. struct file *filep)
  3511. {
  3512. char mtime[64];
  3513. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  3514. conn->num_bytes_sent += mg_printf(conn,
  3515. "<d:response>"
  3516. "<d:href>%s</d:href>"
  3517. "<d:propstat>"
  3518. "<d:prop>"
  3519. "<d:resourcetype>%s</d:resourcetype>"
  3520. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3521. "<d:getlastmodified>%s</d:getlastmodified>"
  3522. "</d:prop>"
  3523. "<d:status>HTTP/1.1 200 OK</d:status>"
  3524. "</d:propstat>"
  3525. "</d:response>\n",
  3526. uri,
  3527. filep->is_directory ? "<d:collection/>" : "",
  3528. filep->size,
  3529. mtime);
  3530. }
  3531. static void print_dav_dir_entry(struct de *de, void *data)
  3532. {
  3533. char href[PATH_MAX];
  3534. char href_encoded[PATH_MAX];
  3535. struct mg_connection *conn = (struct mg_connection *) data;
  3536. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3537. conn->request_info.uri, de->file_name);
  3538. mg_url_encode(href, href_encoded, PATH_MAX-1);
  3539. print_props(conn, href_encoded, &de->file);
  3540. }
  3541. static void handle_propfind(struct mg_connection *conn, const char *path,
  3542. struct file *filep)
  3543. {
  3544. const char *depth = mg_get_header(conn, "Depth");
  3545. conn->must_close = 1;
  3546. conn->status_code = 207;
  3547. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3548. "Connection: close\r\n"
  3549. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3550. conn->num_bytes_sent += mg_printf(conn,
  3551. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3552. "<d:multistatus xmlns:d='DAV:'>\n");
  3553. // Print properties for the requested resource itself
  3554. print_props(conn, conn->request_info.uri, filep);
  3555. // If it is a directory, print directory entries too if Depth is not 0
  3556. if (filep->is_directory &&
  3557. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3558. (depth == NULL || strcmp(depth, "0") != 0)) {
  3559. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3560. }
  3561. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3562. }
  3563. void mg_lock(struct mg_connection* conn)
  3564. {
  3565. (void) pthread_mutex_lock(&conn->mutex);
  3566. }
  3567. void mg_unlock(struct mg_connection* conn)
  3568. {
  3569. (void) pthread_mutex_unlock(&conn->mutex);
  3570. }
  3571. #if defined(USE_WEBSOCKET)
  3572. // START OF SHA-1 code
  3573. // Copyright(c) By Steve Reid <steve@edmweb.com>
  3574. #define SHA1HANDSOFF
  3575. #if defined(__sun)
  3576. #include "solarisfixes.h"
  3577. #endif
  3578. static int is_big_endian(void)
  3579. {
  3580. static const int n = 1;
  3581. return ((char *) &n)[0] == 0;
  3582. }
  3583. union char64long16 {
  3584. unsigned char c[64];
  3585. uint32_t l[16];
  3586. };
  3587. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3588. static uint32_t blk0(union char64long16 *block, int i)
  3589. {
  3590. // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  3591. if (!is_big_endian()) {
  3592. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  3593. (rol(block->l[i], 8) & 0x00FF00FF);
  3594. }
  3595. return block->l[i];
  3596. }
  3597. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3598. ^block->l[(i+2)&15]^block->l[i&15],1))
  3599. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  3600. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3601. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3602. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3603. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3604. typedef struct {
  3605. uint32_t state[5];
  3606. uint32_t count[2];
  3607. unsigned char buffer[64];
  3608. } SHA1_CTX;
  3609. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  3610. {
  3611. uint32_t a, b, c, d, e;
  3612. union char64long16 block[1];
  3613. memcpy(block, buffer, 64);
  3614. a = state[0];
  3615. b = state[1];
  3616. c = state[2];
  3617. d = state[3];
  3618. e = state[4];
  3619. R0(a,b,c,d,e, 0);
  3620. R0(e,a,b,c,d, 1);
  3621. R0(d,e,a,b,c, 2);
  3622. R0(c,d,e,a,b, 3);
  3623. R0(b,c,d,e,a, 4);
  3624. R0(a,b,c,d,e, 5);
  3625. R0(e,a,b,c,d, 6);
  3626. R0(d,e,a,b,c, 7);
  3627. R0(c,d,e,a,b, 8);
  3628. R0(b,c,d,e,a, 9);
  3629. R0(a,b,c,d,e,10);
  3630. R0(e,a,b,c,d,11);
  3631. R0(d,e,a,b,c,12);
  3632. R0(c,d,e,a,b,13);
  3633. R0(b,c,d,e,a,14);
  3634. R0(a,b,c,d,e,15);
  3635. R1(e,a,b,c,d,16);
  3636. R1(d,e,a,b,c,17);
  3637. R1(c,d,e,a,b,18);
  3638. R1(b,c,d,e,a,19);
  3639. R2(a,b,c,d,e,20);
  3640. R2(e,a,b,c,d,21);
  3641. R2(d,e,a,b,c,22);
  3642. R2(c,d,e,a,b,23);
  3643. R2(b,c,d,e,a,24);
  3644. R2(a,b,c,d,e,25);
  3645. R2(e,a,b,c,d,26);
  3646. R2(d,e,a,b,c,27);
  3647. R2(c,d,e,a,b,28);
  3648. R2(b,c,d,e,a,29);
  3649. R2(a,b,c,d,e,30);
  3650. R2(e,a,b,c,d,31);
  3651. R2(d,e,a,b,c,32);
  3652. R2(c,d,e,a,b,33);
  3653. R2(b,c,d,e,a,34);
  3654. R2(a,b,c,d,e,35);
  3655. R2(e,a,b,c,d,36);
  3656. R2(d,e,a,b,c,37);
  3657. R2(c,d,e,a,b,38);
  3658. R2(b,c,d,e,a,39);
  3659. R3(a,b,c,d,e,40);
  3660. R3(e,a,b,c,d,41);
  3661. R3(d,e,a,b,c,42);
  3662. R3(c,d,e,a,b,43);
  3663. R3(b,c,d,e,a,44);
  3664. R3(a,b,c,d,e,45);
  3665. R3(e,a,b,c,d,46);
  3666. R3(d,e,a,b,c,47);
  3667. R3(c,d,e,a,b,48);
  3668. R3(b,c,d,e,a,49);
  3669. R3(a,b,c,d,e,50);
  3670. R3(e,a,b,c,d,51);
  3671. R3(d,e,a,b,c,52);
  3672. R3(c,d,e,a,b,53);
  3673. R3(b,c,d,e,a,54);
  3674. R3(a,b,c,d,e,55);
  3675. R3(e,a,b,c,d,56);
  3676. R3(d,e,a,b,c,57);
  3677. R3(c,d,e,a,b,58);
  3678. R3(b,c,d,e,a,59);
  3679. R4(a,b,c,d,e,60);
  3680. R4(e,a,b,c,d,61);
  3681. R4(d,e,a,b,c,62);
  3682. R4(c,d,e,a,b,63);
  3683. R4(b,c,d,e,a,64);
  3684. R4(a,b,c,d,e,65);
  3685. R4(e,a,b,c,d,66);
  3686. R4(d,e,a,b,c,67);
  3687. R4(c,d,e,a,b,68);
  3688. R4(b,c,d,e,a,69);
  3689. R4(a,b,c,d,e,70);
  3690. R4(e,a,b,c,d,71);
  3691. R4(d,e,a,b,c,72);
  3692. R4(c,d,e,a,b,73);
  3693. R4(b,c,d,e,a,74);
  3694. R4(a,b,c,d,e,75);
  3695. R4(e,a,b,c,d,76);
  3696. R4(d,e,a,b,c,77);
  3697. R4(c,d,e,a,b,78);
  3698. R4(b,c,d,e,a,79);
  3699. state[0] += a;
  3700. state[1] += b;
  3701. state[2] += c;
  3702. state[3] += d;
  3703. state[4] += e;
  3704. a = b = c = d = e = 0;
  3705. memset(block, '\0', sizeof(block));
  3706. }
  3707. static void SHA1Init(SHA1_CTX* context)
  3708. {
  3709. context->state[0] = 0x67452301;
  3710. context->state[1] = 0xEFCDAB89;
  3711. context->state[2] = 0x98BADCFE;
  3712. context->state[3] = 0x10325476;
  3713. context->state[4] = 0xC3D2E1F0;
  3714. context->count[0] = context->count[1] = 0;
  3715. }
  3716. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3717. uint32_t len)
  3718. {
  3719. uint32_t i, j;
  3720. j = context->count[0];
  3721. if ((context->count[0] += len << 3) < j)
  3722. context->count[1]++;
  3723. context->count[1] += (len>>29);
  3724. j = (j >> 3) & 63;
  3725. if ((j + len) > 63) {
  3726. memcpy(&context->buffer[j], data, (i = 64-j));
  3727. SHA1Transform(context->state, context->buffer);
  3728. for ( ; i + 63 < len; i += 64) {
  3729. SHA1Transform(context->state, &data[i]);
  3730. }
  3731. j = 0;
  3732. } else i = 0;
  3733. memcpy(&context->buffer[j], &data[i], len - i);
  3734. }
  3735. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
  3736. {
  3737. unsigned i;
  3738. unsigned char finalcount[8], c;
  3739. for (i = 0; i < 8; i++) {
  3740. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3741. >> ((3-(i & 3)) * 8) ) & 255);
  3742. }
  3743. c = 0200;
  3744. SHA1Update(context, &c, 1);
  3745. while ((context->count[0] & 504) != 448) {
  3746. c = 0000;
  3747. SHA1Update(context, &c, 1);
  3748. }
  3749. SHA1Update(context, finalcount, 8);
  3750. for (i = 0; i < 20; i++) {
  3751. digest[i] = (unsigned char)
  3752. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3753. }
  3754. memset(context, '\0', sizeof(*context));
  3755. memset(&finalcount, '\0', sizeof(finalcount));
  3756. }
  3757. // END OF SHA1 CODE
  3758. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3759. {
  3760. static const char *b64 =
  3761. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3762. int i, j, a, b, c;
  3763. for (i = j = 0; i < src_len; i += 3) {
  3764. a = src[i];
  3765. b = i + 1 >= src_len ? 0 : src[i + 1];
  3766. c = i + 2 >= src_len ? 0 : src[i + 2];
  3767. dst[j++] = b64[a >> 2];
  3768. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3769. if (i + 1 < src_len) {
  3770. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3771. }
  3772. if (i + 2 < src_len) {
  3773. dst[j++] = b64[c & 63];
  3774. }
  3775. }
  3776. while (j % 4 != 0) {
  3777. dst[j++] = '=';
  3778. }
  3779. dst[j++] = '\0';
  3780. }
  3781. static void send_websocket_handshake(struct mg_connection *conn)
  3782. {
  3783. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3784. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3785. SHA1_CTX sha_ctx;
  3786. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3787. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3788. SHA1Init(&sha_ctx);
  3789. SHA1Update(&sha_ctx, (unsigned char *) buf, (uint32_t)strlen(buf));
  3790. SHA1Final((unsigned char *) sha, &sha_ctx);
  3791. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3792. mg_printf(conn, "%s%s%s",
  3793. "HTTP/1.1 101 Switching Protocols\r\n"
  3794. "Upgrade: websocket\r\n"
  3795. "Connection: Upgrade\r\n"
  3796. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3797. }
  3798. static void read_websocket(struct mg_connection *conn)
  3799. {
  3800. // Pointer to the beginning of the portion of the incoming websocket message queue.
  3801. // The original websocket upgrade request is never removed, so the queue begins after it.
  3802. unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
  3803. int n;
  3804. // body_len is the length of the entire queue in bytes
  3805. // len is the length of the current message
  3806. // data_len is the length of the current message's data payload
  3807. // header_len is the length of the current message's header
  3808. size_t i, len, mask_len, data_len, header_len, body_len;
  3809. // "The masking key is a 32-bit value chosen at random by the client."
  3810. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  3811. unsigned char mask[4];
  3812. // data points to the place where the message is stored when passed to the websocket_data
  3813. // callback. This is either mem on the stack, or a dynamically allocated buffer if it is
  3814. // too large.
  3815. char mem[4096];
  3816. char *data = mem;
  3817. // Loop continuously, reading messages from the socket, invoking the callback,
  3818. // and waiting repeatedly until an error occurs.
  3819. assert(conn->content_len == 0);
  3820. for (;;) {
  3821. header_len = 0;
  3822. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3823. len = buf[1] & 127;
  3824. mask_len = buf[1] & 128 ? 4 : 0;
  3825. if (len < 126 && body_len >= mask_len) {
  3826. data_len = len;
  3827. header_len = 2 + mask_len;
  3828. } else if (len == 126 && body_len >= 4 + mask_len) {
  3829. header_len = 4 + mask_len;
  3830. data_len = ((((int) buf[2]) << 8) + buf[3]);
  3831. } else if (body_len >= 10 + mask_len) {
  3832. header_len = 10 + mask_len;
  3833. data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
  3834. ntohl(* (uint32_t *) &buf[6]);
  3835. }
  3836. }
  3837. if (header_len > 0) {
  3838. // Allocate space to hold websocket payload
  3839. data = mem;
  3840. if (data_len > sizeof(mem)) {
  3841. data = (char *)malloc(data_len);
  3842. if (data == NULL) {
  3843. // Allocation failed, exit the loop and then close the connection
  3844. // TODO: notify user about the failure
  3845. break;
  3846. }
  3847. }
  3848. // Copy the mask before we shift the queue and destroy it
  3849. if (mask_len > 0) {
  3850. *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
  3851. } else {
  3852. *(uint32_t*)mask = 0;
  3853. }
  3854. // Read frame payload from the first message in the queue into data and
  3855. // advance the queue by moving the memory in place.
  3856. assert(body_len >= header_len);
  3857. if (data_len + header_len > body_len) {
  3858. // Overflow case
  3859. len = body_len - header_len;
  3860. memcpy(data, buf + header_len, len);
  3861. // TODO: handle pull error
  3862. pull(NULL, conn, data + len, (int)(data_len - len));
  3863. conn->data_len = 0;
  3864. } else {
  3865. // Length of the message being read at the front of the queue
  3866. len = data_len + header_len;
  3867. // Copy the data payload into the data pointer for the callback
  3868. memcpy(data, buf + header_len, data_len);
  3869. // Move the queue forward len bytes
  3870. memmove(buf, buf + len, body_len - len);
  3871. // Mark the queue as advanced
  3872. conn->data_len -= (int)len;
  3873. }
  3874. // Apply mask if necessary
  3875. if (mask_len > 0) {
  3876. for (i = 0; i < data_len; ++i) {
  3877. data[i] ^= mask[i & 3];
  3878. }
  3879. }
  3880. // Exit the loop if callback signalled to exit,
  3881. // or "connection close" opcode received.
  3882. if ((conn->ctx->callbacks.websocket_data != NULL &&
  3883. !conn->ctx->callbacks.websocket_data(conn, buf[0], data, data_len)) ||
  3884. (buf[0] & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) { // Opcode == 8, connection close
  3885. break;
  3886. }
  3887. if (data != mem) {
  3888. free(data);
  3889. }
  3890. // Not breaking the loop, process next websocket frame.
  3891. } else {
  3892. // Read from the socket into the next available location in the message queue.
  3893. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  3894. conn->buf_size - conn->data_len)) <= 0) {
  3895. // Error, no bytes read
  3896. break;
  3897. }
  3898. conn->data_len += n;
  3899. }
  3900. }
  3901. }
  3902. int mg_websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen)
  3903. {
  3904. unsigned char header[10];
  3905. size_t headerLen = 1;
  3906. int retval = -1;
  3907. header[0] = 0x80 + (opcode & 0xF);
  3908. // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
  3909. if (dataLen < 126) {
  3910. // inline 7-bit length field
  3911. header[1] = (unsigned char)dataLen;
  3912. headerLen = 2;
  3913. } else if (dataLen <= 0xFFFF) {
  3914. // 16-bit length field
  3915. header[1] = 126;
  3916. *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
  3917. headerLen = 4;
  3918. } else {
  3919. // 64-bit length field
  3920. header[1] = 127;
  3921. *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
  3922. *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  3923. headerLen = 10;
  3924. }
  3925. // Note that POSIX/Winsock's send() is threadsafe
  3926. // http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  3927. // but mongoose's mg_printf/mg_write is not (because of the loop in push(), although that is only
  3928. // a problem if the packet is large or outgoing buffer is full).
  3929. (void) mg_lock(conn);
  3930. retval = mg_write(conn, header, headerLen);
  3931. retval = mg_write(conn, data, dataLen);
  3932. mg_unlock(conn);
  3933. return retval;
  3934. }
  3935. static void handle_websocket_request(struct mg_connection *conn)
  3936. {
  3937. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  3938. if (version == NULL || strcmp(version, "13") != 0) {
  3939. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  3940. } else if (conn->ctx->callbacks.websocket_connect != NULL &&
  3941. conn->ctx->callbacks.websocket_connect(conn) != 0) {
  3942. // Callback has returned non-zero, do not proceed with handshake
  3943. } else {
  3944. send_websocket_handshake(conn);
  3945. if (conn->ctx->callbacks.websocket_ready != NULL) {
  3946. conn->ctx->callbacks.websocket_ready(conn);
  3947. }
  3948. read_websocket(conn);
  3949. }
  3950. }
  3951. static int is_websocket_request(const struct mg_connection *conn)
  3952. {
  3953. const char *host, *upgrade, *connection, *version, *key;
  3954. host = mg_get_header(conn, "Host");
  3955. upgrade = mg_get_header(conn, "Upgrade");
  3956. connection = mg_get_header(conn, "Connection");
  3957. key = mg_get_header(conn, "Sec-WebSocket-Key");
  3958. version = mg_get_header(conn, "Sec-WebSocket-Version");
  3959. return host != NULL && upgrade != NULL && connection != NULL &&
  3960. key != NULL && version != NULL &&
  3961. mg_strcasestr(upgrade, "websocket") != NULL &&
  3962. mg_strcasestr(connection, "Upgrade") != NULL;
  3963. }
  3964. #endif // !USE_WEBSOCKET
  3965. static int isbyte(int n)
  3966. {
  3967. return n >= 0 && n <= 255;
  3968. }
  3969. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  3970. {
  3971. int n, a, b, c, d, slash = 32, len = 0;
  3972. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3973. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3974. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  3975. slash >= 0 && slash < 33) {
  3976. len = n;
  3977. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  3978. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3979. }
  3980. return len;
  3981. }
  3982. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  3983. {
  3984. int throttle = 0;
  3985. struct vec vec, val;
  3986. uint32_t net, mask;
  3987. char mult;
  3988. double v;
  3989. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  3990. mult = ',';
  3991. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  3992. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  3993. continue;
  3994. }
  3995. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  3996. if (vec.len == 1 && vec.ptr[0] == '*') {
  3997. throttle = (int) v;
  3998. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  3999. if ((remote_ip & mask) == net) {
  4000. throttle = (int) v;
  4001. }
  4002. } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
  4003. throttle = (int) v;
  4004. }
  4005. }
  4006. return throttle;
  4007. }
  4008. static uint32_t get_remote_ip(const struct mg_connection *conn)
  4009. {
  4010. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  4011. }
  4012. #ifdef USE_LUA
  4013. #include "mod_lua.inl"
  4014. #endif // USE_LUA
  4015. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  4016. {
  4017. const char *content_type_header, *boundary_start;
  4018. char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
  4019. FILE *fp;
  4020. int bl, n, i, j, headers_len, boundary_len, eof,
  4021. len = 0, num_uploaded_files = 0;
  4022. // Request looks like this:
  4023. //
  4024. // POST /upload HTTP/1.1
  4025. // Host: 127.0.0.1:8080
  4026. // Content-Length: 244894
  4027. // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  4028. //
  4029. // ------WebKitFormBoundaryRVr
  4030. // Content-Disposition: form-data; name="file"; filename="accum.png"
  4031. // Content-Type: image/png
  4032. //
  4033. // <89>PNG
  4034. // <PNG DATA>
  4035. // ------WebKitFormBoundaryRVr
  4036. // Extract boundary string from the Content-Type header
  4037. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  4038. (boundary_start = mg_strcasestr(content_type_header,
  4039. "boundary=")) == NULL ||
  4040. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  4041. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  4042. boundary[0] == '\0') {
  4043. return num_uploaded_files;
  4044. }
  4045. boundary_len = (int)strlen(boundary);
  4046. bl = boundary_len + 4; // \r\n--<boundary>
  4047. for (;;) {
  4048. // Pull in headers
  4049. assert(len >= 0 && len <= (int) sizeof(buf));
  4050. while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
  4051. len += n;
  4052. }
  4053. if ((headers_len = get_request_len(buf, len)) <= 0) {
  4054. break;
  4055. }
  4056. // Fetch file name.
  4057. fname[0] = '\0';
  4058. for (i = j = 0; i < headers_len; i++) {
  4059. if (buf[i] == '\r' && buf[i + 1] == '\n') {
  4060. buf[i] = buf[i + 1] = '\0';
  4061. // TODO(lsm): don't expect filename to be the 3rd field,
  4062. // parse the header properly instead.
  4063. IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
  4064. fname));
  4065. j = i + 2;
  4066. }
  4067. }
  4068. // Give up if the headers are not what we expect
  4069. if (fname[0] == '\0') {
  4070. break;
  4071. }
  4072. // Move data to the beginning of the buffer
  4073. assert(len >= headers_len);
  4074. memmove(buf, &buf[headers_len], len - headers_len);
  4075. len -= headers_len;
  4076. // We open the file with exclusive lock held. This guarantee us
  4077. // there is no other thread can save into the same file simultaneously.
  4078. fp = NULL;
  4079. // Construct destination file name. Do not allow paths to have slashes.
  4080. if ((s = strrchr(fname, '/')) == NULL &&
  4081. (s = strrchr(fname, '\\')) == NULL) {
  4082. s = fname;
  4083. }
  4084. // Open file in binary mode. TODO: set an exclusive lock.
  4085. snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
  4086. if ((fp = fopen(path, "wb")) == NULL) {
  4087. break;
  4088. }
  4089. // Read POST data, write into file until boundary is found.
  4090. eof = n = 0;
  4091. do {
  4092. len += n;
  4093. for (i = 0; i < len - bl; i++) {
  4094. if (!memcmp(&buf[i], "\r\n--", 4) &&
  4095. !memcmp(&buf[i + 4], boundary, boundary_len)) {
  4096. // Found boundary, that's the end of file data.
  4097. fwrite(buf, 1, i, fp);
  4098. eof = 1;
  4099. memmove(buf, &buf[i + bl], len - (i + bl));
  4100. len -= i + bl;
  4101. break;
  4102. }
  4103. }
  4104. if (!eof && len > bl) {
  4105. fwrite(buf, 1, len - bl, fp);
  4106. memmove(buf, &buf[len - bl], bl);
  4107. len = bl;
  4108. }
  4109. } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
  4110. fclose(fp);
  4111. if (eof) {
  4112. num_uploaded_files++;
  4113. if (conn->ctx->callbacks.upload != NULL) {
  4114. conn->ctx->callbacks.upload(conn, path);
  4115. }
  4116. }
  4117. }
  4118. return num_uploaded_files;
  4119. }
  4120. static int is_put_or_delete_request(const struct mg_connection *conn)
  4121. {
  4122. const char *s = conn->request_info.request_method;
  4123. return s != NULL && (!strcmp(s, "PUT") ||
  4124. !strcmp(s, "DELETE") ||
  4125. !strcmp(s, "MKCOL"));
  4126. }
  4127. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  4128. {
  4129. int i, idx = -1;
  4130. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  4131. idx = ctx->listening_sockets[i].is_ssl ? i : -1;
  4132. }
  4133. return idx;
  4134. }
  4135. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  4136. {
  4137. char host[1025];
  4138. const char *host_header;
  4139. size_t hostlen;
  4140. host_header = mg_get_header(conn, "Host");
  4141. hostlen = sizeof(host);
  4142. if (host_header != NULL) {
  4143. char *pos;
  4144. strncpy(host, host_header, hostlen);
  4145. host[hostlen - 1] = '\0';
  4146. pos = strchr(host, ':');
  4147. if (pos != NULL) {
  4148. *pos = '\0';
  4149. }
  4150. } else {
  4151. // Cannot get host from the Host: header. Fallback to our IP address.
  4152. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  4153. }
  4154. mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
  4155. host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
  4156. lsa.sin.sin_port), conn->request_info.uri);
  4157. }
  4158. void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
  4159. {
  4160. struct mg_request_handler_info *tmp_rh, *lastref = 0;
  4161. size_t urilen = strlen(uri);
  4162. // first see it the uri exists
  4163. for (tmp_rh = ctx->request_handlers;
  4164. tmp_rh != NULL && strcmp(uri, tmp_rh->uri);
  4165. lastref = tmp_rh, tmp_rh = tmp_rh->next) {
  4166. // first try for an exact match
  4167. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4168. // already there...
  4169. if (handler != NULL) {
  4170. // change this entry
  4171. tmp_rh->handler = handler;
  4172. tmp_rh->cbdata = cbdata;
  4173. } else {
  4174. // remove this entry
  4175. if (lastref != NULL)
  4176. lastref->next = tmp_rh->next;
  4177. else
  4178. ctx->request_handlers = tmp_rh->next;
  4179. free(tmp_rh->uri);
  4180. free(tmp_rh);
  4181. }
  4182. return;
  4183. }
  4184. // next try for a partial match, we will accept uri/something
  4185. if (tmp_rh->uri_len < urilen
  4186. && uri[tmp_rh->uri_len] == '/'
  4187. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4188. // if there is a partical match this new entry MUST go BEFORE
  4189. // the current position otherwise it will never be matched.
  4190. break;
  4191. }
  4192. }
  4193. if (handler == NULL) {
  4194. // no handler to set, this was a remove request
  4195. return;
  4196. }
  4197. tmp_rh = (struct mg_request_handler_info *)malloc(sizeof(struct mg_request_handler_info));
  4198. if (tmp_rh == NULL) {
  4199. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  4200. return;
  4201. }
  4202. tmp_rh->uri = mg_strdup(uri);
  4203. tmp_rh->uri_len = strlen(uri);
  4204. tmp_rh->handler = handler;
  4205. tmp_rh->cbdata = cbdata;
  4206. if (lastref == NULL) {
  4207. tmp_rh->next = ctx->request_handlers;
  4208. ctx->request_handlers = tmp_rh;
  4209. } else {
  4210. tmp_rh->next = lastref->next;
  4211. lastref->next = tmp_rh;
  4212. }
  4213. }
  4214. static int use_request_handler(struct mg_connection *conn)
  4215. {
  4216. struct mg_request_info *request_info = mg_get_request_info(conn);
  4217. const char *uri = request_info->uri;
  4218. size_t urilen = strlen(uri);
  4219. struct mg_request_handler_info *tmp_rh = conn->ctx->request_handlers;
  4220. for (; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  4221. // first try for an exact match
  4222. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
  4223. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4224. }
  4225. // next try for a partial match
  4226. // we will accept uri/something
  4227. if (tmp_rh->uri_len < urilen
  4228. && uri[tmp_rh->uri_len] == '/'
  4229. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  4230. return tmp_rh->handler(conn, tmp_rh->cbdata);
  4231. }
  4232. }
  4233. return 0; // none found
  4234. }
  4235. // This is the heart of the Civetweb's logic.
  4236. // This function is called when the request is read, parsed and validated,
  4237. // and Civetweb must decide what action to take: serve a file, or
  4238. // a directory, or call embedded function, etcetera.
  4239. static void handle_request(struct mg_connection *conn)
  4240. {
  4241. struct mg_request_info *ri = &conn->request_info;
  4242. char path[PATH_MAX];
  4243. int uri_len, ssl_index;
  4244. struct file file = STRUCT_FILE_INITIALIZER;
  4245. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  4246. * ((char *) conn->request_info.query_string++) = '\0';
  4247. }
  4248. uri_len = (int) strlen(ri->uri);
  4249. mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
  4250. remove_double_dots_and_double_slashes((char *) ri->uri);
  4251. path[0] = '\0';
  4252. convert_uri_to_file_name(conn, path, sizeof(path), &file);
  4253. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  4254. get_remote_ip(conn), ri->uri);
  4255. DEBUG_TRACE(("%s", ri->uri));
  4256. // Perform redirect and auth checks before calling begin_request() handler.
  4257. // Otherwise, begin_request() would need to perform auth checks and redirects.
  4258. if (!conn->client.is_ssl && conn->client.ssl_redir &&
  4259. (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
  4260. redirect_to_https_port(conn, ssl_index);
  4261. } else if (!is_put_or_delete_request(conn) &&
  4262. !check_authorization(conn, path)) {
  4263. send_authorization_request(conn);
  4264. } else if (conn->ctx->callbacks.begin_request != NULL &&
  4265. conn->ctx->callbacks.begin_request(conn)) {
  4266. // Do nothing, callback has served the request
  4267. } else if (conn->ctx->request_handlers != NULL &&
  4268. use_request_handler(conn)) {
  4269. // Do nothing, callback has served the request
  4270. #if defined(USE_WEBSOCKET)
  4271. } else if (is_websocket_request(conn)) {
  4272. handle_websocket_request(conn);
  4273. #endif
  4274. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  4275. send_options(conn);
  4276. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  4277. send_http_error(conn, 404, "Not Found", "Not Found");
  4278. } else if (is_put_or_delete_request(conn) &&
  4279. (is_authorized_for_put(conn) != 1)) {
  4280. send_authorization_request(conn);
  4281. } else if (!strcmp(ri->request_method, "PUT")) {
  4282. put_file(conn, path);
  4283. } else if (!strcmp(ri->request_method, "MKCOL")) {
  4284. mkcol(conn, path);
  4285. } else if (!strcmp(ri->request_method, "DELETE")) {
  4286. struct de de;
  4287. memset(&de.file, 0, sizeof(de.file));
  4288. if(!mg_stat(conn, path, &de.file)) {
  4289. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4290. } else {
  4291. if(de.file.modification_time) {
  4292. if(de.file.is_directory) {
  4293. remove_directory(conn, path);
  4294. send_http_error(conn, 204, "No Content", "%s", "");
  4295. } else if (mg_remove(path) == 0) {
  4296. send_http_error(conn, 204, "No Content", "%s", "");
  4297. } else {
  4298. send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
  4299. strerror(ERRNO));
  4300. }
  4301. } else {
  4302. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  4303. strerror(ERRNO));
  4304. }
  4305. }
  4306. } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
  4307. must_hide_file(conn, path)) {
  4308. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  4309. } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  4310. mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  4311. "Location: %s/\r\n\r\n", ri->uri);
  4312. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  4313. handle_propfind(conn, path, &file);
  4314. } else if (file.is_directory &&
  4315. !substitute_index_file(conn, path, sizeof(path), &file)) {
  4316. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  4317. handle_directory_request(conn, path);
  4318. } else {
  4319. send_http_error(conn, 403, "Directory Listing Denied",
  4320. "Directory listing denied");
  4321. }
  4322. #ifdef USE_LUA
  4323. } else if (match_prefix("**.lp$", 6, path) > 0) {
  4324. handle_lsp_request(conn, path, &file, NULL);
  4325. #endif
  4326. #if !defined(NO_CGI)
  4327. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4328. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4329. path) > 0) {
  4330. if (strcmp(ri->request_method, "POST") &&
  4331. strcmp(ri->request_method, "HEAD") &&
  4332. strcmp(ri->request_method, "GET")) {
  4333. send_http_error(conn, 501, "Not Implemented",
  4334. "Method %s is not implemented", ri->request_method);
  4335. } else {
  4336. handle_cgi_request(conn, path);
  4337. }
  4338. #endif // !NO_CGI
  4339. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  4340. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  4341. path) > 0) {
  4342. handle_ssi_file_request(conn, path);
  4343. } else if (is_not_modified(conn, &file)) {
  4344. send_http_error(conn, 304, "Not Modified", "%s", "");
  4345. } else {
  4346. handle_file_request(conn, path, &file);
  4347. }
  4348. }
  4349. static void close_all_listening_sockets(struct mg_context *ctx)
  4350. {
  4351. int i;
  4352. for (i = 0; i < ctx->num_listening_sockets; i++) {
  4353. closesocket(ctx->listening_sockets[i].sock);
  4354. }
  4355. free(ctx->listening_sockets);
  4356. }
  4357. static int is_valid_port(unsigned int port)
  4358. {
  4359. return port < 0xffff;
  4360. }
  4361. // Valid listening port specification is: [ip_address:]port[s]
  4362. // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  4363. // TODO(lsm): add parsing of the IPv6 address
  4364. static int parse_port_string(const struct vec *vec, struct socket *so)
  4365. {
  4366. unsigned int a, b, c, d, ch, len, port;
  4367. #if defined(USE_IPV6)
  4368. char buf[100];
  4369. #endif
  4370. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  4371. // Also, all-zeroes in the socket address means binding to all addresses
  4372. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  4373. memset(so, 0, sizeof(*so));
  4374. so->lsa.sin.sin_family = AF_INET;
  4375. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  4376. // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
  4377. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  4378. so->lsa.sin.sin_port = htons((uint16_t) port);
  4379. #if defined(USE_IPV6)
  4380. } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
  4381. inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
  4382. // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
  4383. so->lsa.sin6.sin6_family = AF_INET6;
  4384. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  4385. #endif
  4386. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  4387. // If only port is specified, bind to IPv4, INADDR_ANY
  4388. so->lsa.sin.sin_port = htons((uint16_t) port);
  4389. } else {
  4390. port = len = 0; // Parsing failure. Make port invalid.
  4391. }
  4392. ch = vec->ptr[len]; // Next character after the port number
  4393. so->is_ssl = ch == 's';
  4394. so->ssl_redir = ch == 'r';
  4395. // Make sure the port is valid and vector ends with 's', 'r' or ','
  4396. return is_valid_port(port) &&
  4397. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  4398. }
  4399. static int set_ports_option(struct mg_context *ctx)
  4400. {
  4401. const char *list = ctx->config[LISTENING_PORTS];
  4402. int on = 1, success = 1;
  4403. #if defined(USE_IPV6)
  4404. int off = 0;
  4405. #endif
  4406. struct vec vec;
  4407. struct socket so, *ptr;
  4408. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  4409. if (!parse_port_string(&vec, &so)) {
  4410. mg_cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  4411. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|r]");
  4412. success = 0;
  4413. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  4414. mg_cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  4415. success = 0;
  4416. } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  4417. INVALID_SOCKET ||
  4418. // On Windows, SO_REUSEADDR is recommended only for
  4419. // broadcast UDP sockets
  4420. setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
  4421. (void *) &on, sizeof(on)) != 0 ||
  4422. #if defined(USE_IPV6)
  4423. (so.lsa.sa.sa_family == AF_INET6 &&
  4424. setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
  4425. sizeof(off)) != 0) ||
  4426. #endif
  4427. bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
  4428. sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 ||
  4429. listen(so.sock, SOMAXCONN) != 0) {
  4430. mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
  4431. (int) vec.len, vec.ptr, ERRNO, strerror(errno));
  4432. if (so.sock != INVALID_SOCKET) {
  4433. closesocket(so.sock);
  4434. }
  4435. success = 0;
  4436. } else if ((ptr = (struct socket *) realloc(ctx->listening_sockets,
  4437. (ctx->num_listening_sockets + 1) *
  4438. sizeof(ctx->listening_sockets[0]))) == NULL) {
  4439. closesocket(so.sock);
  4440. success = 0;
  4441. } else {
  4442. set_close_on_exec(so.sock, fc(ctx));
  4443. ctx->listening_sockets = ptr;
  4444. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  4445. ctx->num_listening_sockets++;
  4446. }
  4447. }
  4448. if (!success) {
  4449. close_all_listening_sockets(ctx);
  4450. }
  4451. return success;
  4452. }
  4453. static void log_header(const struct mg_connection *conn, const char *header,
  4454. FILE *fp)
  4455. {
  4456. const char *header_value;
  4457. if ((header_value = mg_get_header(conn, header)) == NULL) {
  4458. (void) fprintf(fp, "%s", " -");
  4459. } else {
  4460. (void) fprintf(fp, " \"%s\"", header_value);
  4461. }
  4462. }
  4463. static void log_access(const struct mg_connection *conn)
  4464. {
  4465. const struct mg_request_info *ri;
  4466. FILE *fp;
  4467. char date[64], src_addr[IP_ADDR_STR_LEN];
  4468. struct tm *tm;
  4469. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  4470. fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  4471. if (fp == NULL)
  4472. return;
  4473. tm = localtime(&conn->birth_time);
  4474. if (tm != NULL) {
  4475. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  4476. } else {
  4477. strncpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  4478. date[sizeof(date) - 1] = '\0';
  4479. }
  4480. ri = &conn->request_info;
  4481. flockfile(fp);
  4482. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  4483. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  4484. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  4485. ri->request_method ? ri->request_method : "-",
  4486. ri->uri ? ri->uri : "-", ri->http_version,
  4487. conn->status_code, conn->num_bytes_sent);
  4488. log_header(conn, "Referer", fp);
  4489. log_header(conn, "User-Agent", fp);
  4490. fputc('\n', fp);
  4491. fflush(fp);
  4492. funlockfile(fp);
  4493. fclose(fp);
  4494. }
  4495. // Verify given socket address against the ACL.
  4496. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  4497. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  4498. {
  4499. int allowed, flag;
  4500. uint32_t net, mask;
  4501. struct vec vec;
  4502. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  4503. // If any ACL is set, deny by default
  4504. allowed = list == NULL ? '+' : '-';
  4505. while ((list = next_option(list, &vec, NULL)) != NULL) {
  4506. flag = vec.ptr[0];
  4507. if ((flag != '+' && flag != '-') ||
  4508. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  4509. mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  4510. return -1;
  4511. }
  4512. if (net == (remote_ip & mask)) {
  4513. allowed = flag;
  4514. }
  4515. }
  4516. return allowed == '+';
  4517. }
  4518. #if !defined(_WIN32)
  4519. static int set_uid_option(struct mg_context *ctx)
  4520. {
  4521. struct passwd *pw;
  4522. const char *uid = ctx->config[RUN_AS_USER];
  4523. int success = 0;
  4524. if (uid == NULL) {
  4525. success = 1;
  4526. } else {
  4527. if ((pw = getpwnam(uid)) == NULL) {
  4528. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  4529. } else if (setgid(pw->pw_gid) == -1) {
  4530. mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  4531. } else if (setuid(pw->pw_uid) == -1) {
  4532. mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  4533. } else {
  4534. success = 1;
  4535. }
  4536. }
  4537. return success;
  4538. }
  4539. #endif // !_WIN32
  4540. #if !defined(NO_SSL)
  4541. static pthread_mutex_t *ssl_mutexes;
  4542. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  4543. {
  4544. return (conn->ssl = SSL_new(s)) != NULL &&
  4545. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  4546. func(conn->ssl) == 1;
  4547. }
  4548. // Return OpenSSL error message
  4549. static const char *ssl_error(void)
  4550. {
  4551. unsigned long err;
  4552. err = ERR_get_error();
  4553. return err == 0 ? "" : ERR_error_string(err, NULL);
  4554. }
  4555. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  4556. int line)
  4557. {
  4558. (void) line;
  4559. (void) file;
  4560. if (mode & 1) { // 1 is CRYPTO_LOCK
  4561. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  4562. } else {
  4563. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  4564. }
  4565. }
  4566. static unsigned long ssl_id_callback(void)
  4567. {
  4568. return (unsigned long) pthread_self();
  4569. }
  4570. #if !defined(NO_SSL_DL)
  4571. static void *load_dll(struct mg_context *ctx, const char *dll_name,
  4572. struct ssl_func *sw)
  4573. {
  4574. union {
  4575. void *p;
  4576. void (*fp)(void);
  4577. } u;
  4578. void *dll_handle;
  4579. struct ssl_func *fp;
  4580. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  4581. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  4582. return NULL;
  4583. }
  4584. for (fp = sw; fp->name != NULL; fp++) {
  4585. #ifdef _WIN32
  4586. // GetProcAddress() returns pointer to function
  4587. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  4588. #else
  4589. // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
  4590. // function pointers. We need to use a union to make a cast.
  4591. u.p = dlsym(dll_handle, fp->name);
  4592. #endif // _WIN32
  4593. if (u.fp == NULL) {
  4594. mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  4595. dlclose(dll_handle);
  4596. return NULL;
  4597. } else {
  4598. fp->ptr = u.fp;
  4599. }
  4600. }
  4601. return dll_handle;
  4602. }
  4603. #endif // NO_SSL_DL
  4604. // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  4605. static int set_ssl_option(struct mg_context *ctx)
  4606. {
  4607. int i, size;
  4608. const char *pem;
  4609. // If PEM file is not specified and the init_ssl callback
  4610. // is not specified, skip SSL initialization.
  4611. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  4612. ctx->callbacks.init_ssl == NULL) {
  4613. return 1;
  4614. }
  4615. #if !defined(NO_SSL_DL)
  4616. ctx->ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  4617. ctx->cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  4618. if (!ctx->ssllib_dll_handle || !ctx->cryptolib_dll_handle) {
  4619. return 0;
  4620. }
  4621. #endif // NO_SSL_DL
  4622. // Initialize SSL library
  4623. SSL_library_init();
  4624. SSL_load_error_strings();
  4625. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  4626. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  4627. return 0;
  4628. }
  4629. // If user callback returned non-NULL, that means that user callback has
  4630. // set up certificate itself. In this case, skip sertificate setting.
  4631. if ((ctx->callbacks.init_ssl == NULL ||
  4632. !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
  4633. (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
  4634. SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  4635. mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
  4636. return 0;
  4637. }
  4638. if (pem != NULL) {
  4639. (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  4640. }
  4641. // Initialize locking callbacks, needed for thread safety.
  4642. // http://www.openssl.org/support/faq.html#PROG1
  4643. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  4644. if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
  4645. mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  4646. return 0;
  4647. }
  4648. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4649. pthread_mutex_init(&ssl_mutexes[i], NULL);
  4650. }
  4651. CRYPTO_set_locking_callback(&ssl_locking_callback);
  4652. CRYPTO_set_id_callback(&ssl_id_callback);
  4653. return 1;
  4654. }
  4655. static void uninitialize_ssl(struct mg_context *ctx)
  4656. {
  4657. int i;
  4658. if (ctx->ssl_ctx != NULL) {
  4659. CRYPTO_set_locking_callback(NULL);
  4660. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4661. pthread_mutex_destroy(&ssl_mutexes[i]);
  4662. }
  4663. CRYPTO_set_locking_callback(NULL);
  4664. CRYPTO_set_id_callback(NULL);
  4665. }
  4666. }
  4667. #endif // !NO_SSL
  4668. static int set_gpass_option(struct mg_context *ctx)
  4669. {
  4670. struct file file = STRUCT_FILE_INITIALIZER;
  4671. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  4672. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  4673. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  4674. return 0;
  4675. }
  4676. return 1;
  4677. }
  4678. static int set_acl_option(struct mg_context *ctx)
  4679. {
  4680. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  4681. }
  4682. static void reset_per_request_attributes(struct mg_connection *conn)
  4683. {
  4684. conn->path_info = NULL;
  4685. conn->num_bytes_sent = conn->consumed_content = 0;
  4686. conn->status_code = -1;
  4687. conn->must_close = conn->request_len = conn->throttle = 0;
  4688. }
  4689. static void close_socket_gracefully(struct mg_connection *conn)
  4690. {
  4691. #if defined(_WIN32)
  4692. char buf[MG_BUF_LEN];
  4693. int n;
  4694. #endif
  4695. struct linger linger;
  4696. // Set linger option to avoid socket hanging out after close. This prevent
  4697. // ephemeral port exhaust problem under high QPS.
  4698. linger.l_onoff = 1;
  4699. linger.l_linger = 1;
  4700. if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
  4701. (char *) &linger, sizeof(linger)) != 0) {
  4702. mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  4703. __func__, strerror(ERRNO));
  4704. }
  4705. // Send FIN to the client
  4706. shutdown(conn->client.sock, SHUT_WR);
  4707. set_non_blocking_mode(conn->client.sock);
  4708. #if defined(_WIN32)
  4709. // Read and discard pending incoming data. If we do not do that and close the
  4710. // socket, the data in the send buffer may be discarded. This
  4711. // behaviour is seen on Windows, when client keeps sending data
  4712. // when server decides to close the connection; then when client
  4713. // does recv() it gets no data back.
  4714. do {
  4715. n = pull(NULL, conn, buf, sizeof(buf));
  4716. } while (n > 0);
  4717. #endif
  4718. // Now we know that our FIN is ACK-ed, safe to close
  4719. closesocket(conn->client.sock);
  4720. }
  4721. static void close_connection(struct mg_connection *conn)
  4722. {
  4723. // call the connection_close callback if assigned
  4724. if (conn->ctx->callbacks.connection_close != NULL)
  4725. conn->ctx->callbacks.connection_close(conn);
  4726. mg_lock(conn);
  4727. conn->must_close = 1;
  4728. #ifndef NO_SSL
  4729. if (conn->ssl != NULL) {
  4730. // Run SSL_shutdown twice to ensure completly close SSL connection
  4731. SSL_shutdown(conn->ssl);
  4732. SSL_free(conn->ssl);
  4733. conn->ssl = NULL;
  4734. }
  4735. #endif
  4736. if (conn->client.sock != INVALID_SOCKET) {
  4737. close_socket_gracefully(conn);
  4738. conn->client.sock = INVALID_SOCKET;
  4739. }
  4740. mg_unlock(conn);
  4741. }
  4742. void mg_close_connection(struct mg_connection *conn)
  4743. {
  4744. #ifndef NO_SSL
  4745. if (conn->client_ssl_ctx != NULL) {
  4746. SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
  4747. }
  4748. #endif
  4749. close_connection(conn);
  4750. (void) pthread_mutex_destroy(&conn->mutex);
  4751. free(conn);
  4752. }
  4753. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  4754. char *ebuf, size_t ebuf_len);
  4755. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  4756. char *ebuf, size_t ebuf_len)
  4757. {
  4758. static struct mg_context fake_ctx;
  4759. struct mg_connection *conn = NULL;
  4760. SOCKET sock;
  4761. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf,
  4762. ebuf_len)) == INVALID_SOCKET) {
  4763. } else if ((conn = (struct mg_connection *)
  4764. calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  4765. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  4766. closesocket(sock);
  4767. #ifndef NO_SSL
  4768. } else if (use_ssl && (conn->client_ssl_ctx =
  4769. SSL_CTX_new(SSLv23_client_method())) == NULL) {
  4770. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  4771. closesocket(sock);
  4772. free(conn);
  4773. conn = NULL;
  4774. #endif // NO_SSL
  4775. } else {
  4776. socklen_t len = sizeof(struct sockaddr);
  4777. conn->buf_size = MAX_REQUEST_SIZE;
  4778. conn->buf = (char *) (conn + 1);
  4779. conn->ctx = &fake_ctx;
  4780. conn->client.sock = sock;
  4781. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  4782. mg_cry(conn, "%s: getsockname() failed: %s",
  4783. __func__, strerror(ERRNO));
  4784. }
  4785. conn->client.is_ssl = use_ssl;
  4786. (void) pthread_mutex_init(&conn->mutex, NULL);
  4787. #ifndef NO_SSL
  4788. if (use_ssl) {
  4789. // SSL_CTX_set_verify call is needed to switch off server certificate
  4790. // checking, which is off by default in OpenSSL and on in yaSSL.
  4791. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  4792. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  4793. }
  4794. #endif
  4795. }
  4796. return conn;
  4797. }
  4798. static int is_valid_uri(const char *uri)
  4799. {
  4800. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4801. // URI can be an asterisk (*) or should start with slash.
  4802. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  4803. }
  4804. static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len)
  4805. {
  4806. const char *cl;
  4807. ebuf[0] = '\0';
  4808. reset_per_request_attributes(conn);
  4809. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  4810. &conn->data_len);
  4811. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  4812. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  4813. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  4814. } else if (conn->request_len <= 0) {
  4815. snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
  4816. } else if (parse_http_message(conn->buf, conn->buf_size,
  4817. &conn->request_info) <= 0) {
  4818. snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
  4819. } else {
  4820. // Request is valid
  4821. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  4822. conn->content_len = strtoll(cl, NULL, 10);
  4823. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  4824. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  4825. conn->content_len = -1;
  4826. } else {
  4827. conn->content_len = 0;
  4828. }
  4829. conn->birth_time = time(NULL);
  4830. }
  4831. return ebuf[0] == '\0';
  4832. }
  4833. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  4834. char *ebuf, size_t ebuf_len,
  4835. const char *fmt, ...)
  4836. {
  4837. struct mg_connection *conn;
  4838. va_list ap;
  4839. va_start(ap, fmt);
  4840. ebuf[0] = '\0';
  4841. if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
  4842. } else if (mg_vprintf(conn, fmt, ap) <= 0) {
  4843. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  4844. } else {
  4845. getreq(conn, ebuf, ebuf_len);
  4846. }
  4847. if (ebuf[0] != '\0' && conn != NULL) {
  4848. mg_close_connection(conn);
  4849. conn = NULL;
  4850. }
  4851. va_end(ap);
  4852. return conn;
  4853. }
  4854. static void process_new_connection(struct mg_connection *conn)
  4855. {
  4856. struct mg_request_info *ri = &conn->request_info;
  4857. int keep_alive_enabled, keep_alive, discard_len;
  4858. char ebuf[100];
  4859. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  4860. keep_alive = 0;
  4861. // Important: on new connection, reset the receiving buffer. Credit goes
  4862. // to crule42.
  4863. conn->data_len = 0;
  4864. do {
  4865. if (!getreq(conn, ebuf, sizeof(ebuf))) {
  4866. send_http_error(conn, 500, "Server Error", "%s", ebuf);
  4867. conn->must_close = 1;
  4868. } else if (!is_valid_uri(conn->request_info.uri)) {
  4869. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  4870. send_http_error(conn, 400, "Bad Request", "%s", ebuf);
  4871. } else if (strcmp(ri->http_version, "1.0") &&
  4872. strcmp(ri->http_version, "1.1")) {
  4873. snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
  4874. send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
  4875. }
  4876. if (ebuf[0] == '\0') {
  4877. handle_request(conn);
  4878. if (conn->ctx->callbacks.end_request != NULL) {
  4879. conn->ctx->callbacks.end_request(conn, conn->status_code);
  4880. }
  4881. log_access(conn);
  4882. }
  4883. if (ri->remote_user != NULL) {
  4884. free((void *) ri->remote_user);
  4885. // Important! When having connections with and without auth
  4886. // would cause double free and then crash
  4887. ri->remote_user = NULL;
  4888. }
  4889. // NOTE(lsm): order is important here. should_keep_alive() call
  4890. // is using parsed request, which will be invalid after memmove's below.
  4891. // Therefore, memorize should_keep_alive() result now for later use
  4892. // in loop exit condition.
  4893. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  4894. conn->content_len >= 0 && should_keep_alive(conn);
  4895. // Discard all buffered data for this request
  4896. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  4897. conn->request_len + conn->content_len < (int64_t) conn->data_len ?
  4898. (int) (conn->request_len + conn->content_len) : conn->data_len;
  4899. assert(discard_len >= 0);
  4900. memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
  4901. conn->data_len -= discard_len;
  4902. assert(conn->data_len >= 0);
  4903. assert(conn->data_len <= conn->buf_size);
  4904. } while (keep_alive);
  4905. }
  4906. // Worker threads take accepted socket from the queue
  4907. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  4908. {
  4909. (void) pthread_mutex_lock(&ctx->mutex);
  4910. DEBUG_TRACE(("going idle"));
  4911. // If the queue is empty, wait. We're idle at this point.
  4912. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  4913. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  4914. }
  4915. // If we're stopping, sq_head may be equal to sq_tail.
  4916. if (ctx->sq_head > ctx->sq_tail) {
  4917. // Copy socket from the queue and increment tail
  4918. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  4919. ctx->sq_tail++;
  4920. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  4921. // Wrap pointers if needed
  4922. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  4923. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  4924. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  4925. }
  4926. }
  4927. (void) pthread_cond_signal(&ctx->sq_empty);
  4928. (void) pthread_mutex_unlock(&ctx->mutex);
  4929. return !ctx->stop_flag;
  4930. }
  4931. static void *worker_thread_run(void *thread_func_param)
  4932. {
  4933. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  4934. struct mg_connection *conn;
  4935. conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  4936. if (conn == NULL) {
  4937. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  4938. } else {
  4939. conn->buf_size = MAX_REQUEST_SIZE;
  4940. conn->buf = (char *) (conn + 1);
  4941. conn->ctx = ctx;
  4942. conn->request_info.user_data = ctx->user_data;
  4943. // Allocate a mutex for this connection to allow communication both
  4944. // within the request handler and from elsewhere in the application
  4945. (void) pthread_mutex_init(&conn->mutex, NULL);
  4946. // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
  4947. // sq_empty condvar to wake up the master waiting in produce_socket()
  4948. while (consume_socket(ctx, &conn->client)) {
  4949. conn->birth_time = time(NULL);
  4950. // Fill in IP, port info early so even if SSL setup below fails,
  4951. // error handler would have the corresponding info.
  4952. // Thanks to Johannes Winkelmann for the patch.
  4953. // TODO(lsm): Fix IPv6 case
  4954. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  4955. memcpy(&conn->request_info.remote_ip,
  4956. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  4957. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  4958. conn->request_info.is_ssl = conn->client.is_ssl;
  4959. if (!conn->client.is_ssl
  4960. #ifndef NO_SSL
  4961. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  4962. #endif
  4963. ) {
  4964. process_new_connection(conn);
  4965. }
  4966. close_connection(conn);
  4967. }
  4968. free(conn);
  4969. }
  4970. // Signal master that we're done with connection and exiting
  4971. (void) pthread_mutex_lock(&ctx->mutex);
  4972. ctx->num_threads--;
  4973. (void) pthread_cond_signal(&ctx->cond);
  4974. assert(ctx->num_threads >= 0);
  4975. (void) pthread_mutex_unlock(&ctx->mutex);
  4976. DEBUG_TRACE(("exiting"));
  4977. return NULL;
  4978. }
  4979. /* Threads have different return types on Windows and Unix. */
  4980. #ifdef _WIN32
  4981. static unsigned __stdcall worker_thread(void *thread_func_param)
  4982. {
  4983. worker_thread_run(thread_func_param);
  4984. return 0;
  4985. }
  4986. #else
  4987. static void *worker_thread(void *thread_func_param)
  4988. {
  4989. worker_thread_run(thread_func_param);
  4990. return NULL;
  4991. }
  4992. #endif /* _WIN32 */
  4993. // Master thread adds accepted socket to a queue
  4994. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  4995. {
  4996. (void) pthread_mutex_lock(&ctx->mutex);
  4997. // If the queue is full, wait
  4998. while (ctx->stop_flag == 0 &&
  4999. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  5000. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  5001. }
  5002. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  5003. // Copy socket to the queue and increment head
  5004. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  5005. ctx->sq_head++;
  5006. DEBUG_TRACE(("queued socket %d", sp->sock));
  5007. }
  5008. (void) pthread_cond_signal(&ctx->sq_full);
  5009. (void) pthread_mutex_unlock(&ctx->mutex);
  5010. }
  5011. static int set_sock_timeout(SOCKET sock, int milliseconds)
  5012. {
  5013. #ifdef _WIN32
  5014. DWORD t = milliseconds;
  5015. #else
  5016. struct timeval t;
  5017. t.tv_sec = milliseconds / 1000;
  5018. t.tv_usec = (milliseconds * 1000) % 1000000;
  5019. #endif
  5020. return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
  5021. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
  5022. }
  5023. static void accept_new_connection(const struct socket *listener,
  5024. struct mg_context *ctx)
  5025. {
  5026. struct socket so;
  5027. char src_addr[IP_ADDR_STR_LEN];
  5028. socklen_t len = sizeof(so.rsa);
  5029. int on = 1;
  5030. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
  5031. } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
  5032. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  5033. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  5034. closesocket(so.sock);
  5035. } else {
  5036. // Put so socket structure into the queue
  5037. DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
  5038. set_close_on_exec(so.sock, fc(ctx));
  5039. so.is_ssl = listener->is_ssl;
  5040. so.ssl_redir = listener->ssl_redir;
  5041. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  5042. mg_cry(fc(ctx), "%s: getsockname() failed: %s",
  5043. __func__, strerror(ERRNO));
  5044. }
  5045. // Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  5046. // is enabled, and client resets the connection, server won't get
  5047. // TCP FIN or RST and will keep the connection open forever. With TCP
  5048. // keep-alive, next keep-alive handshake will figure out that the client
  5049. // is down and will close the server end.
  5050. // Thanks to Igor Klopov who suggested the patch.
  5051. if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
  5052. sizeof(on)) != 0) {
  5053. mg_cry(fc(ctx),
  5054. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  5055. __func__, strerror(ERRNO));
  5056. }
  5057. set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
  5058. produce_socket(ctx, &so);
  5059. }
  5060. }
  5061. static void master_thread_run(void *thread_func_param)
  5062. {
  5063. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  5064. struct pollfd *pfd;
  5065. int i;
  5066. int workerthreadcount;
  5067. // Increase priority of the master thread
  5068. #if defined(_WIN32)
  5069. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  5070. #elif defined(USE_MASTER_THREAD_PRIORITY)
  5071. int min_prio = sched_get_priority_min(SCHED_RR);
  5072. int max_prio = sched_get_priority_max(SCHED_RR);
  5073. if ((min_prio >=0) && (max_prio >= 0) &&
  5074. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  5075. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)
  5076. ) {
  5077. struct sched_param sched_param = {0};
  5078. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  5079. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  5080. }
  5081. #endif
  5082. pfd = (struct pollfd *) calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  5083. while (pfd != NULL && ctx->stop_flag == 0) {
  5084. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5085. pfd[i].fd = ctx->listening_sockets[i].sock;
  5086. pfd[i].events = POLLIN;
  5087. }
  5088. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  5089. for (i = 0; i < ctx->num_listening_sockets; i++) {
  5090. // NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  5091. // successfull poll, and POLLIN is defined as (POLLRDNORM | POLLRDBAND)
  5092. // Therefore, we're checking pfd[i].revents & POLLIN, not
  5093. // pfd[i].revents == POLLIN.
  5094. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  5095. accept_new_connection(&ctx->listening_sockets[i], ctx);
  5096. }
  5097. }
  5098. }
  5099. }
  5100. free(pfd);
  5101. DEBUG_TRACE(("stopping workers"));
  5102. // Stop signal received: somebody called mg_stop. Quit.
  5103. close_all_listening_sockets(ctx);
  5104. // Wakeup workers that are waiting for connections to handle.
  5105. pthread_cond_broadcast(&ctx->sq_full);
  5106. // Wait until all threads finish
  5107. (void) pthread_mutex_lock(&ctx->mutex);
  5108. while (ctx->num_threads > 0) {
  5109. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  5110. }
  5111. (void) pthread_mutex_unlock(&ctx->mutex);
  5112. // Join all worker threads to avoid leaking threads.
  5113. workerthreadcount = ctx->workerthreadcount;
  5114. for (i = 0; i < workerthreadcount; i++) {
  5115. mg_join_thread(ctx->workerthreadids[i]);
  5116. }
  5117. // All threads exited, no sync is needed. Destroy mutex and condvars
  5118. (void) pthread_mutex_destroy(&ctx->mutex);
  5119. (void) pthread_cond_destroy(&ctx->cond);
  5120. (void) pthread_cond_destroy(&ctx->sq_empty);
  5121. (void) pthread_cond_destroy(&ctx->sq_full);
  5122. #if !defined(NO_SSL)
  5123. uninitialize_ssl(ctx);
  5124. #endif
  5125. DEBUG_TRACE(("exiting"));
  5126. // Signal mg_stop() that we're done.
  5127. // WARNING: This must be the very last thing this
  5128. // thread does, as ctx becomes invalid after this line.
  5129. ctx->stop_flag = 2;
  5130. }
  5131. /* Threads have different return types on Windows and Unix. */
  5132. #ifdef _WIN32
  5133. static unsigned __stdcall master_thread(void *thread_func_param)
  5134. {
  5135. master_thread_run(thread_func_param);
  5136. return 0;
  5137. }
  5138. #else
  5139. static void *master_thread(void *thread_func_param)
  5140. {
  5141. master_thread_run(thread_func_param);
  5142. return NULL;
  5143. }
  5144. #endif /* _WIN32 */
  5145. static void free_context(struct mg_context *ctx)
  5146. {
  5147. int i;
  5148. struct mg_request_handler_info *tmp_rh;
  5149. if (ctx == NULL)
  5150. return;
  5151. // Deallocate config parameters
  5152. for (i = 0; i < NUM_OPTIONS; i++) {
  5153. if (ctx->config[i] != NULL)
  5154. #ifdef WIN32
  5155. #pragma warning(suppress: 6001)
  5156. #endif
  5157. free(ctx->config[i]);
  5158. }
  5159. // Deallocate request handlers
  5160. while (ctx->request_handlers) {
  5161. tmp_rh = ctx->request_handlers;
  5162. ctx->request_handlers = tmp_rh->next;
  5163. free(tmp_rh->uri);
  5164. free(tmp_rh);
  5165. }
  5166. #ifndef NO_SSL
  5167. // Deallocate SSL context
  5168. if (ctx->ssl_ctx != NULL) {
  5169. SSL_CTX_free(ctx->ssl_ctx);
  5170. }
  5171. if (ssl_mutexes != NULL) {
  5172. free(ssl_mutexes);
  5173. ssl_mutexes = NULL;
  5174. }
  5175. #endif // !NO_SSL
  5176. // Deallocate worker thread ID array
  5177. if (ctx->workerthreadids != NULL) {
  5178. free(ctx->workerthreadids);
  5179. }
  5180. // Deallocate context itself
  5181. free(ctx);
  5182. }
  5183. void mg_stop(struct mg_context *ctx)
  5184. {
  5185. ctx->stop_flag = 1;
  5186. // Wait until mg_fini() stops
  5187. while (ctx->stop_flag != 2) {
  5188. (void) mg_sleep(10);
  5189. }
  5190. mg_join_thread(ctx->masterthreadid);
  5191. free_context(ctx);
  5192. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5193. (void) WSACleanup();
  5194. #endif // _WIN32
  5195. }
  5196. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  5197. void *user_data,
  5198. const char **options)
  5199. {
  5200. struct mg_context *ctx;
  5201. const char *name, *value, *default_value;
  5202. int i;
  5203. int workerthreadcount;
  5204. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  5205. WSADATA data;
  5206. WSAStartup(MAKEWORD(2,2), &data);
  5207. #pragma warning(suppress: 28125)
  5208. InitializeCriticalSection(&global_log_file_lock);
  5209. #endif // _WIN32
  5210. // Allocate context and initialize reasonable general case defaults.
  5211. // TODO(lsm): do proper error handling here.
  5212. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  5213. return NULL;
  5214. }
  5215. ctx->callbacks = *callbacks;
  5216. ctx->user_data = user_data;
  5217. ctx->request_handlers = 0;
  5218. while (options && (name = *options++) != NULL) {
  5219. if ((i = get_option_index(name)) == -1) {
  5220. mg_cry(fc(ctx), "Invalid option: %s", name);
  5221. free_context(ctx);
  5222. return NULL;
  5223. } else if ((value = *options++) == NULL) {
  5224. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  5225. free_context(ctx);
  5226. return NULL;
  5227. }
  5228. if (ctx->config[i] != NULL) {
  5229. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  5230. free(ctx->config[i]);
  5231. }
  5232. ctx->config[i] = mg_strdup(value);
  5233. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  5234. }
  5235. // Set default value if needed
  5236. for (i = 0; config_options[i * 2] != NULL; i++) {
  5237. default_value = config_options[i * 2 + 1];
  5238. if (ctx->config[i] == NULL && default_value != NULL) {
  5239. ctx->config[i] = mg_strdup(default_value);
  5240. }
  5241. }
  5242. // NOTE(lsm): order is important here. SSL certificates must
  5243. // be initialized before listening ports. UID must be set last.
  5244. if (!set_gpass_option(ctx) ||
  5245. #if !defined(NO_SSL)
  5246. !set_ssl_option(ctx) ||
  5247. #endif
  5248. !set_ports_option(ctx) ||
  5249. #if !defined(_WIN32)
  5250. !set_uid_option(ctx) ||
  5251. #endif
  5252. !set_acl_option(ctx)) {
  5253. free_context(ctx);
  5254. return NULL;
  5255. }
  5256. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  5257. // Ignore SIGPIPE signal, so if browser cancels the request, it
  5258. // won't kill the whole process.
  5259. (void) signal(SIGPIPE, SIG_IGN);
  5260. #endif // !_WIN32
  5261. (void) pthread_mutex_init(&ctx->mutex, NULL);
  5262. (void) pthread_cond_init(&ctx->cond, NULL);
  5263. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  5264. (void) pthread_cond_init(&ctx->sq_full, NULL);
  5265. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  5266. if (workerthreadcount > MAX_WORKER_THREADS) {
  5267. mg_cry(fc(ctx), "Too many worker threads");
  5268. free_context(ctx);
  5269. return NULL;
  5270. }
  5271. if (workerthreadcount > 0) {
  5272. ctx->workerthreadcount = workerthreadcount;
  5273. ctx->workerthreadids = calloc(workerthreadcount, sizeof(pthread_t));
  5274. if (ctx->workerthreadids == NULL) {
  5275. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  5276. free_context(ctx);
  5277. return NULL;
  5278. }
  5279. }
  5280. // Start master (listening) thread
  5281. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  5282. // Start worker threads
  5283. for (i = 0; i < workerthreadcount; i++) {
  5284. (void) pthread_mutex_lock(&ctx->mutex);
  5285. ctx->num_threads++;
  5286. (void) pthread_mutex_unlock(&ctx->mutex);
  5287. if (mg_start_thread_with_id(worker_thread, ctx,
  5288. &ctx->workerthreadids[i]) != 0) {
  5289. (void) pthread_mutex_lock(&ctx->mutex);
  5290. ctx->num_threads--;
  5291. (void) pthread_mutex_unlock(&ctx->mutex);
  5292. mg_cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
  5293. }
  5294. }
  5295. return ctx;
  5296. }