civetweb.c 326 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #ifdef __linux__
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t));
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t clock_start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (clock_start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. clock_start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - clock_start_time)
  150. * (double)timebase_ifo.numer
  151. / (double)timebase_ifo.denom);
  152. t->tv_sec = now / 1000000000;
  153. t->tv_nsec = now % 1000000000;
  154. return 0;
  155. }
  156. return -1; /* EINVAL - Clock ID is unknown */
  157. }
  158. #endif
  159. #include <time.h>
  160. #include <stdlib.h>
  161. #include <stdarg.h>
  162. #include <assert.h>
  163. #include <string.h>
  164. #include <ctype.h>
  165. #include <limits.h>
  166. #include <stddef.h>
  167. #include <stdio.h>
  168. #ifndef MAX_WORKER_THREADS
  169. #define MAX_WORKER_THREADS (1024 * 64)
  170. #endif
  171. #ifndef SOCKET_TIMEOUT_QUANTUM
  172. #define SOCKET_TIMEOUT_QUANTUM (10000)
  173. #endif
  174. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. typedef long off_t;
  201. #define errno ((int)(GetLastError()))
  202. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  203. #endif /* _WIN32_WCE */
  204. #define MAKEUQUAD(lo, hi) \
  205. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  206. #define RATE_DIFF (10000000) /* 100 nsecs */
  207. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  208. #define SYS2UNIX_TIME(lo, hi) \
  209. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  210. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  211. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  212. * Also use _strtoui64 on modern M$ compilers */
  213. #if defined(_MSC_VER)
  214. #if (_MSC_VER < 1300)
  215. #define STRX(x) #x
  216. #define STR(x) STRX(x)
  217. #define __func__ __FILE__ ":" STR(__LINE__)
  218. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  219. #define strtoll(x, y, z) (_atoi64(x))
  220. #else
  221. #define __func__ __FUNCTION__
  222. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  223. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  224. #endif
  225. #endif /* _MSC_VER */
  226. #define ERRNO ((int)(GetLastError()))
  227. #define NO_SOCKLEN_T
  228. #define SSL_LIB "ssleay32.dll"
  229. #define CRYPTO_LIB "libeay32.dll"
  230. #define O_NONBLOCK (0)
  231. #ifndef W_OK
  232. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  233. #endif
  234. #if !defined(EWOULDBLOCK)
  235. #define EWOULDBLOCK WSAEWOULDBLOCK
  236. #endif /* !EWOULDBLOCK */
  237. #define _POSIX_
  238. #define INT64_FMT "I64d"
  239. #define UINT64_FMT "I64u"
  240. #define WINCDECL __cdecl
  241. #define SHUT_RD (0)
  242. #define SHUT_WR (1)
  243. #define SHUT_BOTH (2)
  244. #define vsnprintf_impl _vsnprintf
  245. #define access _access
  246. #define mg_sleep(x) (Sleep(x))
  247. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  248. #ifndef popen
  249. #define popen(x, y) (_popen(x, y))
  250. #endif
  251. #ifndef pclose
  252. #define pclose(x) (_pclose(x))
  253. #endif
  254. #define close(x) (_close(x))
  255. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  256. #define RTLD_LAZY (0)
  257. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  258. #define fdopen(x, y) (_fdopen((x), (y)))
  259. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  260. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  261. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  262. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  263. #define sleep(x) (Sleep((x)*1000))
  264. #define rmdir(x) (_rmdir(x))
  265. #if !defined(fileno)
  266. #define fileno(x) (_fileno(x))
  267. #endif /* !fileno MINGW #defines fileno */
  268. typedef HANDLE pthread_mutex_t;
  269. typedef DWORD pthread_key_t;
  270. typedef HANDLE pthread_t;
  271. typedef struct {
  272. CRITICAL_SECTION threadIdSec;
  273. int waitingthreadcount; /* The number of threads queued. */
  274. pthread_t *waitingthreadhdls; /* The thread handles. */
  275. } pthread_cond_t;
  276. #ifndef __clockid_t_defined
  277. typedef DWORD clockid_t;
  278. #endif
  279. #ifndef CLOCK_MONOTONIC
  280. #define CLOCK_MONOTONIC (1)
  281. #endif
  282. #ifndef CLOCK_REALTIME
  283. #define CLOCK_REALTIME (2)
  284. #endif
  285. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  286. #define _TIMESPEC_DEFINED
  287. #endif
  288. #ifndef _TIMESPEC_DEFINED
  289. struct timespec {
  290. time_t tv_sec; /* seconds */
  291. long tv_nsec; /* nanoseconds */
  292. };
  293. #endif
  294. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  295. static int pthread_mutex_lock(pthread_mutex_t *);
  296. static int pthread_mutex_unlock(pthread_mutex_t *);
  297. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  298. struct file;
  299. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  300. #if defined(HAVE_STDINT)
  301. #include <stdint.h>
  302. #else
  303. typedef unsigned char uint8_t;
  304. typedef unsigned short uint16_t;
  305. typedef unsigned int uint32_t;
  306. typedef unsigned __int64 uint64_t;
  307. typedef __int64 int64_t;
  308. #define INT64_MAX (9223372036854775807)
  309. #endif /* HAVE_STDINT */
  310. /* POSIX dirent interface */
  311. struct dirent {
  312. char d_name[PATH_MAX];
  313. };
  314. typedef struct DIR {
  315. HANDLE handle;
  316. WIN32_FIND_DATAW info;
  317. struct dirent result;
  318. } DIR;
  319. #if defined(_WIN32) && !defined(POLLIN)
  320. #ifndef HAVE_POLL
  321. struct pollfd {
  322. SOCKET fd;
  323. short events;
  324. short revents;
  325. };
  326. #define POLLIN (0x0300)
  327. #endif
  328. #endif
  329. /* Mark required libraries */
  330. #if defined(_MSC_VER)
  331. #pragma comment(lib, "Ws2_32.lib")
  332. #endif
  333. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  334. block */
  335. #include <sys/wait.h>
  336. #include <sys/socket.h>
  337. #include <sys/poll.h>
  338. #include <netinet/in.h>
  339. #include <arpa/inet.h>
  340. #include <sys/time.h>
  341. #include <sys/utsname.h>
  342. #include <stdint.h>
  343. #include <inttypes.h>
  344. #include <netdb.h>
  345. typedef const void *SOCK_OPT_TYPE;
  346. #if defined(ANDROID)
  347. typedef unsigned short int in_port_t;
  348. #endif
  349. #include <pwd.h>
  350. #include <unistd.h>
  351. #include <grp.h>
  352. #include <dirent.h>
  353. #define vsnprintf_impl vsnprintf
  354. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  355. #include <dlfcn.h>
  356. #endif
  357. #include <pthread.h>
  358. #if defined(__MACH__)
  359. #define SSL_LIB "libssl.dylib"
  360. #define CRYPTO_LIB "libcrypto.dylib"
  361. #else
  362. #if !defined(SSL_LIB)
  363. #define SSL_LIB "libssl.so"
  364. #endif
  365. #if !defined(CRYPTO_LIB)
  366. #define CRYPTO_LIB "libcrypto.so"
  367. #endif
  368. #endif
  369. #ifndef O_BINARY
  370. #define O_BINARY (0)
  371. #endif /* O_BINARY */
  372. #define closesocket(a) (close(a))
  373. #define mg_mkdir(x, y) (mkdir(x, y))
  374. #define mg_remove(x) (remove(x))
  375. #define mg_sleep(x) (usleep((x)*1000))
  376. #define ERRNO (errno)
  377. #define INVALID_SOCKET (-1)
  378. #define INT64_FMT PRId64
  379. #define UINT64_FMT PRIu64
  380. typedef int SOCKET;
  381. #define WINCDECL
  382. #if defined(__hpux)
  383. /* HPUX 11 does not have monotonic, fall back to realtime */
  384. #ifndef CLOCK_MONOTONIC
  385. #define CLOCK_MONOTONIC CLOCK_REALTIME
  386. #endif
  387. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  388. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  389. * the prototypes use int* rather than socklen_t* which matches the
  390. * actual library expectation. When called with the wrong size arg
  391. * accept() returns a zero client inet addr and check_acl() always
  392. * fails. Since socklen_t is widely used below, just force replace
  393. * their typedef with int. - DTL
  394. */
  395. #define socklen_t int
  396. #endif /* hpux */
  397. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  398. block */
  399. /* va_copy should always be a macro, C99 and C++11 - DTL */
  400. #ifndef va_copy
  401. #define va_copy(x, y) ((x) = (y))
  402. #endif
  403. #ifdef _WIN32
  404. /* Create substitutes for POSIX functions in Win32. */
  405. #if defined(__MINGW32__)
  406. /* Show no warning in case system functions are not used. */
  407. #pragma GCC diagnostic push
  408. #pragma GCC diagnostic ignored "-Wunused-function"
  409. #endif
  410. static CRITICAL_SECTION global_log_file_lock;
  411. static DWORD
  412. pthread_self(void)
  413. {
  414. return GetCurrentThreadId();
  415. }
  416. static int
  417. pthread_key_create(
  418. pthread_key_t *key,
  419. void (*_ignored)(void *) /* destructor not supported for Windows */
  420. )
  421. {
  422. (void)_ignored;
  423. if ((key != 0)) {
  424. *key = TlsAlloc();
  425. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  426. }
  427. return -2;
  428. }
  429. static int
  430. pthread_key_delete(pthread_key_t key)
  431. {
  432. return TlsFree(key) ? 0 : 1;
  433. }
  434. static int
  435. pthread_setspecific(pthread_key_t key, void *value)
  436. {
  437. return TlsSetValue(key, value) ? 0 : 1;
  438. }
  439. static void *
  440. pthread_getspecific(pthread_key_t key)
  441. {
  442. return TlsGetValue(key);
  443. }
  444. #if defined(__MINGW32__)
  445. /* Enable unused function warning again */
  446. #pragma GCC diagnostic pop
  447. #endif
  448. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  449. #else
  450. static pthread_mutexattr_t pthread_mutex_attr;
  451. #endif /* _WIN32 */
  452. #include "civetweb.h"
  453. #define PASSWORDS_FILE_NAME ".htpasswd"
  454. #define CGI_ENVIRONMENT_SIZE (4096)
  455. #define MAX_CGI_ENVIR_VARS (256)
  456. #define MG_BUF_LEN (8192)
  457. #ifndef MAX_REQUEST_SIZE
  458. #define MAX_REQUEST_SIZE (16384)
  459. #endif
  460. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  461. "request size length must be a positive number");
  462. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  463. #if !defined(DEBUG_TRACE)
  464. #if defined(DEBUG)
  465. static void DEBUG_TRACE_FUNC(const char *func,
  466. unsigned line,
  467. PRINTF_FORMAT_STRING(const char *fmt),
  468. ...) PRINTF_ARGS(3, 4);
  469. static void
  470. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  471. {
  472. va_list args;
  473. flockfile(stdout);
  474. printf("*** %lu.%p.%s.%u: ",
  475. (unsigned long)time(NULL),
  476. (void *)pthread_self(),
  477. func,
  478. line);
  479. va_start(args, fmt);
  480. vprintf(fmt, args);
  481. va_end(args);
  482. putchar('\n');
  483. fflush(stdout);
  484. funlockfile(stdout);
  485. }
  486. #define DEBUG_TRACE(fmt, ...) \
  487. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  488. #else
  489. #define DEBUG_TRACE(fmt, ...) \
  490. do { \
  491. } while (0)
  492. #endif /* DEBUG */
  493. #endif /* DEBUG_TRACE */
  494. #if defined(MEMORY_DEBUGGING)
  495. unsigned long mg_memory_debug_blockCount = 0;
  496. unsigned long mg_memory_debug_totalMemUsed = 0;
  497. static void *
  498. mg_malloc_ex(size_t size, const char *file, unsigned line)
  499. {
  500. void *data = malloc(size + sizeof(size_t));
  501. void *memory = 0;
  502. char mallocStr[256];
  503. if (data) {
  504. *(size_t *)data = size;
  505. mg_memory_debug_totalMemUsed += size;
  506. mg_memory_debug_blockCount++;
  507. memory = (void *)(((char *)data) + sizeof(size_t));
  508. }
  509. sprintf(mallocStr,
  510. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  511. memory,
  512. (unsigned long)size,
  513. mg_memory_debug_totalMemUsed,
  514. mg_memory_debug_blockCount,
  515. file,
  516. line);
  517. #if defined(_WIN32)
  518. OutputDebugStringA(mallocStr);
  519. #else
  520. DEBUG_TRACE("%s", mallocStr);
  521. #endif
  522. return memory;
  523. }
  524. static void *
  525. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  526. {
  527. void *data = mg_malloc_ex(size * count, file, line);
  528. if (data) {
  529. memset(data, 0, size);
  530. }
  531. return data;
  532. }
  533. static void
  534. mg_free_ex(void *memory, const char *file, unsigned line)
  535. {
  536. char mallocStr[256];
  537. void *data = (void *)(((char *)memory) - sizeof(size_t));
  538. size_t size;
  539. if (memory) {
  540. size = *(size_t *)data;
  541. mg_memory_debug_totalMemUsed -= size;
  542. mg_memory_debug_blockCount--;
  543. sprintf(mallocStr,
  544. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  545. memory,
  546. (unsigned long)size,
  547. mg_memory_debug_totalMemUsed,
  548. mg_memory_debug_blockCount,
  549. file,
  550. line);
  551. #if defined(_WIN32)
  552. OutputDebugStringA(mallocStr);
  553. #else
  554. DEBUG_TRACE("%s", mallocStr);
  555. #endif
  556. free(data);
  557. }
  558. }
  559. static void *
  560. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  561. {
  562. char mallocStr[256];
  563. void *data;
  564. void *_realloc;
  565. size_t oldsize;
  566. if (newsize) {
  567. if (memory) {
  568. data = (void *)(((char *)memory) - sizeof(size_t));
  569. oldsize = *(size_t *)data;
  570. _realloc = realloc(data, newsize + sizeof(size_t));
  571. if (_realloc) {
  572. data = _realloc;
  573. mg_memory_debug_totalMemUsed -= oldsize;
  574. sprintf(mallocStr,
  575. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  576. memory,
  577. (unsigned long)oldsize,
  578. mg_memory_debug_totalMemUsed,
  579. mg_memory_debug_blockCount,
  580. file,
  581. line);
  582. #if defined(_WIN32)
  583. OutputDebugStringA(mallocStr);
  584. #else
  585. DEBUG_TRACE("%s", mallocStr);
  586. #endif
  587. mg_memory_debug_totalMemUsed += newsize;
  588. sprintf(mallocStr,
  589. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  590. memory,
  591. (unsigned long)newsize,
  592. mg_memory_debug_totalMemUsed,
  593. mg_memory_debug_blockCount,
  594. file,
  595. line);
  596. #if defined(_WIN32)
  597. OutputDebugStringA(mallocStr);
  598. #else
  599. DEBUG_TRACE("%s", mallocStr);
  600. #endif
  601. *(size_t *)data = newsize;
  602. data = (void *)(((char *)data) + sizeof(size_t));
  603. } else {
  604. #if defined(_WIN32)
  605. OutputDebugStringA("MEM: realloc failed\n");
  606. #else
  607. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  608. #endif
  609. return _realloc;
  610. }
  611. } else {
  612. data = mg_malloc_ex(newsize, file, line);
  613. }
  614. } else {
  615. data = 0;
  616. mg_free_ex(memory, file, line);
  617. }
  618. return data;
  619. }
  620. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  621. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  622. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  623. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  624. #else
  625. static __inline void *
  626. mg_malloc(size_t a)
  627. {
  628. return malloc(a);
  629. }
  630. static __inline void *
  631. mg_calloc(size_t a, size_t b)
  632. {
  633. return calloc(a, b);
  634. }
  635. static __inline void *
  636. mg_realloc(void *a, size_t b)
  637. {
  638. return realloc(a, b);
  639. }
  640. static __inline void
  641. mg_free(void *a)
  642. {
  643. free(a);
  644. }
  645. #endif
  646. static void mg_vsnprintf(const struct mg_connection *conn,
  647. int *truncated,
  648. char *buf,
  649. size_t buflen,
  650. const char *fmt,
  651. va_list ap);
  652. static void mg_snprintf(const struct mg_connection *conn,
  653. int *truncated,
  654. char *buf,
  655. size_t buflen,
  656. PRINTF_FORMAT_STRING(const char *fmt),
  657. ...) PRINTF_ARGS(5, 6);
  658. /* This following lines are just meant as a reminder to use the mg-functions
  659. * for memory management */
  660. #ifdef malloc
  661. #undef malloc
  662. #endif
  663. #ifdef calloc
  664. #undef calloc
  665. #endif
  666. #ifdef realloc
  667. #undef realloc
  668. #endif
  669. #ifdef free
  670. #undef free
  671. #endif
  672. #ifdef snprintf
  673. #undef snprintf
  674. #endif
  675. #ifdef vsnprintf
  676. #undef vsnprintf
  677. #endif
  678. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  679. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  680. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  681. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  682. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  683. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  684. * but this define only works well for Windows. */
  685. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  686. #endif
  687. #define MD5_STATIC static
  688. #include "md5.inl"
  689. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  690. #ifdef NO_SOCKLEN_T
  691. typedef int socklen_t;
  692. #endif /* NO_SOCKLEN_T */
  693. #define _DARWIN_UNLIMITED_SELECT
  694. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  695. #if !defined(MSG_NOSIGNAL)
  696. #define MSG_NOSIGNAL (0)
  697. #endif
  698. #if !defined(SOMAXCONN)
  699. #define SOMAXCONN (100)
  700. #endif
  701. /* Size of the accepted socket queue */
  702. #if !defined(MGSQLEN)
  703. #define MGSQLEN (20)
  704. #endif
  705. #if defined(NO_SSL_DL)
  706. #include <openssl/ssl.h>
  707. #include <openssl/err.h>
  708. #include <openssl/crypto.h>
  709. #include <openssl/x509.h>
  710. #include <openssl/pem.h>
  711. #else
  712. /* SSL loaded dynamically from DLL.
  713. * I put the prototypes here to be independent from OpenSSL source
  714. * installation. */
  715. typedef struct ssl_st SSL;
  716. typedef struct ssl_method_st SSL_METHOD;
  717. typedef struct ssl_ctx_st SSL_CTX;
  718. typedef struct x509_store_ctx_st X509_STORE_CTX;
  719. #define SSL_CTRL_OPTIONS (32)
  720. #define SSL_CTRL_CLEAR_OPTIONS (77)
  721. #define SSL_VERIFY_NONE (0)
  722. #define SSL_VERIFY_PEER (1)
  723. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  724. #define SSL_VERIFY_CLIENT_ONCE (4)
  725. #define SSL_OP_ALL (0x80000BFFL)
  726. #define SSL_OP_NO_SSLv2 (0x01000000L)
  727. #define SSL_OP_NO_SSLv3 (0x02000000L)
  728. #define SSL_OP_NO_TLSv1 (0x04000000L)
  729. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  730. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  731. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  732. struct ssl_func {
  733. const char *name; /* SSL function name */
  734. void (*ptr)(void); /* Function pointer */
  735. };
  736. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  737. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  738. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  739. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  740. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  741. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  742. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  743. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  744. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  745. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  746. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  747. #define SSL_CTX_use_PrivateKey_file \
  748. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  749. #define SSL_CTX_use_certificate_file \
  750. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  751. #define SSL_CTX_set_default_passwd_cb \
  752. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  753. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  754. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  755. #define SSL_CTX_use_certificate_chain_file \
  756. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  757. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  758. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  759. #define SSL_CTX_set_verify \
  760. (*(void (*)(SSL_CTX *, \
  761. int, \
  762. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  763. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  764. #define SSL_CTX_load_verify_locations \
  765. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  766. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  767. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  768. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  769. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  770. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  771. #define SSL_CIPHER_get_name \
  772. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  773. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  774. #define SSL_CTX_set_session_id_context \
  775. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  776. #define SSL_CTX_ctrl \
  777. (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  778. #define SSL_CTX_set_cipher_list \
  779. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  780. #define SSL_CTX_set_options(ctx,op) \
  781. SSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
  782. #define SSL_CTX_clear_options(ctx,op) \
  783. SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_OPTIONS,(op),NULL)
  784. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  785. #define CRYPTO_set_locking_callback \
  786. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  787. #define CRYPTO_set_id_callback \
  788. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  789. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  790. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  791. /* set_ssl_option() function updates this array.
  792. * It loads SSL library dynamically and changes NULLs to the actual addresses
  793. * of respective functions. The macros above (like SSL_connect()) are really
  794. * just calling these functions indirectly via the pointer. */
  795. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  796. {"SSL_accept", NULL},
  797. {"SSL_connect", NULL},
  798. {"SSL_read", NULL},
  799. {"SSL_write", NULL},
  800. {"SSL_get_error", NULL},
  801. {"SSL_set_fd", NULL},
  802. {"SSL_new", NULL},
  803. {"SSL_CTX_new", NULL},
  804. {"SSLv23_server_method", NULL},
  805. {"SSL_library_init", NULL},
  806. {"SSL_CTX_use_PrivateKey_file", NULL},
  807. {"SSL_CTX_use_certificate_file", NULL},
  808. {"SSL_CTX_set_default_passwd_cb", NULL},
  809. {"SSL_CTX_free", NULL},
  810. {"SSL_load_error_strings", NULL},
  811. {"SSL_CTX_use_certificate_chain_file", NULL},
  812. {"SSLv23_client_method", NULL},
  813. {"SSL_pending", NULL},
  814. {"SSL_CTX_set_verify", NULL},
  815. {"SSL_shutdown", NULL},
  816. {"SSL_CTX_load_verify_locations", NULL},
  817. {"SSL_CTX_set_default_verify_paths", NULL},
  818. {"SSL_CTX_set_verify_depth", NULL},
  819. {"SSL_get_peer_certificate", NULL},
  820. {"SSL_get_version", NULL},
  821. {"SSL_get_current_cipher", NULL},
  822. {"SSL_CIPHER_get_name", NULL},
  823. {"SSL_CTX_check_private_key", NULL},
  824. {"SSL_CTX_set_session_id_context", NULL},
  825. {"SSL_CTX_ctrl", NULL},
  826. {"SSL_CTX_set_cipher_list", NULL},
  827. {NULL, NULL}};
  828. /* Similar array as ssl_sw. These functions could be located in different
  829. * lib. */
  830. #if !defined(NO_SSL)
  831. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  832. {"CRYPTO_set_locking_callback", NULL},
  833. {"CRYPTO_set_id_callback", NULL},
  834. {"ERR_get_error", NULL},
  835. {"ERR_error_string", NULL},
  836. {NULL, NULL}};
  837. #endif /* NO_SSL */
  838. #endif /* NO_SSL_DL */
  839. static const char *month_names[] = {"Jan",
  840. "Feb",
  841. "Mar",
  842. "Apr",
  843. "May",
  844. "Jun",
  845. "Jul",
  846. "Aug",
  847. "Sep",
  848. "Oct",
  849. "Nov",
  850. "Dec"};
  851. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  852. * union u. */
  853. union usa {
  854. struct sockaddr sa;
  855. struct sockaddr_in sin;
  856. #if defined(USE_IPV6)
  857. struct sockaddr_in6 sin6;
  858. #endif
  859. };
  860. /* Describes a string (chunk of memory). */
  861. struct vec {
  862. const char *ptr;
  863. size_t len;
  864. };
  865. struct file {
  866. uint64_t size;
  867. time_t last_modified;
  868. FILE *fp;
  869. const char *membuf; /* Non-NULL if file data is in memory */
  870. int is_directory;
  871. int gzipped; /* set to 1 if the content is gzipped
  872. * in which case we need a content-encoding: gzip header */
  873. };
  874. #define STRUCT_FILE_INITIALIZER \
  875. { \
  876. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  877. }
  878. /* Describes listening socket, or socket which was accept()-ed by the master
  879. * thread and queued for future handling by the worker thread. */
  880. struct socket {
  881. SOCKET sock; /* Listening socket */
  882. union usa lsa; /* Local socket address */
  883. union usa rsa; /* Remote socket address */
  884. unsigned char is_ssl; /* Is port SSL-ed */
  885. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  886. * port */
  887. };
  888. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  889. enum {
  890. CGI_EXTENSIONS,
  891. CGI_ENVIRONMENT,
  892. PUT_DELETE_PASSWORDS_FILE,
  893. CGI_INTERPRETER,
  894. PROTECT_URI,
  895. AUTHENTICATION_DOMAIN,
  896. SSI_EXTENSIONS,
  897. THROTTLE,
  898. ACCESS_LOG_FILE,
  899. ENABLE_DIRECTORY_LISTING,
  900. ERROR_LOG_FILE,
  901. GLOBAL_PASSWORDS_FILE,
  902. INDEX_FILES,
  903. ENABLE_KEEP_ALIVE,
  904. ACCESS_CONTROL_LIST,
  905. EXTRA_MIME_TYPES,
  906. LISTENING_PORTS,
  907. DOCUMENT_ROOT,
  908. SSL_CERTIFICATE,
  909. NUM_THREADS,
  910. RUN_AS_USER,
  911. REWRITE,
  912. HIDE_FILES,
  913. REQUEST_TIMEOUT,
  914. SSL_DO_VERIFY_PEER,
  915. SSL_CA_PATH,
  916. SSL_CA_FILE,
  917. SSL_VERIFY_DEPTH,
  918. SSL_DEFAULT_VERIFY_PATHS,
  919. SSL_CIPHER_LIST,
  920. SSL_PROTOCOL_VERSION,
  921. #if defined(USE_WEBSOCKET)
  922. WEBSOCKET_TIMEOUT,
  923. #endif
  924. DECODE_URL,
  925. #if defined(USE_LUA)
  926. LUA_PRELOAD_FILE,
  927. LUA_SCRIPT_EXTENSIONS,
  928. LUA_SERVER_PAGE_EXTENSIONS,
  929. #endif
  930. #if defined(USE_DUKTAPE)
  931. DUKTAPE_SCRIPT_EXTENSIONS,
  932. #endif
  933. #if defined(USE_WEBSOCKET)
  934. WEBSOCKET_ROOT,
  935. #endif
  936. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  937. LUA_WEBSOCKET_EXTENSIONS,
  938. #endif
  939. ACCESS_CONTROL_ALLOW_ORIGIN,
  940. ERROR_PAGES,
  941. NUM_OPTIONS
  942. };
  943. /* Config option name, config types, default value */
  944. static struct mg_option config_options[] = {
  945. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  946. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  947. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  948. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  949. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  950. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  951. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  952. {"throttle", CONFIG_TYPE_STRING, NULL},
  953. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  954. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  955. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  956. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  957. {"index_files",
  958. CONFIG_TYPE_STRING,
  959. #ifdef USE_LUA
  960. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  961. "index.shtml,index.php"},
  962. #else
  963. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  964. #endif
  965. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  966. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  967. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  968. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  969. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  970. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  971. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  972. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  973. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  974. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  975. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  976. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  977. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  978. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  979. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  980. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  981. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  982. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  983. #if defined(USE_WEBSOCKET)
  984. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  985. #endif
  986. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  987. #if defined(USE_LUA)
  988. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  989. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  990. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  991. #endif
  992. #if defined(USE_DUKTAPE)
  993. {"_experimental_duktape_script_pattern",
  994. CONFIG_TYPE_EXT_PATTERN,
  995. "**.ssjs$"}, /* TODO: redefine parameter */
  996. #endif
  997. #if defined(USE_WEBSOCKET)
  998. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  999. #endif
  1000. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1001. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1002. #endif
  1003. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1004. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1005. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1006. /* Check if the config_options and the corresponding enum have compatible
  1007. * sizes. */
  1008. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1009. == (NUM_OPTIONS + 1),
  1010. "config_options and enum not sync");
  1011. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1012. struct mg_handler_info {
  1013. /* Name/Pattern of the URI. */
  1014. char *uri;
  1015. size_t uri_len;
  1016. /* handler type */
  1017. int handler_type;
  1018. /* Handler for http/https or authorization requests. */
  1019. mg_request_handler handler;
  1020. /* Handler for ws/wss (websocket) requests. */
  1021. mg_websocket_connect_handler connect_handler;
  1022. mg_websocket_ready_handler ready_handler;
  1023. mg_websocket_data_handler data_handler;
  1024. mg_websocket_close_handler close_handler;
  1025. /* Handler for authorization requests */
  1026. mg_authorization_handler auth_handler;
  1027. /* User supplied argument for the handler function. */
  1028. void *cbdata;
  1029. /* next handler in a linked list */
  1030. struct mg_handler_info *next;
  1031. };
  1032. struct mg_context {
  1033. volatile int stop_flag; /* Should we stop event loop */
  1034. SSL_CTX *ssl_ctx; /* SSL context */
  1035. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1036. struct mg_callbacks callbacks; /* User-defined callback function */
  1037. void *user_data; /* User-defined data */
  1038. int context_type; /* 1 = server context, 2 = client context */
  1039. struct socket *listening_sockets;
  1040. in_port_t *listening_ports;
  1041. unsigned int num_listening_sockets;
  1042. volatile int
  1043. running_worker_threads; /* Number of currently running worker threads */
  1044. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1045. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1046. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1047. volatile int sq_head; /* Head of the socket queue */
  1048. volatile int sq_tail; /* Tail of the socket queue */
  1049. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1050. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1051. pthread_t masterthreadid; /* The master thread ID */
  1052. unsigned int
  1053. cfg_worker_threads; /* The number of configured worker threads. */
  1054. pthread_t *workerthreadids; /* The worker thread IDs */
  1055. time_t start_time; /* Server start time, used for authentication */
  1056. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1057. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1058. unsigned long nonce_count; /* Used nonces, used for authentication */
  1059. char *systemName; /* What operating system is running */
  1060. /* linked list of uri handlers */
  1061. struct mg_handler_info *handlers;
  1062. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1063. /* linked list of shared lua websockets */
  1064. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1065. #endif
  1066. #ifdef USE_TIMERS
  1067. struct ttimers *timers;
  1068. #endif
  1069. };
  1070. struct mg_connection {
  1071. struct mg_request_info request_info;
  1072. struct mg_context *ctx;
  1073. SSL *ssl; /* SSL descriptor */
  1074. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1075. struct socket client; /* Connected client */
  1076. time_t conn_birth_time; /* Time (wall clock) when connection was
  1077. * established */
  1078. struct timespec req_time; /* Time (since system start) when the request
  1079. * was received */
  1080. int64_t num_bytes_sent; /* Total bytes sent to client */
  1081. int64_t content_len; /* Content-Length header value */
  1082. int64_t consumed_content; /* How many bytes of content have been read */
  1083. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1084. * data available, 2: all data read */
  1085. size_t chunk_remainder; /* Unread data from the last chunk */
  1086. char *buf; /* Buffer for received data */
  1087. char *path_info; /* PATH_INFO part of the URL */
  1088. int must_close; /* 1 if connection must be closed */
  1089. int in_error_handler; /* 1 if in handler for user defined error
  1090. * pages */
  1091. int internal_error; /* 1 if an error occured while processing the
  1092. * request */
  1093. int buf_size; /* Buffer size */
  1094. int request_len; /* Size of the request + headers in a buffer */
  1095. int data_len; /* Total size of data in a buffer */
  1096. int status_code; /* HTTP reply status code, e.g. 200 */
  1097. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1098. * throttle */
  1099. time_t last_throttle_time; /* Last time throttled data was sent */
  1100. int64_t last_throttle_bytes; /* Bytes sent this second */
  1101. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1102. * atomic transmissions for websockets */
  1103. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1104. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1105. #endif
  1106. };
  1107. static pthread_key_t sTlsKey; /* Thread local storage index */
  1108. static int sTlsInit = 0;
  1109. static int thread_idx_max = 0;
  1110. struct mg_workerTLS {
  1111. int is_master;
  1112. unsigned long thread_idx;
  1113. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1114. HANDLE pthread_cond_helper_mutex;
  1115. #endif
  1116. };
  1117. /* Directory entry */
  1118. struct de {
  1119. struct mg_connection *conn;
  1120. char *file_name;
  1121. struct file file;
  1122. };
  1123. #if defined(USE_WEBSOCKET)
  1124. static int is_websocket_protocol(const struct mg_connection *conn);
  1125. #else
  1126. #define is_websocket_protocol(conn) (0)
  1127. #endif
  1128. static int
  1129. mg_atomic_inc(volatile int *addr)
  1130. {
  1131. int ret;
  1132. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1133. /* Depending on the SDK, this function uses either
  1134. * (volatile unsigned int *) or (volatile LONG *),
  1135. * so whatever you use, the other SDK is likely to raise a warning. */
  1136. ret = InterlockedIncrement((volatile long *)addr);
  1137. #elif defined(__GNUC__) \
  1138. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1139. ret = __sync_add_and_fetch(addr, 1);
  1140. #else
  1141. ret = (++(*addr));
  1142. #endif
  1143. return ret;
  1144. }
  1145. static int
  1146. mg_atomic_dec(volatile int *addr)
  1147. {
  1148. int ret;
  1149. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1150. /* Depending on the SDK, this function uses either
  1151. * (volatile unsigned int *) or (volatile LONG *),
  1152. * so whatever you use, the other SDK is likely to raise a warning. */
  1153. ret = InterlockedDecrement((volatile long *)addr);
  1154. #elif defined(__GNUC__) \
  1155. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1156. ret = __sync_sub_and_fetch(addr, 1);
  1157. #else
  1158. ret = (--(*addr));
  1159. #endif
  1160. return ret;
  1161. }
  1162. #if !defined(NO_THREAD_NAME)
  1163. #if defined(_WIN32) && defined(_MSC_VER)
  1164. /* Set the thread name for debugging purposes in Visual Studio
  1165. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1166. */
  1167. #pragma pack(push, 8)
  1168. typedef struct tagTHREADNAME_INFO {
  1169. DWORD dwType; /* Must be 0x1000. */
  1170. LPCSTR szName; /* Pointer to name (in user addr space). */
  1171. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1172. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1173. } THREADNAME_INFO;
  1174. #pragma pack(pop)
  1175. #elif defined(__linux__)
  1176. #include <sys/prctl.h>
  1177. #include <sys/sendfile.h>
  1178. #endif
  1179. static void
  1180. mg_set_thread_name(const char *name)
  1181. {
  1182. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1183. mg_snprintf(
  1184. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1185. #if defined(_WIN32)
  1186. #if defined(_MSC_VER)
  1187. /* Windows and Visual Studio Compiler */
  1188. __try
  1189. {
  1190. THREADNAME_INFO info;
  1191. info.dwType = 0x1000;
  1192. info.szName = threadName;
  1193. info.dwThreadID = ~0U;
  1194. info.dwFlags = 0;
  1195. RaiseException(0x406D1388,
  1196. 0,
  1197. sizeof(info) / sizeof(ULONG_PTR),
  1198. (ULONG_PTR *)&info);
  1199. }
  1200. __except(EXCEPTION_EXECUTE_HANDLER)
  1201. {
  1202. }
  1203. #elif defined(__MINGW32__)
  1204. /* No option known to set thread name for MinGW */
  1205. #endif
  1206. #elif defined(__GLIBC__) \
  1207. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1208. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1209. (void)pthread_setname_np(pthread_self(), threadName);
  1210. #elif defined(__linux__)
  1211. /* on linux we can use the old prctl function */
  1212. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1213. #endif
  1214. }
  1215. #else /* !defined(NO_THREAD_NAME) */
  1216. void
  1217. mg_set_thread_name(const char *threadName)
  1218. {
  1219. }
  1220. #endif
  1221. #if defined(MG_LEGACY_INTERFACE)
  1222. const char **
  1223. mg_get_valid_option_names(void)
  1224. {
  1225. /* This function is deprecated. Use mg_get_valid_options instead. */
  1226. static const char *
  1227. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1228. int i;
  1229. for (i = 0; config_options[i].name != NULL; i++) {
  1230. data[i * 2] = config_options[i].name;
  1231. data[i * 2 + 1] = config_options[i].default_value;
  1232. }
  1233. return data;
  1234. }
  1235. #endif
  1236. const struct mg_option *
  1237. mg_get_valid_options(void)
  1238. {
  1239. return config_options;
  1240. }
  1241. static int
  1242. is_file_in_memory(struct mg_connection *conn,
  1243. const char *path,
  1244. struct file *filep)
  1245. {
  1246. size_t size = 0;
  1247. if (!conn || !filep) {
  1248. return 0;
  1249. }
  1250. if (conn->ctx->callbacks.open_file) {
  1251. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1252. if (filep->membuf != NULL) {
  1253. /* NOTE: override filep->size only on success. Otherwise, it might
  1254. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1255. filep->size = size;
  1256. }
  1257. }
  1258. return filep->membuf != NULL;
  1259. }
  1260. static int
  1261. is_file_opened(const struct file *filep)
  1262. {
  1263. if (!filep) {
  1264. return 0;
  1265. }
  1266. return filep->membuf != NULL || filep->fp != NULL;
  1267. }
  1268. static int
  1269. mg_fopen(struct mg_connection *conn,
  1270. const char *path,
  1271. const char *mode,
  1272. struct file *filep)
  1273. {
  1274. if (!filep) {
  1275. return 0;
  1276. }
  1277. memset(filep, 0, sizeof(*filep));
  1278. if (!is_file_in_memory(conn, path, filep)) {
  1279. #ifdef _WIN32
  1280. wchar_t wbuf[PATH_MAX], wmode[20];
  1281. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1282. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1283. filep->fp = _wfopen(wbuf, wmode);
  1284. #else
  1285. filep->fp = fopen(path, mode);
  1286. #endif
  1287. }
  1288. return is_file_opened(filep);
  1289. }
  1290. static void
  1291. mg_fclose(struct file *filep)
  1292. {
  1293. if (filep != NULL && filep->fp != NULL) {
  1294. fclose(filep->fp);
  1295. }
  1296. }
  1297. static void
  1298. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1299. {
  1300. for (; *src != '\0' && n > 1; n--) {
  1301. *dst++ = *src++;
  1302. }
  1303. *dst = '\0';
  1304. }
  1305. static int
  1306. lowercase(const char *s)
  1307. {
  1308. return tolower(*(const unsigned char *)s);
  1309. }
  1310. int
  1311. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1312. {
  1313. int diff = 0;
  1314. if (len > 0) {
  1315. do {
  1316. diff = lowercase(s1++) - lowercase(s2++);
  1317. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1318. }
  1319. return diff;
  1320. }
  1321. static int
  1322. mg_strcasecmp(const char *s1, const char *s2)
  1323. {
  1324. int diff;
  1325. do {
  1326. diff = lowercase(s1++) - lowercase(s2++);
  1327. } while (diff == 0 && s1[-1] != '\0');
  1328. return diff;
  1329. }
  1330. static char *
  1331. mg_strndup(const char *ptr, size_t len)
  1332. {
  1333. char *p;
  1334. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1335. mg_strlcpy(p, ptr, len + 1);
  1336. }
  1337. return p;
  1338. }
  1339. static char *
  1340. mg_strdup(const char *str)
  1341. {
  1342. return mg_strndup(str, strlen(str));
  1343. }
  1344. static const char *
  1345. mg_strcasestr(const char *big_str, const char *small_str)
  1346. {
  1347. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1348. if (big_len >= small_len) {
  1349. for (i = 0; i <= (big_len - small_len); i++) {
  1350. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1351. return big_str + i;
  1352. }
  1353. }
  1354. }
  1355. return NULL;
  1356. }
  1357. /* Return null terminated string of given maximum length.
  1358. * Report errors if length is exceeded. */
  1359. static void
  1360. mg_vsnprintf(const struct mg_connection *conn,
  1361. int *truncated,
  1362. char *buf,
  1363. size_t buflen,
  1364. const char *fmt,
  1365. va_list ap)
  1366. {
  1367. int n, ok;
  1368. if (buflen == 0) {
  1369. return;
  1370. }
  1371. #ifdef __clang__
  1372. #pragma clang diagnostic push
  1373. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1374. /* Using fmt as a non-literal is intended here, since it is mostly called
  1375. * indirectly by mg_snprintf */
  1376. #endif
  1377. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1378. ok = (n >= 0) && ((size_t)n < buflen);
  1379. #ifdef __clang__
  1380. #pragma clang diagnostic pop
  1381. #endif
  1382. if (ok) {
  1383. if (truncated) {
  1384. *truncated = 0;
  1385. }
  1386. } else {
  1387. if (truncated) {
  1388. *truncated = 1;
  1389. }
  1390. mg_cry(conn,
  1391. "truncating vsnprintf buffer: [%.*s]",
  1392. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1393. buf);
  1394. n = (int)buflen - 1;
  1395. }
  1396. buf[n] = '\0';
  1397. }
  1398. static void
  1399. mg_snprintf(const struct mg_connection *conn,
  1400. int *truncated,
  1401. char *buf,
  1402. size_t buflen,
  1403. const char *fmt,
  1404. ...)
  1405. {
  1406. va_list ap;
  1407. va_start(ap, fmt);
  1408. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1409. va_end(ap);
  1410. }
  1411. static int
  1412. get_option_index(const char *name)
  1413. {
  1414. int i;
  1415. for (i = 0; config_options[i].name != NULL; i++) {
  1416. if (strcmp(config_options[i].name, name) == 0) {
  1417. return i;
  1418. }
  1419. }
  1420. return -1;
  1421. }
  1422. const char *
  1423. mg_get_option(const struct mg_context *ctx, const char *name)
  1424. {
  1425. int i;
  1426. if ((i = get_option_index(name)) == -1) {
  1427. return NULL;
  1428. } else if (!ctx || ctx->config[i] == NULL) {
  1429. return "";
  1430. } else {
  1431. return ctx->config[i];
  1432. }
  1433. }
  1434. struct mg_context *
  1435. mg_get_context(const struct mg_connection *conn)
  1436. {
  1437. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1438. }
  1439. void *
  1440. mg_get_user_data(const struct mg_context *ctx)
  1441. {
  1442. return (ctx == NULL) ? NULL : ctx->user_data;
  1443. }
  1444. void
  1445. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1446. {
  1447. if (conn != NULL) {
  1448. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1449. }
  1450. }
  1451. void *
  1452. mg_get_user_connection_data(const struct mg_connection *conn)
  1453. {
  1454. if (conn != NULL) {
  1455. return conn->request_info.conn_data;
  1456. }
  1457. return NULL;
  1458. }
  1459. size_t
  1460. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1461. {
  1462. size_t i;
  1463. if (!ctx) {
  1464. return 0;
  1465. }
  1466. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1467. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1468. ports[i] = ctx->listening_ports[i];
  1469. }
  1470. return i;
  1471. }
  1472. int
  1473. mg_get_server_ports(const struct mg_context *ctx,
  1474. int size,
  1475. struct mg_server_ports *ports)
  1476. {
  1477. int i, cnt = 0;
  1478. if (size <= 0) {
  1479. return -1;
  1480. }
  1481. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1482. if (!ctx) {
  1483. return -1;
  1484. }
  1485. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1486. return -1;
  1487. }
  1488. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1489. ports[cnt].port = ctx->listening_ports[i];
  1490. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1491. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1492. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1493. /* IPv4 */
  1494. ports[cnt].protocol = 1;
  1495. cnt++;
  1496. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1497. /* IPv6 */
  1498. ports[cnt].protocol = 3;
  1499. cnt++;
  1500. }
  1501. }
  1502. return cnt;
  1503. }
  1504. static void
  1505. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1506. {
  1507. buf[0] = '\0';
  1508. if (!usa) {
  1509. return;
  1510. }
  1511. if (usa->sa.sa_family == AF_INET) {
  1512. getnameinfo(&usa->sa,
  1513. sizeof(usa->sin),
  1514. buf,
  1515. (unsigned)len,
  1516. NULL,
  1517. 0,
  1518. NI_NUMERICHOST);
  1519. }
  1520. #if defined(USE_IPV6)
  1521. else if (usa->sa.sa_family == AF_INET6) {
  1522. getnameinfo(&usa->sa,
  1523. sizeof(usa->sin6),
  1524. buf,
  1525. (unsigned)len,
  1526. NULL,
  1527. 0,
  1528. NI_NUMERICHOST);
  1529. }
  1530. #endif
  1531. }
  1532. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1533. * included in all responses other than 100, 101, 5xx. */
  1534. static void
  1535. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1536. {
  1537. struct tm *tm;
  1538. tm = gmtime(t);
  1539. if (tm != NULL) {
  1540. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1541. } else {
  1542. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1543. buf[buf_len - 1] = '\0';
  1544. }
  1545. }
  1546. /* difftime for struct timespec. Return value is in seconds. */
  1547. static double
  1548. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1549. {
  1550. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1551. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1552. }
  1553. /* Print error message to the opened error log stream. */
  1554. void
  1555. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1556. {
  1557. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1558. va_list ap;
  1559. FILE *fp;
  1560. time_t timestamp;
  1561. va_start(ap, fmt);
  1562. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1563. va_end(ap);
  1564. buf[sizeof(buf) - 1] = 0;
  1565. /* Do not lock when getting the callback value, here and below.
  1566. * I suppose this is fine, since function cannot disappear in the
  1567. * same way string option can. */
  1568. if (conn && (conn->ctx->callbacks.log_message == NULL
  1569. || conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1570. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1571. ? NULL
  1572. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1573. if (fp != NULL) {
  1574. flockfile(fp);
  1575. timestamp = time(NULL);
  1576. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1577. fprintf(fp,
  1578. "[%010lu] [error] [client %s] ",
  1579. (unsigned long)timestamp,
  1580. src_addr);
  1581. if (conn->request_info.request_method != NULL) {
  1582. fprintf(fp,
  1583. "%s %s: ",
  1584. conn->request_info.request_method,
  1585. conn->request_info.request_uri);
  1586. }
  1587. fprintf(fp, "%s", buf);
  1588. fputc('\n', fp);
  1589. funlockfile(fp);
  1590. fclose(fp);
  1591. }
  1592. }
  1593. }
  1594. /* Return fake connection structure. Used for logging, if connection
  1595. * is not applicable at the moment of logging. */
  1596. static struct mg_connection *
  1597. fc(struct mg_context *ctx)
  1598. {
  1599. static struct mg_connection fake_connection;
  1600. fake_connection.ctx = ctx;
  1601. return &fake_connection;
  1602. }
  1603. const char *
  1604. mg_version(void)
  1605. {
  1606. return CIVETWEB_VERSION;
  1607. }
  1608. const struct mg_request_info *
  1609. mg_get_request_info(const struct mg_connection *conn)
  1610. {
  1611. if (!conn) {
  1612. return NULL;
  1613. }
  1614. return &conn->request_info;
  1615. }
  1616. /* Skip the characters until one of the delimiters characters found.
  1617. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1618. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1619. * Delimiters can be quoted with quotechar. */
  1620. static char *
  1621. skip_quoted(char **buf,
  1622. const char *delimiters,
  1623. const char *whitespace,
  1624. char quotechar)
  1625. {
  1626. char *p, *begin_word, *end_word, *end_whitespace;
  1627. begin_word = *buf;
  1628. end_word = begin_word + strcspn(begin_word, delimiters);
  1629. /* Check for quotechar */
  1630. if (end_word > begin_word) {
  1631. p = end_word - 1;
  1632. while (*p == quotechar) {
  1633. /* While the delimiter is quoted, look for the next delimiter. */
  1634. /* This happens, e.g., in calls from parse_auth_header,
  1635. * if the user name contains a " character. */
  1636. /* If there is anything beyond end_word, copy it. */
  1637. if (*end_word != '\0') {
  1638. size_t end_off = strcspn(end_word + 1, delimiters);
  1639. memmove(p, end_word, end_off + 1);
  1640. p += end_off; /* p must correspond to end_word - 1 */
  1641. end_word += end_off + 1;
  1642. } else {
  1643. *p = '\0';
  1644. break;
  1645. }
  1646. }
  1647. for (p++; p < end_word; p++) {
  1648. *p = '\0';
  1649. }
  1650. }
  1651. if (*end_word == '\0') {
  1652. *buf = end_word;
  1653. } else {
  1654. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1655. for (p = end_word; p < end_whitespace; p++) {
  1656. *p = '\0';
  1657. }
  1658. *buf = end_whitespace;
  1659. }
  1660. return begin_word;
  1661. }
  1662. /* Simplified version of skip_quoted without quote char
  1663. * and whitespace == delimiters */
  1664. static char *
  1665. skip(char **buf, const char *delimiters)
  1666. {
  1667. return skip_quoted(buf, delimiters, delimiters, 0);
  1668. }
  1669. /* Return HTTP header value, or NULL if not found. */
  1670. static const char *
  1671. get_header(const struct mg_request_info *ri, const char *name)
  1672. {
  1673. int i;
  1674. if (ri) {
  1675. for (i = 0; i < ri->num_headers; i++) {
  1676. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1677. return ri->http_headers[i].value;
  1678. }
  1679. }
  1680. }
  1681. return NULL;
  1682. }
  1683. const char *
  1684. mg_get_header(const struct mg_connection *conn, const char *name)
  1685. {
  1686. if (!conn) {
  1687. return NULL;
  1688. }
  1689. return get_header(&conn->request_info, name);
  1690. }
  1691. /* A helper function for traversing a comma separated list of values.
  1692. * It returns a list pointer shifted to the next value, or NULL if the end
  1693. * of the list found.
  1694. * Value is stored in val vector. If value has form "x=y", then eq_val
  1695. * vector is initialized to point to the "y" part, and val vector length
  1696. * is adjusted to point only to "x". */
  1697. static const char *
  1698. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1699. {
  1700. if (val == NULL || list == NULL || *list == '\0') {
  1701. /* End of the list */
  1702. list = NULL;
  1703. } else {
  1704. val->ptr = list;
  1705. if ((list = strchr(val->ptr, ',')) != NULL) {
  1706. /* Comma found. Store length and shift the list ptr */
  1707. val->len = ((size_t)(list - val->ptr));
  1708. list++;
  1709. } else {
  1710. /* This value is the last one */
  1711. list = val->ptr + strlen(val->ptr);
  1712. val->len = ((size_t)(list - val->ptr));
  1713. }
  1714. if (eq_val != NULL) {
  1715. /* Value has form "x=y", adjust pointers and lengths
  1716. * so that val points to "x", and eq_val points to "y". */
  1717. eq_val->len = 0;
  1718. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1719. if (eq_val->ptr != NULL) {
  1720. eq_val->ptr++; /* Skip over '=' character */
  1721. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1722. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1723. }
  1724. }
  1725. }
  1726. return list;
  1727. }
  1728. /* Perform case-insensitive match of string against pattern */
  1729. static int
  1730. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1731. {
  1732. const char *or_str;
  1733. size_t i;
  1734. int j, len, res;
  1735. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1736. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1737. return res > 0 ? res : match_prefix(or_str + 1,
  1738. (size_t)((pattern + pattern_len)
  1739. - (or_str + 1)),
  1740. str);
  1741. }
  1742. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1743. if (pattern[i] == '?' && str[j] != '\0') {
  1744. continue;
  1745. } else if (pattern[i] == '$') {
  1746. return str[j] == '\0' ? j : -1;
  1747. } else if (pattern[i] == '*') {
  1748. i++;
  1749. if (pattern[i] == '*') {
  1750. i++;
  1751. len = (int)strlen(str + j);
  1752. } else {
  1753. len = (int)strcspn(str + j, "/");
  1754. }
  1755. if (i == pattern_len) {
  1756. return j + len;
  1757. }
  1758. do {
  1759. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1760. } while (res == -1 && len-- > 0);
  1761. return res == -1 ? -1 : j + res + len;
  1762. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1763. return -1;
  1764. }
  1765. }
  1766. return j;
  1767. }
  1768. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1769. * This function must tolerate situations when connection info is not
  1770. * set up, for example if request parsing failed. */
  1771. static int
  1772. should_keep_alive(const struct mg_connection *conn)
  1773. {
  1774. if (conn != NULL) {
  1775. const char *http_version = conn->request_info.http_version;
  1776. const char *header = mg_get_header(conn, "Connection");
  1777. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1778. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1779. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1780. || (header == NULL && http_version
  1781. && 0 != strcmp(http_version, "1.1"))) {
  1782. return 0;
  1783. }
  1784. return 1;
  1785. }
  1786. return 0;
  1787. }
  1788. static int
  1789. should_decode_url(const struct mg_connection *conn)
  1790. {
  1791. if (!conn || !conn->ctx) {
  1792. return 0;
  1793. }
  1794. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1795. }
  1796. static const char *
  1797. suggest_connection_header(const struct mg_connection *conn)
  1798. {
  1799. return should_keep_alive(conn) ? "keep-alive" : "close";
  1800. }
  1801. static int
  1802. send_no_cache_header(struct mg_connection *conn)
  1803. {
  1804. /* Send all current and obsolete cache opt-out directives. */
  1805. return mg_printf(conn,
  1806. "Cache-Control: no-cache, no-store, "
  1807. "must-revalidate, private, max-age=0\r\n"
  1808. "Pragma: no-cache\r\n"
  1809. "Expires: 0\r\n");
  1810. }
  1811. static int
  1812. send_static_cache_header(struct mg_connection *conn)
  1813. {
  1814. /* TODO: Get max age (in seconds) for static files from conn->ctx */
  1815. int max_age = 60 /* + conn->ctx.TODO */;
  1816. if (max_age <= 0) {
  1817. return send_no_cache_header(conn);
  1818. }
  1819. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", max_age);
  1820. }
  1821. static void handle_file_based_request(struct mg_connection *conn,
  1822. const char *path,
  1823. struct file *filep);
  1824. static int
  1825. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1826. static const char *
  1827. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1828. {
  1829. switch (response_code) {
  1830. /* RFC2616 Section 10.1 - Informational 1xx */
  1831. case 100:
  1832. return "Continue"; /* RFC2616 Section 10.1.1 */
  1833. case 101:
  1834. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1835. case 102:
  1836. return "Processing"; /* RFC2518 Section 10.1 */
  1837. /* RFC2616 Section 10.2 - Successful 2xx */
  1838. case 200:
  1839. return "OK"; /* RFC2616 Section 10.2.1 */
  1840. case 201:
  1841. return "Created"; /* RFC2616 Section 10.2.2 */
  1842. case 202:
  1843. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1844. case 203:
  1845. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1846. case 204:
  1847. return "No Content"; /* RFC2616 Section 10.2.5 */
  1848. case 205:
  1849. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1850. case 206:
  1851. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1852. case 207:
  1853. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1854. /* RFC2616 Section 10.3 - Redirection 3xx */
  1855. case 300:
  1856. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1857. case 301:
  1858. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1859. case 302:
  1860. return "Found"; /* RFC2616 Section 10.3.3 */
  1861. case 303:
  1862. return "See Other"; /* RFC2616 Section 10.3.4 */
  1863. case 304:
  1864. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1865. case 305:
  1866. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1867. case 307:
  1868. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1869. /* RFC2616 Section 10.4 - Client Error 4xx */
  1870. case 400:
  1871. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1872. case 401:
  1873. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1874. case 402:
  1875. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1876. case 403:
  1877. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1878. case 404:
  1879. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1880. case 405:
  1881. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1882. case 406:
  1883. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1884. case 407:
  1885. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1886. case 408:
  1887. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1888. case 409:
  1889. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1890. case 410:
  1891. return "Gone"; /* RFC2616 Section 10.4.11 */
  1892. case 411:
  1893. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1894. case 412:
  1895. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1896. case 413:
  1897. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1898. case 414:
  1899. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1900. case 415:
  1901. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1902. case 416:
  1903. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1904. case 417:
  1905. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1906. case 422:
  1907. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1908. * Section 11.2 */
  1909. case 423:
  1910. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1911. case 424:
  1912. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1913. * Section 11.4 */
  1914. case 428:
  1915. return "Precondition Required"; /* RFC 6585, Section 3 */
  1916. case 429:
  1917. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1918. case 431:
  1919. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1920. /* RFC2616 Section 10.5 - Server Error 5xx */
  1921. case 500:
  1922. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1923. case 501:
  1924. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1925. case 502:
  1926. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1927. case 503:
  1928. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1929. case 504:
  1930. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1931. case 505:
  1932. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1933. case 507:
  1934. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1935. * Section 11.5 */
  1936. case 511:
  1937. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1938. /* Other RFCs */
  1939. case 426:
  1940. return "Upgrade Required"; /* RFC 2817 */
  1941. /* Return codes from non normative RFCs: */
  1942. /* Informative and experimental RFCs, "de facto" standards due to common
  1943. * use, ... */
  1944. case 208:
  1945. return "Already Reported"; /* RFC5842 Section 7.1 */
  1946. case 226:
  1947. return "IM used"; /* RFC3229 Section 10.4.1 */
  1948. case 308:
  1949. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1950. case 418:
  1951. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1952. case 419:
  1953. return "Authentication Timeout"; /* common use */
  1954. case 451:
  1955. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1956. * Section 3 */
  1957. case 506:
  1958. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1959. case 508:
  1960. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1961. case 510:
  1962. return "Not Extended"; /* RFC 2774, Section 7 */
  1963. default:
  1964. /* This error code is unknown. This should not happen. */
  1965. if (conn) {
  1966. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1967. }
  1968. /* Return at least a category according to RFC 2616 Section 10. */
  1969. if (response_code >= 100 && response_code < 200) {
  1970. /* Unknown informational status code */
  1971. return "Information";
  1972. }
  1973. if (response_code >= 200 && response_code < 300) {
  1974. /* Unknown success code */
  1975. return "Success";
  1976. }
  1977. if (response_code >= 300 && response_code < 400) {
  1978. /* Unknown redirection code */
  1979. return "Redirection";
  1980. }
  1981. if (response_code >= 400 && response_code < 500) {
  1982. /* Unknown request error code */
  1983. return "Client Error";
  1984. }
  1985. if (response_code >= 500 && response_code < 600) {
  1986. /* Unknown server error code */
  1987. return "Server Error";
  1988. }
  1989. /* Response code not even within reasonable range */
  1990. return "";
  1991. }
  1992. }
  1993. static void send_http_error(struct mg_connection *,
  1994. int,
  1995. PRINTF_FORMAT_STRING(const char *fmt),
  1996. ...) PRINTF_ARGS(3, 4);
  1997. static void
  1998. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1999. {
  2000. char buf[MG_BUF_LEN];
  2001. va_list ap;
  2002. int len, i, page_handler_found, scope, truncated;
  2003. char date[64];
  2004. time_t curtime = time(NULL);
  2005. const char *error_handler = NULL;
  2006. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2007. const char *error_page_file_ext, *tstr;
  2008. const char *status_text = mg_get_response_code_text(status, conn);
  2009. if (conn == NULL) {
  2010. return;
  2011. }
  2012. conn->status_code = status;
  2013. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2014. || conn->ctx->callbacks.http_error(conn, status)) {
  2015. if (!conn->in_error_handler) {
  2016. /* Send user defined error pages, if defined */
  2017. error_handler = conn->ctx->config[ERROR_PAGES];
  2018. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2019. page_handler_found = 0;
  2020. if (error_handler != NULL) {
  2021. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2022. switch (scope) {
  2023. case 1: /* Handler for specific error, e.g. 404 error */
  2024. mg_snprintf(conn,
  2025. &truncated,
  2026. buf,
  2027. sizeof(buf) - 32,
  2028. "%serror%03u.",
  2029. error_handler,
  2030. status);
  2031. break;
  2032. case 2: /* Handler for error group, e.g., 5xx error handler
  2033. * for all server errors (500-599) */
  2034. mg_snprintf(conn,
  2035. &truncated,
  2036. buf,
  2037. sizeof(buf) - 32,
  2038. "%serror%01uxx.",
  2039. error_handler,
  2040. status / 100);
  2041. break;
  2042. default: /* Handler for all errors */
  2043. mg_snprintf(conn,
  2044. &truncated,
  2045. buf,
  2046. sizeof(buf) - 32,
  2047. "%serror.",
  2048. error_handler);
  2049. break;
  2050. }
  2051. /* String truncation in buf may only occur if error_handler
  2052. * is too long. This string is from the config, not from a
  2053. * client. */
  2054. (void)truncated;
  2055. len = (int)strlen(buf);
  2056. tstr = strchr(error_page_file_ext, '.');
  2057. while (tstr) {
  2058. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2059. i++)
  2060. buf[len + i - 1] = tstr[i];
  2061. buf[len + i - 1] = 0;
  2062. if (mg_stat(conn, buf, &error_page_file)) {
  2063. page_handler_found = 1;
  2064. break;
  2065. }
  2066. tstr = strchr(tstr + i, '.');
  2067. }
  2068. }
  2069. }
  2070. if (page_handler_found) {
  2071. conn->in_error_handler = 1;
  2072. handle_file_based_request(conn, buf, &error_page_file);
  2073. conn->in_error_handler = 0;
  2074. return;
  2075. }
  2076. }
  2077. /* No custom error page. Send default error page. */
  2078. gmt_time_string(date, sizeof(date), &curtime);
  2079. conn->must_close = 1;
  2080. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2081. send_no_cache_header(conn);
  2082. mg_printf(conn,
  2083. "Date: %s\r\n"
  2084. "Connection: close\r\n\r\n",
  2085. date);
  2086. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2087. if (status > 199 && status != 204 && status != 304) {
  2088. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2089. if (fmt != NULL) {
  2090. va_start(ap, fmt);
  2091. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2092. va_end(ap);
  2093. mg_write(conn, buf, strlen(buf));
  2094. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2095. }
  2096. } else {
  2097. /* No body allowed. Close the connection. */
  2098. DEBUG_TRACE("Error %i", status);
  2099. }
  2100. }
  2101. }
  2102. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2103. /* Create substitutes for POSIX functions in Win32. */
  2104. #if defined(__MINGW32__)
  2105. /* Show no warning in case system functions are not used. */
  2106. #pragma GCC diagnostic push
  2107. #pragma GCC diagnostic ignored "-Wunused-function"
  2108. #endif
  2109. static int
  2110. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2111. {
  2112. (void)unused;
  2113. *mutex = CreateMutex(NULL, FALSE, NULL);
  2114. return *mutex == NULL ? -1 : 0;
  2115. }
  2116. static int
  2117. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2118. {
  2119. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2120. }
  2121. static int
  2122. pthread_mutex_lock(pthread_mutex_t *mutex)
  2123. {
  2124. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2125. }
  2126. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2127. static int
  2128. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2129. {
  2130. switch (WaitForSingleObject(*mutex, 0)) {
  2131. case WAIT_OBJECT_0:
  2132. return 0;
  2133. case WAIT_TIMEOUT:
  2134. return -2; /* EBUSY */
  2135. }
  2136. return -1;
  2137. }
  2138. #endif
  2139. static int
  2140. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2141. {
  2142. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2143. }
  2144. #ifndef WIN_PTHREADS_TIME_H
  2145. static int
  2146. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2147. {
  2148. FILETIME ft;
  2149. ULARGE_INTEGER li;
  2150. BOOL ok = FALSE;
  2151. double d;
  2152. static double perfcnt_per_sec = 0.0;
  2153. if (tp) {
  2154. memset(tp, 0, sizeof(*tp));
  2155. if (clk_id == CLOCK_REALTIME) {
  2156. GetSystemTimeAsFileTime(&ft);
  2157. li.LowPart = ft.dwLowDateTime;
  2158. li.HighPart = ft.dwHighDateTime;
  2159. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2160. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2161. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2162. ok = TRUE;
  2163. } else if (clk_id == CLOCK_MONOTONIC) {
  2164. if (perfcnt_per_sec == 0.0) {
  2165. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2166. perfcnt_per_sec = 1.0 / li.QuadPart;
  2167. }
  2168. if (perfcnt_per_sec != 0.0) {
  2169. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2170. d = li.QuadPart * perfcnt_per_sec;
  2171. tp->tv_sec = (time_t)d;
  2172. d -= tp->tv_sec;
  2173. tp->tv_nsec = (long)(d * 1.0E9);
  2174. ok = TRUE;
  2175. }
  2176. }
  2177. }
  2178. return ok ? 0 : -1;
  2179. }
  2180. #endif
  2181. static int
  2182. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2183. {
  2184. (void)unused;
  2185. InitializeCriticalSection(&cv->threadIdSec);
  2186. cv->waitingthreadcount = 0;
  2187. cv->waitingthreadhdls =
  2188. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2189. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2190. }
  2191. static int
  2192. pthread_cond_timedwait(pthread_cond_t *cv,
  2193. pthread_mutex_t *mutex,
  2194. const struct timespec *abstime)
  2195. {
  2196. struct mg_workerTLS *tls =
  2197. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2198. int ok;
  2199. struct timespec tsnow;
  2200. int64_t nsnow, nswaitabs, nswaitrel;
  2201. DWORD mswaitrel;
  2202. EnterCriticalSection(&cv->threadIdSec);
  2203. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2204. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2205. tls->pthread_cond_helper_mutex;
  2206. cv->waitingthreadcount++;
  2207. LeaveCriticalSection(&cv->threadIdSec);
  2208. if (abstime) {
  2209. clock_gettime(CLOCK_REALTIME, &tsnow);
  2210. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2211. nswaitabs =
  2212. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2213. nswaitrel = nswaitabs - nsnow;
  2214. if (nswaitrel < 0) {
  2215. nswaitrel = 0;
  2216. }
  2217. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2218. } else {
  2219. mswaitrel = INFINITE;
  2220. }
  2221. pthread_mutex_unlock(mutex);
  2222. ok = (WAIT_OBJECT_0
  2223. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2224. pthread_mutex_lock(mutex);
  2225. return ok ? 0 : -1;
  2226. }
  2227. static int
  2228. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2229. {
  2230. return pthread_cond_timedwait(cv, mutex, NULL);
  2231. }
  2232. static int
  2233. pthread_cond_signal(pthread_cond_t *cv)
  2234. {
  2235. int i;
  2236. HANDLE wkup = NULL;
  2237. BOOL ok = FALSE;
  2238. EnterCriticalSection(&cv->threadIdSec);
  2239. if (cv->waitingthreadcount) {
  2240. wkup = cv->waitingthreadhdls[0];
  2241. ok = SetEvent(wkup);
  2242. for (i = 1; i < cv->waitingthreadcount; i++) {
  2243. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2244. }
  2245. cv->waitingthreadcount--;
  2246. assert(ok);
  2247. }
  2248. LeaveCriticalSection(&cv->threadIdSec);
  2249. return ok ? 0 : 1;
  2250. }
  2251. static int
  2252. pthread_cond_broadcast(pthread_cond_t *cv)
  2253. {
  2254. EnterCriticalSection(&cv->threadIdSec);
  2255. while (cv->waitingthreadcount) {
  2256. pthread_cond_signal(cv);
  2257. }
  2258. LeaveCriticalSection(&cv->threadIdSec);
  2259. return 0;
  2260. }
  2261. static int
  2262. pthread_cond_destroy(pthread_cond_t *cv)
  2263. {
  2264. EnterCriticalSection(&cv->threadIdSec);
  2265. assert(cv->waitingthreadcount == 0);
  2266. mg_free(cv->waitingthreadhdls);
  2267. cv->waitingthreadhdls = 0;
  2268. LeaveCriticalSection(&cv->threadIdSec);
  2269. DeleteCriticalSection(&cv->threadIdSec);
  2270. return 0;
  2271. }
  2272. #if defined(__MINGW32__)
  2273. /* Enable unused function warning again */
  2274. #pragma GCC diagnostic pop
  2275. #endif
  2276. /* For Windows, change all slashes to backslashes in path names. */
  2277. static void
  2278. change_slashes_to_backslashes(char *path)
  2279. {
  2280. int i;
  2281. for (i = 0; path[i] != '\0'; i++) {
  2282. if (path[i] == '/') {
  2283. path[i] = '\\';
  2284. }
  2285. /* remove double backslash (check i > 0 to preserve UNC paths,
  2286. * like \\server\file.txt) */
  2287. if ((path[i] == '\\') && (i > 0)) {
  2288. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2289. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2290. }
  2291. }
  2292. }
  2293. }
  2294. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2295. * wbuf and wbuf_len is a target buffer and its length. */
  2296. static void
  2297. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2298. {
  2299. char buf[PATH_MAX], buf2[PATH_MAX];
  2300. mg_strlcpy(buf, path, sizeof(buf));
  2301. change_slashes_to_backslashes(buf);
  2302. /* Convert to Unicode and back. If doubly-converted string does not
  2303. * match the original, something is fishy, reject. */
  2304. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2305. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2306. WideCharToMultiByte(
  2307. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2308. if (strcmp(buf, buf2) != 0) {
  2309. wbuf[0] = L'\0';
  2310. }
  2311. }
  2312. #if defined(_WIN32_WCE)
  2313. /* Create substitutes for POSIX functions in Win32. */
  2314. #if defined(__MINGW32__)
  2315. /* Show no warning in case system functions are not used. */
  2316. #pragma GCC diagnostic push
  2317. #pragma GCC diagnostic ignored "-Wunused-function"
  2318. #endif
  2319. static time_t
  2320. time(time_t *ptime)
  2321. {
  2322. time_t t;
  2323. SYSTEMTIME st;
  2324. FILETIME ft;
  2325. GetSystemTime(&st);
  2326. SystemTimeToFileTime(&st, &ft);
  2327. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2328. if (ptime != NULL) {
  2329. *ptime = t;
  2330. }
  2331. return t;
  2332. }
  2333. static struct tm *
  2334. localtime(const time_t *ptime, struct tm *ptm)
  2335. {
  2336. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2337. FILETIME ft, lft;
  2338. SYSTEMTIME st;
  2339. TIME_ZONE_INFORMATION tzinfo;
  2340. if (ptm == NULL) {
  2341. return NULL;
  2342. }
  2343. *(int64_t *)&ft = t;
  2344. FileTimeToLocalFileTime(&ft, &lft);
  2345. FileTimeToSystemTime(&lft, &st);
  2346. ptm->tm_year = st.wYear - 1900;
  2347. ptm->tm_mon = st.wMonth - 1;
  2348. ptm->tm_wday = st.wDayOfWeek;
  2349. ptm->tm_mday = st.wDay;
  2350. ptm->tm_hour = st.wHour;
  2351. ptm->tm_min = st.wMinute;
  2352. ptm->tm_sec = st.wSecond;
  2353. ptm->tm_yday = 0; /* hope nobody uses this */
  2354. ptm->tm_isdst =
  2355. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2356. return ptm;
  2357. }
  2358. static struct tm *
  2359. gmtime(const time_t *ptime, struct tm *ptm)
  2360. {
  2361. /* FIXME(lsm): fix this. */
  2362. return localtime(ptime, ptm);
  2363. }
  2364. static size_t
  2365. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2366. {
  2367. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2368. return 0;
  2369. }
  2370. #if defined(__MINGW32__)
  2371. /* Enable unused function warning again */
  2372. #pragma GCC diagnostic pop
  2373. #endif
  2374. #endif
  2375. /* Windows happily opens files with some garbage at the end of file name.
  2376. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2377. * "a.cgi", despite one would expect an error back.
  2378. * This function returns non-0 if path ends with some garbage. */
  2379. static int
  2380. path_cannot_disclose_cgi(const char *path)
  2381. {
  2382. static const char *allowed_last_characters = "_-";
  2383. int last = path[strlen(path) - 1];
  2384. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2385. }
  2386. static int
  2387. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2388. {
  2389. wchar_t wbuf[PATH_MAX];
  2390. WIN32_FILE_ATTRIBUTE_DATA info;
  2391. time_t creation_time;
  2392. if (!filep) {
  2393. return 0;
  2394. }
  2395. memset(filep, 0, sizeof(*filep));
  2396. if (conn && is_file_in_memory(conn, path, filep)) {
  2397. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2398. * memset */
  2399. filep->last_modified = time(NULL);
  2400. /* last_modified = now ... assumes the file may change during runtime,
  2401. * so every mg_fopen call may return different data */
  2402. /* last_modified = conn->ctx.start_time;
  2403. * May be used it the data does not change during runtime. This allows
  2404. * browser caching. Since we do not know, we have to assume the file
  2405. * in memory may change. */
  2406. return 1;
  2407. }
  2408. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2409. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2410. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2411. filep->last_modified =
  2412. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2413. info.ftLastWriteTime.dwHighDateTime);
  2414. /* On Windows, the file creation time can be higher than the
  2415. * modification time, e.g. when a file is copied.
  2416. * Since the Last-Modified timestamp is used for caching
  2417. * it should be based on the most recent timestamp. */
  2418. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2419. info.ftCreationTime.dwHighDateTime);
  2420. if (creation_time > filep->last_modified) {
  2421. filep->last_modified = creation_time;
  2422. }
  2423. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2424. /* If file name is fishy, reset the file structure and return
  2425. * error.
  2426. * Note it is important to reset, not just return the error, cause
  2427. * functions like is_file_opened() check the struct. */
  2428. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2429. memset(filep, 0, sizeof(*filep));
  2430. return 0;
  2431. }
  2432. return 1;
  2433. }
  2434. return 0;
  2435. }
  2436. #if !defined(NO_FILES)
  2437. static int
  2438. mg_remove(const char *path)
  2439. {
  2440. wchar_t wbuf[PATH_MAX];
  2441. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2442. return DeleteFileW(wbuf) ? 0 : -1;
  2443. }
  2444. static int
  2445. mg_mkdir(const char *path, int mode)
  2446. {
  2447. char buf[PATH_MAX];
  2448. wchar_t wbuf[PATH_MAX];
  2449. (void)mode;
  2450. mg_strlcpy(buf, path, sizeof(buf));
  2451. change_slashes_to_backslashes(buf);
  2452. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2453. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2454. }
  2455. #endif
  2456. /* Create substitutes for POSIX functions in Win32. */
  2457. #if defined(__MINGW32__)
  2458. /* Show no warning in case system functions are not used. */
  2459. #pragma GCC diagnostic push
  2460. #pragma GCC diagnostic ignored "-Wunused-function"
  2461. #endif
  2462. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2463. static DIR *
  2464. opendir(const char *name)
  2465. {
  2466. DIR *dir = NULL;
  2467. wchar_t wpath[PATH_MAX];
  2468. DWORD attrs;
  2469. if (name == NULL) {
  2470. SetLastError(ERROR_BAD_ARGUMENTS);
  2471. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2472. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2473. } else {
  2474. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2475. attrs = GetFileAttributesW(wpath);
  2476. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2477. == FILE_ATTRIBUTE_DIRECTORY)) {
  2478. (void)wcscat(wpath, L"\\*");
  2479. dir->handle = FindFirstFileW(wpath, &dir->info);
  2480. dir->result.d_name[0] = '\0';
  2481. } else {
  2482. mg_free(dir);
  2483. dir = NULL;
  2484. }
  2485. }
  2486. return dir;
  2487. }
  2488. static int
  2489. closedir(DIR *dir)
  2490. {
  2491. int result = 0;
  2492. if (dir != NULL) {
  2493. if (dir->handle != INVALID_HANDLE_VALUE)
  2494. result = FindClose(dir->handle) ? 0 : -1;
  2495. mg_free(dir);
  2496. } else {
  2497. result = -1;
  2498. SetLastError(ERROR_BAD_ARGUMENTS);
  2499. }
  2500. return result;
  2501. }
  2502. static struct dirent *
  2503. readdir(DIR *dir)
  2504. {
  2505. struct dirent *result = 0;
  2506. if (dir) {
  2507. if (dir->handle != INVALID_HANDLE_VALUE) {
  2508. result = &dir->result;
  2509. (void)WideCharToMultiByte(CP_UTF8,
  2510. 0,
  2511. dir->info.cFileName,
  2512. -1,
  2513. result->d_name,
  2514. sizeof(result->d_name),
  2515. NULL,
  2516. NULL);
  2517. if (!FindNextFileW(dir->handle, &dir->info)) {
  2518. (void)FindClose(dir->handle);
  2519. dir->handle = INVALID_HANDLE_VALUE;
  2520. }
  2521. } else {
  2522. SetLastError(ERROR_FILE_NOT_FOUND);
  2523. }
  2524. } else {
  2525. SetLastError(ERROR_BAD_ARGUMENTS);
  2526. }
  2527. return result;
  2528. }
  2529. #ifndef HAVE_POLL
  2530. static int
  2531. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2532. {
  2533. struct timeval tv;
  2534. fd_set set;
  2535. unsigned int i;
  2536. int result;
  2537. SOCKET maxfd = 0;
  2538. memset(&tv, 0, sizeof(tv));
  2539. tv.tv_sec = milliseconds / 1000;
  2540. tv.tv_usec = (milliseconds % 1000) * 1000;
  2541. FD_ZERO(&set);
  2542. for (i = 0; i < n; i++) {
  2543. FD_SET((SOCKET)pfd[i].fd, &set);
  2544. pfd[i].revents = 0;
  2545. if (pfd[i].fd > maxfd) {
  2546. maxfd = pfd[i].fd;
  2547. }
  2548. }
  2549. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2550. for (i = 0; i < n; i++) {
  2551. if (FD_ISSET(pfd[i].fd, &set)) {
  2552. pfd[i].revents = POLLIN;
  2553. }
  2554. }
  2555. }
  2556. return result;
  2557. }
  2558. #endif /* HAVE_POLL */
  2559. #if defined(__MINGW32__)
  2560. /* Enable unused function warning again */
  2561. #pragma GCC diagnostic pop
  2562. #endif
  2563. static void
  2564. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2565. {
  2566. (void)conn; /* Unused. */
  2567. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2568. }
  2569. int
  2570. mg_start_thread(mg_thread_func_t f, void *p)
  2571. {
  2572. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2573. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2574. */
  2575. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2576. == ((uintptr_t)(-1L)))
  2577. ? -1
  2578. : 0);
  2579. #else
  2580. return (
  2581. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2582. ? -1
  2583. : 0);
  2584. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2585. }
  2586. /* Start a thread storing the thread context. */
  2587. static int
  2588. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2589. void *p,
  2590. pthread_t *threadidptr)
  2591. {
  2592. uintptr_t uip;
  2593. HANDLE threadhandle;
  2594. int result = -1;
  2595. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2596. threadhandle = (HANDLE)uip;
  2597. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2598. *threadidptr = threadhandle;
  2599. result = 0;
  2600. }
  2601. return result;
  2602. }
  2603. /* Wait for a thread to finish. */
  2604. static int
  2605. mg_join_thread(pthread_t threadid)
  2606. {
  2607. int result;
  2608. DWORD dwevent;
  2609. result = -1;
  2610. dwevent = WaitForSingleObject(threadid, INFINITE);
  2611. if (dwevent == WAIT_FAILED) {
  2612. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2613. } else {
  2614. if (dwevent == WAIT_OBJECT_0) {
  2615. CloseHandle(threadid);
  2616. result = 0;
  2617. }
  2618. }
  2619. return result;
  2620. }
  2621. #if !defined(NO_SSL_DL)
  2622. /* Create substitutes for POSIX functions in Win32. */
  2623. #if defined(__MINGW32__)
  2624. /* Show no warning in case system functions are not used. */
  2625. #pragma GCC diagnostic push
  2626. #pragma GCC diagnostic ignored "-Wunused-function"
  2627. #endif
  2628. static HANDLE
  2629. dlopen(const char *dll_name, int flags)
  2630. {
  2631. wchar_t wbuf[PATH_MAX];
  2632. (void)flags;
  2633. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2634. return LoadLibraryW(wbuf);
  2635. }
  2636. static int
  2637. dlclose(void *handle)
  2638. {
  2639. int result;
  2640. if (FreeLibrary((HMODULE)handle) != 0) {
  2641. result = 0;
  2642. } else {
  2643. result = -1;
  2644. }
  2645. return result;
  2646. }
  2647. #if defined(__MINGW32__)
  2648. /* Enable unused function warning again */
  2649. #pragma GCC diagnostic pop
  2650. #endif
  2651. #endif
  2652. #if !defined(NO_CGI)
  2653. #define SIGKILL (0)
  2654. static int
  2655. kill(pid_t pid, int sig_num)
  2656. {
  2657. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2658. (void)CloseHandle((HANDLE)pid);
  2659. return 0;
  2660. }
  2661. static void
  2662. trim_trailing_whitespaces(char *s)
  2663. {
  2664. char *e = s + strlen(s) - 1;
  2665. while (e > s && isspace(*(unsigned char *)e)) {
  2666. *e-- = '\0';
  2667. }
  2668. }
  2669. static pid_t
  2670. spawn_process(struct mg_connection *conn,
  2671. const char *prog,
  2672. char *envblk,
  2673. char *envp[],
  2674. int fdin,
  2675. int fdout,
  2676. int fderr,
  2677. const char *dir)
  2678. {
  2679. HANDLE me;
  2680. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2681. cmdline[PATH_MAX], buf[PATH_MAX];
  2682. int truncated;
  2683. struct file file = STRUCT_FILE_INITIALIZER;
  2684. STARTUPINFOA si;
  2685. PROCESS_INFORMATION pi = {0};
  2686. (void)envp;
  2687. memset(&si, 0, sizeof(si));
  2688. si.cb = sizeof(si);
  2689. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2690. si.wShowWindow = SW_HIDE;
  2691. me = GetCurrentProcess();
  2692. DuplicateHandle(me,
  2693. (HANDLE)_get_osfhandle(fdin),
  2694. me,
  2695. &si.hStdInput,
  2696. 0,
  2697. TRUE,
  2698. DUPLICATE_SAME_ACCESS);
  2699. DuplicateHandle(me,
  2700. (HANDLE)_get_osfhandle(fdout),
  2701. me,
  2702. &si.hStdOutput,
  2703. 0,
  2704. TRUE,
  2705. DUPLICATE_SAME_ACCESS);
  2706. DuplicateHandle(me,
  2707. (HANDLE)_get_osfhandle(fderr),
  2708. me,
  2709. &si.hStdError,
  2710. 0,
  2711. TRUE,
  2712. DUPLICATE_SAME_ACCESS);
  2713. /* If CGI file is a script, try to read the interpreter line */
  2714. interp = conn->ctx->config[CGI_INTERPRETER];
  2715. if (interp == NULL) {
  2716. buf[0] = buf[1] = '\0';
  2717. /* Read the first line of the script into the buffer */
  2718. mg_snprintf(
  2719. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2720. if (truncated) {
  2721. pi.hProcess = (pid_t)-1;
  2722. goto spawn_cleanup;
  2723. }
  2724. if (mg_fopen(conn, cmdline, "r", &file)) {
  2725. p = (char *)file.membuf;
  2726. mg_fgets(buf, sizeof(buf), &file, &p);
  2727. mg_fclose(&file);
  2728. buf[sizeof(buf) - 1] = '\0';
  2729. }
  2730. if (buf[0] == '#' && buf[1] == '!') {
  2731. trim_trailing_whitespaces(buf + 2);
  2732. } else {
  2733. buf[2] = '\0';
  2734. }
  2735. interp = buf + 2;
  2736. }
  2737. if (interp[0] != '\0') {
  2738. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2739. interp = full_interp;
  2740. }
  2741. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2742. if (interp[0] != '\0') {
  2743. mg_snprintf(conn,
  2744. &truncated,
  2745. cmdline,
  2746. sizeof(cmdline),
  2747. "\"%s\" \"%s\\%s\"",
  2748. interp,
  2749. full_dir,
  2750. prog);
  2751. } else {
  2752. mg_snprintf(conn,
  2753. &truncated,
  2754. cmdline,
  2755. sizeof(cmdline),
  2756. "\"%s\\%s\"",
  2757. full_dir,
  2758. prog);
  2759. }
  2760. if (truncated) {
  2761. pi.hProcess = (pid_t)-1;
  2762. goto spawn_cleanup;
  2763. }
  2764. DEBUG_TRACE("Running [%s]", cmdline);
  2765. if (CreateProcessA(NULL,
  2766. cmdline,
  2767. NULL,
  2768. NULL,
  2769. TRUE,
  2770. CREATE_NEW_PROCESS_GROUP,
  2771. envblk,
  2772. NULL,
  2773. &si,
  2774. &pi) == 0) {
  2775. mg_cry(
  2776. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2777. pi.hProcess = (pid_t)-1;
  2778. /* goto spawn_cleanup; */
  2779. }
  2780. spawn_cleanup:
  2781. (void)CloseHandle(si.hStdOutput);
  2782. (void)CloseHandle(si.hStdError);
  2783. (void)CloseHandle(si.hStdInput);
  2784. if (pi.hThread != NULL) {
  2785. (void)CloseHandle(pi.hThread);
  2786. }
  2787. return (pid_t)pi.hProcess;
  2788. }
  2789. #endif /* !NO_CGI */
  2790. static int
  2791. set_non_blocking_mode(SOCKET sock)
  2792. {
  2793. unsigned long on = 1;
  2794. return ioctlsocket(sock, (long)FIONBIO, &on);
  2795. }
  2796. #else
  2797. static int
  2798. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2799. {
  2800. struct stat st;
  2801. if (!filep) {
  2802. return 0;
  2803. }
  2804. memset(filep, 0, sizeof(*filep));
  2805. if (conn && is_file_in_memory(conn, path, filep)) {
  2806. return 1;
  2807. }
  2808. if (0 == stat(path, &st)) {
  2809. filep->size = (uint64_t)(st.st_size);
  2810. filep->last_modified = st.st_mtime;
  2811. filep->is_directory = S_ISDIR(st.st_mode);
  2812. return 1;
  2813. }
  2814. return 0;
  2815. }
  2816. static void
  2817. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2818. {
  2819. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2820. if (conn) {
  2821. mg_cry(conn,
  2822. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2823. __func__,
  2824. strerror(ERRNO));
  2825. }
  2826. }
  2827. }
  2828. int
  2829. mg_start_thread(mg_thread_func_t func, void *param)
  2830. {
  2831. pthread_t thread_id;
  2832. pthread_attr_t attr;
  2833. int result;
  2834. (void)pthread_attr_init(&attr);
  2835. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2836. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2837. /* Compile-time option to control stack size,
  2838. * e.g. -DUSE_STACK_SIZE=16384 */
  2839. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2840. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2841. result = pthread_create(&thread_id, &attr, func, param);
  2842. pthread_attr_destroy(&attr);
  2843. return result;
  2844. }
  2845. /* Start a thread storing the thread context. */
  2846. static int
  2847. mg_start_thread_with_id(mg_thread_func_t func,
  2848. void *param,
  2849. pthread_t *threadidptr)
  2850. {
  2851. pthread_t thread_id;
  2852. pthread_attr_t attr;
  2853. int result;
  2854. (void)pthread_attr_init(&attr);
  2855. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2856. /* Compile-time option to control stack size,
  2857. * e.g. -DUSE_STACK_SIZE=16384 */
  2858. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2859. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2860. result = pthread_create(&thread_id, &attr, func, param);
  2861. pthread_attr_destroy(&attr);
  2862. if ((result == 0) && (threadidptr != NULL)) {
  2863. *threadidptr = thread_id;
  2864. }
  2865. return result;
  2866. }
  2867. /* Wait for a thread to finish. */
  2868. static int
  2869. mg_join_thread(pthread_t threadid)
  2870. {
  2871. int result;
  2872. result = pthread_join(threadid, NULL);
  2873. return result;
  2874. }
  2875. #ifndef NO_CGI
  2876. static pid_t
  2877. spawn_process(struct mg_connection *conn,
  2878. const char *prog,
  2879. char *envblk,
  2880. char *envp[],
  2881. int fdin,
  2882. int fdout,
  2883. int fderr,
  2884. const char *dir)
  2885. {
  2886. pid_t pid;
  2887. const char *interp;
  2888. (void)envblk;
  2889. if (conn == NULL) {
  2890. return 0;
  2891. }
  2892. if ((pid = fork()) == -1) {
  2893. /* Parent */
  2894. send_http_error(conn,
  2895. 500,
  2896. "Error: Creating CGI process\nfork(): %s",
  2897. strerror(ERRNO));
  2898. } else if (pid == 0) {
  2899. /* Child */
  2900. if (chdir(dir) != 0) {
  2901. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2902. } else if (dup2(fdin, 0) == -1) {
  2903. mg_cry(
  2904. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2905. } else if (dup2(fdout, 1) == -1) {
  2906. mg_cry(
  2907. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2908. } else if (dup2(fderr, 2) == -1) {
  2909. mg_cry(
  2910. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2911. } else {
  2912. /* Keep stderr and stdout in two different pipes.
  2913. * Stdout will be sent back to the client,
  2914. * stderr should go into a server error log. */
  2915. (void)close(fdin);
  2916. (void)close(fdout);
  2917. (void)close(fderr);
  2918. /* After exec, all signal handlers are restored to their default
  2919. * values, with one exception of SIGCHLD. According to
  2920. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2921. * leave unchanged after exec if it was set to be ignored. Restore
  2922. * it to default action. */
  2923. signal(SIGCHLD, SIG_DFL);
  2924. interp = conn->ctx->config[CGI_INTERPRETER];
  2925. if (interp == NULL) {
  2926. (void)execle(prog, prog, NULL, envp);
  2927. mg_cry(conn,
  2928. "%s: execle(%s): %s",
  2929. __func__,
  2930. prog,
  2931. strerror(ERRNO));
  2932. } else {
  2933. (void)execle(interp, interp, prog, NULL, envp);
  2934. mg_cry(conn,
  2935. "%s: execle(%s %s): %s",
  2936. __func__,
  2937. interp,
  2938. prog,
  2939. strerror(ERRNO));
  2940. }
  2941. }
  2942. exit(EXIT_FAILURE);
  2943. }
  2944. return pid;
  2945. }
  2946. #endif /* !NO_CGI */
  2947. static int
  2948. set_non_blocking_mode(SOCKET sock)
  2949. {
  2950. int flags;
  2951. flags = fcntl(sock, F_GETFL, 0);
  2952. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2953. return 0;
  2954. }
  2955. #endif /* _WIN32 */
  2956. /* End of initial operating system specific define block. */
  2957. /* Get a random number (independent of C rand function) */
  2958. static uint64_t
  2959. get_random(void)
  2960. {
  2961. static uint64_t lfsr = 0; /* Linear feedback shift register */
  2962. static uint64_t lcg = 0; /* Linear congruential generator */
  2963. struct timespec now;
  2964. memset(&now, 0, sizeof(now));
  2965. clock_gettime(CLOCK_MONOTONIC, &now);
  2966. if (lfsr == 0) {
  2967. /* lfsr will be only 0 if has not been initialized,
  2968. * so this code is called only once. */
  2969. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  2970. ^ ((uint64_t)(ptrdiff_t)&now) ^ ((uint64_t)pthread_self())
  2971. ^ (((uint64_t)time(NULL)) << 33);
  2972. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  2973. + (uint64_t)(ptrdiff_t)&now;
  2974. } else {
  2975. /* Get the next step of both random number generators. */
  2976. lfsr = (lfsr >> 1)
  2977. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  2978. << 63);
  2979. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  2980. }
  2981. /* Combining two pseudo-random number generators and a high resolution part
  2982. * of the current server time will make it hard (impossible?) to guess the
  2983. * next number. */
  2984. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  2985. }
  2986. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2987. * descriptor. Return number of bytes written. */
  2988. static int
  2989. push(struct mg_context *ctx,
  2990. FILE *fp,
  2991. SOCKET sock,
  2992. SSL *ssl,
  2993. const char *buf,
  2994. int len,
  2995. double timeout)
  2996. {
  2997. struct timespec start, now;
  2998. int n, err;
  2999. #ifdef _WIN32
  3000. typedef int len_t;
  3001. #else
  3002. typedef size_t len_t;
  3003. #endif
  3004. if (timeout > 0) {
  3005. memset(&start, 0, sizeof(start));
  3006. memset(&now, 0, sizeof(now));
  3007. clock_gettime(CLOCK_MONOTONIC, &start);
  3008. }
  3009. if (ctx == NULL) {
  3010. return -1;
  3011. }
  3012. #ifdef NO_SSL
  3013. if (ssl) {
  3014. return -1;
  3015. }
  3016. #endif
  3017. do {
  3018. #ifndef NO_SSL
  3019. if (ssl != NULL) {
  3020. n = SSL_write(ssl, buf, len);
  3021. if (n <= 0) {
  3022. err = SSL_get_error(ssl, n);
  3023. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3024. err = ERRNO;
  3025. } else {
  3026. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3027. return -1;
  3028. }
  3029. } else {
  3030. err = 0;
  3031. }
  3032. } else
  3033. #endif
  3034. if (fp != NULL) {
  3035. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3036. if (ferror(fp)) {
  3037. n = -1;
  3038. err = ERRNO;
  3039. } else {
  3040. err = 0;
  3041. }
  3042. } else {
  3043. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3044. err = (n < 0) ? ERRNO : 0;
  3045. }
  3046. if (ctx->stop_flag) {
  3047. return -1;
  3048. }
  3049. if ((n > 0) || (n == 0 && len == 0)) {
  3050. /* some data has been read, or no data was requested */
  3051. return n;
  3052. }
  3053. if (n == 0) {
  3054. /* shutdown of the socket at client side */
  3055. return -1;
  3056. }
  3057. if (n < 0) {
  3058. /* socket error - check errno */
  3059. DEBUG_TRACE("send() failed, error %d", err);
  3060. /* TODO: error handling depending on the error code.
  3061. * These codes are different between Windows and Linux.
  3062. */
  3063. return -1;
  3064. }
  3065. if (timeout > 0) {
  3066. clock_gettime(CLOCK_MONOTONIC, &now);
  3067. }
  3068. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3069. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3070. used */
  3071. return -1;
  3072. }
  3073. static int64_t
  3074. push_all(struct mg_context *ctx,
  3075. FILE *fp,
  3076. SOCKET sock,
  3077. SSL *ssl,
  3078. const char *buf,
  3079. int64_t len)
  3080. {
  3081. double timeout = -1.0;
  3082. int64_t n, nwritten = 0;
  3083. if (ctx == NULL) {
  3084. return -1;
  3085. }
  3086. if (ctx->config[REQUEST_TIMEOUT]) {
  3087. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3088. }
  3089. while (len > 0 && ctx->stop_flag == 0) {
  3090. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3091. if (n < 0) {
  3092. if (nwritten == 0) {
  3093. nwritten = n; /* Propagate the error */
  3094. }
  3095. break;
  3096. } else if (n == 0) {
  3097. break; /* No more data to write */
  3098. } else {
  3099. nwritten += n;
  3100. len -= n;
  3101. }
  3102. }
  3103. return nwritten;
  3104. }
  3105. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3106. * Return negative value on error, or number of bytes read on success. */
  3107. static int
  3108. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3109. {
  3110. int nread, err;
  3111. struct timespec start, now;
  3112. #ifdef _WIN32
  3113. typedef int len_t;
  3114. #else
  3115. typedef size_t len_t;
  3116. #endif
  3117. if (timeout > 0) {
  3118. memset(&start, 0, sizeof(start));
  3119. memset(&now, 0, sizeof(now));
  3120. clock_gettime(CLOCK_MONOTONIC, &start);
  3121. }
  3122. do {
  3123. if (fp != NULL) {
  3124. /* Use read() instead of fread(), because if we're reading from the
  3125. * CGI pipe, fread() may block until IO buffer is filled up. We
  3126. * cannot afford to block and must pass all read bytes immediately
  3127. * to the client. */
  3128. nread = (int)read(fileno(fp), buf, (size_t)len);
  3129. err = (nread < 0) ? ERRNO : 0;
  3130. #ifndef NO_SSL
  3131. } else if (conn->ssl != NULL) {
  3132. nread = SSL_read(conn->ssl, buf, len);
  3133. if (nread <= 0) {
  3134. err = SSL_get_error(conn->ssl, nread);
  3135. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3136. err = ERRNO;
  3137. } else {
  3138. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3139. return -1;
  3140. }
  3141. } else {
  3142. err = 0;
  3143. }
  3144. #endif
  3145. } else {
  3146. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3147. err = (nread < 0) ? ERRNO : 0;
  3148. }
  3149. if (conn->ctx->stop_flag) {
  3150. return -1;
  3151. }
  3152. if ((nread > 0) || (nread == 0 && len == 0)) {
  3153. /* some data has been read, or no data was requested */
  3154. return nread;
  3155. }
  3156. if (nread == 0) {
  3157. /* shutdown of the socket at client side */
  3158. return -1;
  3159. }
  3160. if (nread < 0) {
  3161. /* socket error - check errno */
  3162. #ifdef _WIN32
  3163. if (err == WSAEWOULDBLOCK) {
  3164. /* standard case if called from close_socket_gracefully */
  3165. return -1;
  3166. } else if (err == WSAETIMEDOUT) {
  3167. /* timeout is handled by the while loop */
  3168. } else {
  3169. DEBUG_TRACE("recv() failed, error %d", err);
  3170. return -1;
  3171. }
  3172. #else
  3173. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3174. * if the timeout is reached and if the socket was set to non-
  3175. * blocking in close_socket_gracefully, so we can not distinguish
  3176. * here. We have to wait for the timeout in both cases for now.
  3177. */
  3178. if (err == EAGAIN || err == EWOULDBLOCK) {
  3179. /* standard case if called from close_socket_gracefully
  3180. * => should return -1 */
  3181. /* or timeout occured
  3182. * => the code must stay in the while loop */
  3183. } else {
  3184. DEBUG_TRACE("recv() failed, error %d", err);
  3185. return -1;
  3186. }
  3187. #endif
  3188. }
  3189. if (timeout > 0) {
  3190. clock_gettime(CLOCK_MONOTONIC, &now);
  3191. }
  3192. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3193. /* Timeout occured, but no data available. */
  3194. return -1;
  3195. }
  3196. static int
  3197. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3198. {
  3199. int n, nread = 0;
  3200. double timeout = -1.0;
  3201. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3202. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3203. }
  3204. while (len > 0 && conn->ctx->stop_flag == 0) {
  3205. n = pull(fp, conn, buf + nread, len, timeout);
  3206. if (n < 0) {
  3207. if (nread == 0) {
  3208. nread = n; /* Propagate the error */
  3209. }
  3210. break;
  3211. } else if (n == 0) {
  3212. break; /* No more data to read */
  3213. } else {
  3214. conn->consumed_content += n;
  3215. nread += n;
  3216. len -= n;
  3217. }
  3218. }
  3219. return nread;
  3220. }
  3221. static void
  3222. discard_unread_request_data(struct mg_connection *conn)
  3223. {
  3224. char buf[MG_BUF_LEN];
  3225. size_t to_read;
  3226. int nread;
  3227. if (conn == NULL) {
  3228. return;
  3229. }
  3230. to_read = sizeof(buf);
  3231. if (conn->is_chunked) {
  3232. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3233. * completely */
  3234. while (conn->is_chunked == 1) {
  3235. nread = mg_read(conn, buf, to_read);
  3236. if (nread <= 0) {
  3237. break;
  3238. }
  3239. }
  3240. } else {
  3241. /* Not chunked: content length is known */
  3242. while (conn->consumed_content < conn->content_len) {
  3243. if (to_read
  3244. > (size_t)(conn->content_len - conn->consumed_content)) {
  3245. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3246. }
  3247. nread = mg_read(conn, buf, to_read);
  3248. if (nread <= 0) {
  3249. break;
  3250. }
  3251. }
  3252. }
  3253. }
  3254. static int
  3255. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3256. {
  3257. int64_t n, buffered_len, nread;
  3258. int64_t len64 =
  3259. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3260. * int, we may not read more
  3261. * bytes */
  3262. const char *body;
  3263. if (conn == NULL) {
  3264. return 0;
  3265. }
  3266. /* If Content-Length is not set for a PUT or POST request, read until
  3267. * socket is closed */
  3268. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3269. conn->content_len = INT64_MAX;
  3270. conn->must_close = 1;
  3271. }
  3272. nread = 0;
  3273. if (conn->consumed_content < conn->content_len) {
  3274. /* Adjust number of bytes to read. */
  3275. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3276. if (left_to_read < len64) {
  3277. /* Do not read more than the total content length of the request.
  3278. */
  3279. len64 = left_to_read;
  3280. }
  3281. /* Return buffered data */
  3282. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3283. - conn->consumed_content;
  3284. if (buffered_len > 0) {
  3285. if (len64 < buffered_len) {
  3286. buffered_len = len64;
  3287. }
  3288. body = conn->buf + conn->request_len + conn->consumed_content;
  3289. memcpy(buf, body, (size_t)buffered_len);
  3290. len64 -= buffered_len;
  3291. conn->consumed_content += buffered_len;
  3292. nread += buffered_len;
  3293. buf = (char *)buf + buffered_len;
  3294. }
  3295. /* We have returned all buffered data. Read new data from the remote
  3296. * socket.
  3297. */
  3298. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3299. nread += n;
  3300. } else {
  3301. nread = (nread > 0 ? nread : n);
  3302. }
  3303. }
  3304. return (int)nread;
  3305. }
  3306. static char
  3307. mg_getc(struct mg_connection *conn)
  3308. {
  3309. char c;
  3310. if (conn == NULL) {
  3311. return 0;
  3312. }
  3313. conn->content_len++;
  3314. if (mg_read_inner(conn, &c, 1) <= 0) {
  3315. return (char)0;
  3316. }
  3317. return c;
  3318. }
  3319. int
  3320. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3321. {
  3322. if (len > INT_MAX) {
  3323. len = INT_MAX;
  3324. }
  3325. if (conn == NULL) {
  3326. return 0;
  3327. }
  3328. if (conn->is_chunked) {
  3329. size_t all_read = 0;
  3330. while (len > 0) {
  3331. if (conn->chunk_remainder) {
  3332. /* copy from the remainder of the last received chunk */
  3333. long read_ret;
  3334. size_t read_now =
  3335. ((conn->chunk_remainder > len) ? (len)
  3336. : (conn->chunk_remainder));
  3337. conn->content_len += (int)read_now;
  3338. read_ret =
  3339. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3340. all_read += (size_t)read_ret;
  3341. conn->chunk_remainder -= read_now;
  3342. len -= read_now;
  3343. if (conn->chunk_remainder == 0) {
  3344. /* the rest of the data in the current chunk has been read
  3345. */
  3346. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3347. /* Protocol violation */
  3348. return -1;
  3349. }
  3350. }
  3351. } else {
  3352. /* fetch a new chunk */
  3353. int i = 0;
  3354. char lenbuf[64];
  3355. char *end = 0;
  3356. unsigned long chunkSize = 0;
  3357. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3358. lenbuf[i] = mg_getc(conn);
  3359. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3360. continue;
  3361. }
  3362. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3363. lenbuf[i + 1] = 0;
  3364. chunkSize = strtoul(lenbuf, &end, 16);
  3365. break;
  3366. }
  3367. if (!isalnum(lenbuf[i])) {
  3368. /* illegal character for chunk length */
  3369. return -1;
  3370. }
  3371. }
  3372. if ((end == NULL) || (*end != '\r')) {
  3373. /* chunksize not set correctly */
  3374. return -1;
  3375. }
  3376. conn->chunk_remainder = chunkSize;
  3377. if (chunkSize == 0) {
  3378. /* regular end of content */
  3379. conn->is_chunked = 2;
  3380. break;
  3381. }
  3382. }
  3383. }
  3384. return (int)all_read;
  3385. }
  3386. return mg_read_inner(conn, buf, len);
  3387. }
  3388. int
  3389. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3390. {
  3391. time_t now;
  3392. int64_t n, total, allowed;
  3393. if (conn == NULL) {
  3394. return 0;
  3395. }
  3396. if (conn->throttle > 0) {
  3397. if ((now = time(NULL)) != conn->last_throttle_time) {
  3398. conn->last_throttle_time = now;
  3399. conn->last_throttle_bytes = 0;
  3400. }
  3401. allowed = conn->throttle - conn->last_throttle_bytes;
  3402. if (allowed > (int64_t)len) {
  3403. allowed = (int64_t)len;
  3404. }
  3405. if ((total = push_all(conn->ctx,
  3406. NULL,
  3407. conn->client.sock,
  3408. conn->ssl,
  3409. (const char *)buf,
  3410. (int64_t)allowed)) == allowed) {
  3411. buf = (char *)buf + total;
  3412. conn->last_throttle_bytes += total;
  3413. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3414. allowed = conn->throttle > (int64_t)len - total
  3415. ? (int64_t)len - total
  3416. : conn->throttle;
  3417. if ((n = push_all(conn->ctx,
  3418. NULL,
  3419. conn->client.sock,
  3420. conn->ssl,
  3421. (const char *)buf,
  3422. (int64_t)allowed)) != allowed) {
  3423. break;
  3424. }
  3425. sleep(1);
  3426. conn->last_throttle_bytes = allowed;
  3427. conn->last_throttle_time = time(NULL);
  3428. buf = (char *)buf + n;
  3429. total += n;
  3430. }
  3431. }
  3432. } else {
  3433. total = push_all(conn->ctx,
  3434. NULL,
  3435. conn->client.sock,
  3436. conn->ssl,
  3437. (const char *)buf,
  3438. (int64_t)len);
  3439. }
  3440. return (int)total;
  3441. }
  3442. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3443. static int
  3444. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3445. {
  3446. va_list ap_copy;
  3447. size_t size = MG_BUF_LEN;
  3448. int len = -1;
  3449. *buf = NULL;
  3450. while (len < 0) {
  3451. if (*buf) {
  3452. mg_free(*buf);
  3453. }
  3454. *buf = (char *)mg_malloc(size *= 4);
  3455. if (!*buf) {
  3456. break;
  3457. }
  3458. va_copy(ap_copy, ap);
  3459. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3460. va_end(ap_copy);
  3461. *buf[size - 1] = 0;
  3462. }
  3463. return len;
  3464. }
  3465. /* Print message to buffer. If buffer is large enough to hold the message,
  3466. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3467. * and return allocated buffer. */
  3468. static int
  3469. alloc_vprintf(char **out_buf,
  3470. char *prealloc_buf,
  3471. size_t prealloc_size,
  3472. const char *fmt,
  3473. va_list ap)
  3474. {
  3475. va_list ap_copy;
  3476. int len;
  3477. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3478. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3479. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3480. * Therefore, we make two passes: on first pass, get required message
  3481. * length.
  3482. * On second pass, actually print the message. */
  3483. va_copy(ap_copy, ap);
  3484. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3485. va_end(ap_copy);
  3486. if (len < 0) {
  3487. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3488. * Switch to alternative code path that uses incremental allocations.
  3489. */
  3490. va_copy(ap_copy, ap);
  3491. len = alloc_vprintf2(out_buf, fmt, ap);
  3492. va_end(ap_copy);
  3493. } else if ((size_t)(len) >= prealloc_size) {
  3494. /* The pre-allocated buffer not large enough. */
  3495. /* Allocate a new buffer. */
  3496. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3497. if (!*out_buf) {
  3498. /* Allocation failed. Return -1 as "out of memory" error. */
  3499. return -1;
  3500. }
  3501. /* Buffer allocation successful. Store the string there. */
  3502. va_copy(ap_copy, ap);
  3503. IGNORE_UNUSED_RESULT(
  3504. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3505. va_end(ap_copy);
  3506. } else {
  3507. /* The pre-allocated buffer is large enough.
  3508. * Use it to store the string and return the address. */
  3509. va_copy(ap_copy, ap);
  3510. IGNORE_UNUSED_RESULT(
  3511. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3512. va_end(ap_copy);
  3513. *out_buf = prealloc_buf;
  3514. }
  3515. return len;
  3516. }
  3517. static int
  3518. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3519. {
  3520. char mem[MG_BUF_LEN];
  3521. char *buf = NULL;
  3522. int len;
  3523. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3524. len = mg_write(conn, buf, (size_t)len);
  3525. }
  3526. if (buf != mem && buf != NULL) {
  3527. mg_free(buf);
  3528. }
  3529. return len;
  3530. }
  3531. int
  3532. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3533. {
  3534. va_list ap;
  3535. int result;
  3536. va_start(ap, fmt);
  3537. result = mg_vprintf(conn, fmt, ap);
  3538. va_end(ap);
  3539. return result;
  3540. }
  3541. int
  3542. mg_url_decode(const char *src,
  3543. int src_len,
  3544. char *dst,
  3545. int dst_len,
  3546. int is_form_url_encoded)
  3547. {
  3548. int i, j, a, b;
  3549. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3550. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3551. if (i < src_len - 2 && src[i] == '%'
  3552. && isxdigit(*(const unsigned char *)(src + i + 1))
  3553. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3554. a = tolower(*(const unsigned char *)(src + i + 1));
  3555. b = tolower(*(const unsigned char *)(src + i + 2));
  3556. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3557. i += 2;
  3558. } else if (is_form_url_encoded && src[i] == '+') {
  3559. dst[j] = ' ';
  3560. } else {
  3561. dst[j] = src[i];
  3562. }
  3563. }
  3564. dst[j] = '\0'; /* Null-terminate the destination */
  3565. return i >= src_len ? j : -1;
  3566. }
  3567. int
  3568. mg_get_var(const char *data,
  3569. size_t data_len,
  3570. const char *name,
  3571. char *dst,
  3572. size_t dst_len)
  3573. {
  3574. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3575. }
  3576. int
  3577. mg_get_var2(const char *data,
  3578. size_t data_len,
  3579. const char *name,
  3580. char *dst,
  3581. size_t dst_len,
  3582. size_t occurrence)
  3583. {
  3584. const char *p, *e, *s;
  3585. size_t name_len;
  3586. int len;
  3587. if (dst == NULL || dst_len == 0) {
  3588. len = -2;
  3589. } else if (data == NULL || name == NULL || data_len == 0) {
  3590. len = -1;
  3591. dst[0] = '\0';
  3592. } else {
  3593. name_len = strlen(name);
  3594. e = data + data_len;
  3595. len = -1;
  3596. dst[0] = '\0';
  3597. /* data is "var1=val1&var2=val2...". Find variable first */
  3598. for (p = data; p + name_len < e; p++) {
  3599. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3600. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3601. /* Point p to variable value */
  3602. p += name_len + 1;
  3603. /* Point s to the end of the value */
  3604. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3605. if (s == NULL) {
  3606. s = e;
  3607. }
  3608. /* assert(s >= p); */
  3609. if (s < p) {
  3610. return -3;
  3611. }
  3612. /* Decode variable into destination buffer */
  3613. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3614. /* Redirect error code from -1 to -2 (destination buffer too
  3615. * small). */
  3616. if (len == -1) {
  3617. len = -2;
  3618. }
  3619. break;
  3620. }
  3621. }
  3622. }
  3623. return len;
  3624. }
  3625. int
  3626. mg_get_cookie(const char *cookie_header,
  3627. const char *var_name,
  3628. char *dst,
  3629. size_t dst_size)
  3630. {
  3631. const char *s, *p, *end;
  3632. int name_len, len = -1;
  3633. if (dst == NULL || dst_size == 0) {
  3634. len = -2;
  3635. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3636. len = -1;
  3637. dst[0] = '\0';
  3638. } else {
  3639. name_len = (int)strlen(var_name);
  3640. end = s + strlen(s);
  3641. dst[0] = '\0';
  3642. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3643. if (s[name_len] == '=') {
  3644. s += name_len + 1;
  3645. if ((p = strchr(s, ' ')) == NULL) {
  3646. p = end;
  3647. }
  3648. if (p[-1] == ';') {
  3649. p--;
  3650. }
  3651. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3652. s++;
  3653. p--;
  3654. }
  3655. if ((size_t)(p - s) < dst_size) {
  3656. len = (int)(p - s);
  3657. mg_strlcpy(dst, s, (size_t)len + 1);
  3658. } else {
  3659. len = -3;
  3660. }
  3661. break;
  3662. }
  3663. }
  3664. }
  3665. return len;
  3666. }
  3667. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3668. static void
  3669. base64_encode(const unsigned char *src, int src_len, char *dst)
  3670. {
  3671. static const char *b64 =
  3672. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3673. int i, j, a, b, c;
  3674. for (i = j = 0; i < src_len; i += 3) {
  3675. a = src[i];
  3676. b = i + 1 >= src_len ? 0 : src[i + 1];
  3677. c = i + 2 >= src_len ? 0 : src[i + 2];
  3678. dst[j++] = b64[a >> 2];
  3679. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3680. if (i + 1 < src_len) {
  3681. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3682. }
  3683. if (i + 2 < src_len) {
  3684. dst[j++] = b64[c & 63];
  3685. }
  3686. }
  3687. while (j % 4 != 0) {
  3688. dst[j++] = '=';
  3689. }
  3690. dst[j++] = '\0';
  3691. }
  3692. #endif
  3693. #if defined(USE_LUA)
  3694. static unsigned char
  3695. b64reverse(char letter)
  3696. {
  3697. if (letter >= 'A' && letter <= 'Z') {
  3698. return letter - 'A';
  3699. }
  3700. if (letter >= 'a' && letter <= 'z') {
  3701. return letter - 'a' + 26;
  3702. }
  3703. if (letter >= '0' && letter <= '9') {
  3704. return letter - '0' + 52;
  3705. }
  3706. if (letter == '+') {
  3707. return 62;
  3708. }
  3709. if (letter == '/') {
  3710. return 63;
  3711. }
  3712. if (letter == '=') {
  3713. return 255; /* normal end */
  3714. }
  3715. return 254; /* error */
  3716. }
  3717. static int
  3718. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3719. {
  3720. int i;
  3721. unsigned char a, b, c, d;
  3722. *dst_len = 0;
  3723. for (i = 0; i < src_len; i += 4) {
  3724. a = b64reverse(src[i]);
  3725. if (a >= 254) {
  3726. return i;
  3727. }
  3728. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3729. if (b >= 254) {
  3730. return i + 1;
  3731. }
  3732. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3733. if (c == 254) {
  3734. return i + 2;
  3735. }
  3736. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3737. if (d == 254) {
  3738. return i + 3;
  3739. }
  3740. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3741. if (c != 255) {
  3742. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3743. if (d != 255) {
  3744. dst[(*dst_len)++] = (c << 6) + d;
  3745. }
  3746. }
  3747. }
  3748. return -1;
  3749. }
  3750. #endif
  3751. static int
  3752. is_put_or_delete_method(const struct mg_connection *conn)
  3753. {
  3754. if (conn) {
  3755. const char *s = conn->request_info.request_method;
  3756. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3757. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3758. }
  3759. return 0;
  3760. }
  3761. static void
  3762. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3763. char *filename, /* out: filename */
  3764. size_t filename_buf_len, /* in: size of filename buffer */
  3765. struct file *filep, /* out: file structure */
  3766. int *is_found, /* out: file is found (directly) */
  3767. int *is_script_resource, /* out: handled by a script? */
  3768. int *is_websocket_request, /* out: websocket connetion? */
  3769. int *is_put_or_delete_request /* out: put/delete a file? */
  3770. )
  3771. {
  3772. /* TODO (high): Restructure this function */
  3773. #if !defined(NO_FILES)
  3774. const char *uri = conn->request_info.local_uri;
  3775. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3776. const char *rewrite;
  3777. struct vec a, b;
  3778. int match_len;
  3779. char gz_path[PATH_MAX];
  3780. char const *accept_encoding;
  3781. int truncated;
  3782. #if !defined(NO_CGI) || defined(USE_LUA)
  3783. char *p;
  3784. #endif
  3785. #else
  3786. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3787. #endif
  3788. memset(filep, 0, sizeof(*filep));
  3789. *filename = 0;
  3790. *is_found = 0;
  3791. *is_script_resource = 0;
  3792. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3793. #if defined(USE_WEBSOCKET)
  3794. *is_websocket_request = is_websocket_protocol(conn);
  3795. #if !defined(NO_FILES)
  3796. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3797. root = conn->ctx->config[WEBSOCKET_ROOT];
  3798. }
  3799. #endif /* !NO_FILES */
  3800. #else /* USE_WEBSOCKET */
  3801. *is_websocket_request = 0;
  3802. #endif /* USE_WEBSOCKET */
  3803. #if !defined(NO_FILES)
  3804. /* Note that root == NULL is a regular use case here. This occurs,
  3805. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3806. * config is not required. */
  3807. if (root == NULL) {
  3808. /* all file related outputs have already been set to 0, just return
  3809. */
  3810. return;
  3811. }
  3812. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3813. * of the path one byte on the right.
  3814. * If document_root is NULL, leave the file empty. */
  3815. mg_snprintf(
  3816. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3817. if (truncated) {
  3818. goto interpret_cleanup;
  3819. }
  3820. rewrite = conn->ctx->config[REWRITE];
  3821. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3822. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3823. mg_snprintf(conn,
  3824. &truncated,
  3825. filename,
  3826. filename_buf_len - 1,
  3827. "%.*s%s",
  3828. (int)b.len,
  3829. b.ptr,
  3830. uri + match_len);
  3831. break;
  3832. }
  3833. }
  3834. if (truncated) {
  3835. goto interpret_cleanup;
  3836. }
  3837. /* Local file path and name, corresponding to requested URI
  3838. * is now stored in "filename" variable. */
  3839. if (mg_stat(conn, filename, filep)) {
  3840. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3841. /* File exists. Check if it is a script type. */
  3842. if (0
  3843. #if !defined(NO_CGI)
  3844. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3845. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3846. filename) > 0
  3847. #endif
  3848. #if defined(USE_LUA)
  3849. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3850. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3851. filename) > 0
  3852. #endif
  3853. #if defined(USE_DUKTAPE)
  3854. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3855. strlen(
  3856. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3857. filename) > 0
  3858. #endif
  3859. ) {
  3860. /* The request addresses a CGI script or a Lua script. The URI
  3861. * corresponds to the script itself (like /path/script.cgi),
  3862. * and there is no additional resource path
  3863. * (like /path/script.cgi/something).
  3864. * Requests that modify (replace or delete) a resource, like
  3865. * PUT and DELETE requests, should replace/delete the script
  3866. * file.
  3867. * Requests that read or write from/to a resource, like GET and
  3868. * POST requests, should call the script and return the
  3869. * generated response. */
  3870. *is_script_resource = !*is_put_or_delete_request;
  3871. }
  3872. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3873. *is_found = 1;
  3874. return;
  3875. }
  3876. /* If we can't find the actual file, look for the file
  3877. * with the same name but a .gz extension. If we find it,
  3878. * use that and set the gzipped flag in the file struct
  3879. * to indicate that the response need to have the content-
  3880. * encoding: gzip header.
  3881. * We can only do this if the browser declares support. */
  3882. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3883. if (strstr(accept_encoding, "gzip") != NULL) {
  3884. mg_snprintf(
  3885. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3886. if (truncated) {
  3887. goto interpret_cleanup;
  3888. }
  3889. if (mg_stat(conn, gz_path, filep)) {
  3890. if (filep) {
  3891. filep->gzipped = 1;
  3892. *is_found = 1;
  3893. }
  3894. /* Currently gz files can not be scripts. */
  3895. return;
  3896. }
  3897. }
  3898. }
  3899. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3900. /* Support PATH_INFO for CGI scripts. */
  3901. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3902. if (*p == '/') {
  3903. *p = '\0';
  3904. if ((0
  3905. #if !defined(NO_CGI)
  3906. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3907. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3908. filename) > 0
  3909. #endif
  3910. #if defined(USE_LUA)
  3911. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3912. strlen(
  3913. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3914. filename) > 0
  3915. #endif
  3916. #if defined(USE_DUKTAPE)
  3917. || match_prefix(
  3918. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3919. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3920. filename) > 0
  3921. #endif
  3922. ) && mg_stat(conn, filename, filep)) {
  3923. /* Shift PATH_INFO block one character right, e.g.
  3924. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3925. * conn->path_info is pointing to the local variable "path"
  3926. * declared in handle_request(), so PATH_INFO is not valid
  3927. * after handle_request returns. */
  3928. conn->path_info = p + 1;
  3929. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3930. * trailing \0 */
  3931. p[1] = '/';
  3932. *is_script_resource = 1;
  3933. break;
  3934. } else {
  3935. *p = '/';
  3936. }
  3937. }
  3938. }
  3939. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3940. #endif /* !defined(NO_FILES) */
  3941. return;
  3942. #if !defined(NO_FILES)
  3943. /* Reset all outputs */
  3944. interpret_cleanup:
  3945. memset(filep, 0, sizeof(*filep));
  3946. *filename = 0;
  3947. *is_found = 0;
  3948. *is_script_resource = 0;
  3949. *is_websocket_request = 0;
  3950. *is_put_or_delete_request = 0;
  3951. #endif /* !defined(NO_FILES) */
  3952. }
  3953. /* Check whether full request is buffered. Return:
  3954. * -1 if request is malformed
  3955. * 0 if request is not yet fully buffered
  3956. * >0 actual request length, including last \r\n\r\n */
  3957. static int
  3958. get_request_len(const char *buf, int buflen)
  3959. {
  3960. const char *s, *e;
  3961. int len = 0;
  3962. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3963. /* Control characters are not allowed but >=128 is. */
  3964. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  3965. && *(const unsigned char *)s < 128) {
  3966. len = -1;
  3967. break; /* [i_a] abort scan as soon as one malformed character is
  3968. * found; */
  3969. /* don't let subsequent \r\n\r\n win us over anyhow */
  3970. } else if (s[0] == '\n' && s[1] == '\n') {
  3971. len = (int)(s - buf) + 2;
  3972. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3973. len = (int)(s - buf) + 3;
  3974. }
  3975. return len;
  3976. }
  3977. /* Convert month to the month number. Return -1 on error, or month number */
  3978. static int
  3979. get_month_index(const char *s)
  3980. {
  3981. size_t i;
  3982. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3983. if (!strcmp(s, month_names[i])) {
  3984. return (int)i;
  3985. }
  3986. }
  3987. return -1;
  3988. }
  3989. static int
  3990. num_leap_years(int year)
  3991. {
  3992. return year / 4 - year / 100 + year / 400;
  3993. }
  3994. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3995. static time_t
  3996. parse_date_string(const char *datetime)
  3997. {
  3998. static const unsigned short days_before_month[] = {
  3999. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  4000. char month_str[32] = {0};
  4001. int second, minute, hour, day, month, year, leap_days, days;
  4002. time_t result = (time_t)0;
  4003. if ((sscanf(datetime,
  4004. "%d/%3s/%d %d:%d:%d",
  4005. &day,
  4006. month_str,
  4007. &year,
  4008. &hour,
  4009. &minute,
  4010. &second) == 6) || (sscanf(datetime,
  4011. "%d %3s %d %d:%d:%d",
  4012. &day,
  4013. month_str,
  4014. &year,
  4015. &hour,
  4016. &minute,
  4017. &second) == 6)
  4018. || (sscanf(datetime,
  4019. "%*3s, %d %3s %d %d:%d:%d",
  4020. &day,
  4021. month_str,
  4022. &year,
  4023. &hour,
  4024. &minute,
  4025. &second) == 6) || (sscanf(datetime,
  4026. "%d-%3s-%d %d:%d:%d",
  4027. &day,
  4028. month_str,
  4029. &year,
  4030. &hour,
  4031. &minute,
  4032. &second) == 6)) {
  4033. month = get_month_index(month_str);
  4034. if ((month >= 0) && (year > 1970)) {
  4035. leap_days = num_leap_years(year) - num_leap_years(1970);
  4036. year -= 1970;
  4037. days =
  4038. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  4039. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600
  4040. + minute * 60 + second;
  4041. }
  4042. }
  4043. return result;
  4044. }
  4045. /* Protect against directory disclosure attack by removing '..',
  4046. * excessive '/' and '\' characters */
  4047. static void
  4048. remove_double_dots_and_double_slashes(char *s)
  4049. {
  4050. char *p = s;
  4051. while (*s != '\0') {
  4052. *p++ = *s++;
  4053. if (s[-1] == '/' || s[-1] == '\\') {
  4054. /* Skip all following slashes, backslashes and double-dots */
  4055. while (s[0] != '\0') {
  4056. if (s[0] == '/' || s[0] == '\\') {
  4057. s++;
  4058. } else if (s[0] == '.' && s[1] == '.') {
  4059. s += 2;
  4060. } else {
  4061. break;
  4062. }
  4063. }
  4064. }
  4065. }
  4066. *p = '\0';
  4067. }
  4068. static const struct {
  4069. const char *extension;
  4070. size_t ext_len;
  4071. const char *mime_type;
  4072. } builtin_mime_types[] = {
  4073. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4074. * application types */
  4075. {".doc", 4, "application/msword"},
  4076. {".eps", 4, "application/postscript"},
  4077. {".exe", 4, "application/octet-stream"},
  4078. {".js", 3, "application/javascript"},
  4079. {".json", 5, "application/json"},
  4080. {".pdf", 4, "application/pdf"},
  4081. {".ps", 3, "application/postscript"},
  4082. {".rtf", 4, "application/rtf"},
  4083. {".xhtml", 6, "application/xhtml+xml"},
  4084. {".xsl", 4, "application/xml"},
  4085. {".xslt", 5, "application/xml"},
  4086. /* audio */
  4087. {".mp3", 4, "audio/mpeg"},
  4088. {".oga", 4, "audio/ogg"},
  4089. {".ogg", 4, "audio/ogg"},
  4090. /* image */
  4091. {".gif", 4, "image/gif"},
  4092. {".ief", 4, "image/ief"},
  4093. {".jpeg", 5, "image/jpeg"},
  4094. {".jpg", 4, "image/jpeg"},
  4095. {".jpm", 4, "image/jpm"},
  4096. {".jpx", 4, "image/jpx"},
  4097. {".png", 4, "image/png"},
  4098. {".svg", 4, "image/svg+xml"},
  4099. {".tif", 4, "image/tiff"},
  4100. {".tiff", 5, "image/tiff"},
  4101. /* model */
  4102. {".wrl", 4, "model/vrml"},
  4103. /* text */
  4104. {".css", 4, "text/css"},
  4105. {".csv", 4, "text/csv"},
  4106. {".htm", 4, "text/html"},
  4107. {".html", 5, "text/html"},
  4108. {".sgm", 4, "text/sgml"},
  4109. {".shtm", 5, "text/html"},
  4110. {".shtml", 6, "text/html"},
  4111. {".txt", 4, "text/plain"},
  4112. {".xml", 4, "text/xml"},
  4113. /* video */
  4114. {".mov", 4, "video/quicktime"},
  4115. {".mp4", 4, "video/mp4"},
  4116. {".mpeg", 5, "video/mpeg"},
  4117. {".mpg", 4, "video/mpeg"},
  4118. {".ogv", 4, "video/ogg"},
  4119. {".qt", 3, "video/quicktime"},
  4120. /* not registered types
  4121. * (http://reference.sitepoint.com/html/mime-types-full,
  4122. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4123. {".arj", 4, "application/x-arj-compressed"},
  4124. {".gz", 3, "application/x-gunzip"},
  4125. {".rar", 4, "application/x-arj-compressed"},
  4126. {".swf", 4, "application/x-shockwave-flash"},
  4127. {".tar", 4, "application/x-tar"},
  4128. {".tgz", 4, "application/x-tar-gz"},
  4129. {".torrent", 8, "application/x-bittorrent"},
  4130. {".ppt", 4, "application/x-mspowerpoint"},
  4131. {".xls", 4, "application/x-msexcel"},
  4132. {".zip", 4, "application/x-zip-compressed"},
  4133. {".aac",
  4134. 4,
  4135. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4136. {".aif", 4, "audio/x-aif"},
  4137. {".m3u", 4, "audio/x-mpegurl"},
  4138. {".mid", 4, "audio/x-midi"},
  4139. {".ra", 3, "audio/x-pn-realaudio"},
  4140. {".ram", 4, "audio/x-pn-realaudio"},
  4141. {".wav", 4, "audio/x-wav"},
  4142. {".bmp", 4, "image/bmp"},
  4143. {".ico", 4, "image/x-icon"},
  4144. {".pct", 4, "image/x-pct"},
  4145. {".pict", 5, "image/pict"},
  4146. {".rgb", 4, "image/x-rgb"},
  4147. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4148. {".asf", 4, "video/x-ms-asf"},
  4149. {".avi", 4, "video/x-msvideo"},
  4150. {".m4v", 4, "video/x-m4v"},
  4151. {NULL, 0, NULL}};
  4152. const char *
  4153. mg_get_builtin_mime_type(const char *path)
  4154. {
  4155. const char *ext;
  4156. size_t i, path_len;
  4157. path_len = strlen(path);
  4158. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4159. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4160. if (path_len > builtin_mime_types[i].ext_len
  4161. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4162. return builtin_mime_types[i].mime_type;
  4163. }
  4164. }
  4165. return "text/plain";
  4166. }
  4167. /* Look at the "path" extension and figure what mime type it has.
  4168. * Store mime type in the vector. */
  4169. static void
  4170. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4171. {
  4172. struct vec ext_vec, mime_vec;
  4173. const char *list, *ext;
  4174. size_t path_len;
  4175. path_len = strlen(path);
  4176. if (ctx == NULL || vec == NULL) {
  4177. return;
  4178. }
  4179. /* Scan user-defined mime types first, in case user wants to
  4180. * override default mime types. */
  4181. list = ctx->config[EXTRA_MIME_TYPES];
  4182. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4183. /* ext now points to the path suffix */
  4184. ext = path + path_len - ext_vec.len;
  4185. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4186. *vec = mime_vec;
  4187. return;
  4188. }
  4189. }
  4190. vec->ptr = mg_get_builtin_mime_type(path);
  4191. vec->len = strlen(vec->ptr);
  4192. }
  4193. /* Stringify binary data. Output buffer must be twice as big as input,
  4194. * because each byte takes 2 bytes in string representation */
  4195. static void
  4196. bin2str(char *to, const unsigned char *p, size_t len)
  4197. {
  4198. static const char *hex = "0123456789abcdef";
  4199. for (; len--; p++) {
  4200. *to++ = hex[p[0] >> 4];
  4201. *to++ = hex[p[0] & 0x0f];
  4202. }
  4203. *to = '\0';
  4204. }
  4205. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4206. char *
  4207. mg_md5(char buf[33], ...)
  4208. {
  4209. md5_byte_t hash[16];
  4210. const char *p;
  4211. va_list ap;
  4212. md5_state_t ctx;
  4213. md5_init(&ctx);
  4214. va_start(ap, buf);
  4215. while ((p = va_arg(ap, const char *)) != NULL) {
  4216. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4217. }
  4218. va_end(ap);
  4219. md5_finish(&ctx, hash);
  4220. bin2str(buf, hash, sizeof(hash));
  4221. return buf;
  4222. }
  4223. /* Check the user's password, return 1 if OK */
  4224. static int
  4225. check_password(const char *method,
  4226. const char *ha1,
  4227. const char *uri,
  4228. const char *nonce,
  4229. const char *nc,
  4230. const char *cnonce,
  4231. const char *qop,
  4232. const char *response)
  4233. {
  4234. char ha2[32 + 1], expected_response[32 + 1];
  4235. /* Some of the parameters may be NULL */
  4236. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4237. || qop == NULL
  4238. || response == NULL) {
  4239. return 0;
  4240. }
  4241. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4242. if (strlen(response) != 32) {
  4243. return 0;
  4244. }
  4245. mg_md5(ha2, method, ":", uri, NULL);
  4246. mg_md5(expected_response,
  4247. ha1,
  4248. ":",
  4249. nonce,
  4250. ":",
  4251. nc,
  4252. ":",
  4253. cnonce,
  4254. ":",
  4255. qop,
  4256. ":",
  4257. ha2,
  4258. NULL);
  4259. return mg_strcasecmp(response, expected_response) == 0;
  4260. }
  4261. /* Use the global passwords file, if specified by auth_gpass option,
  4262. * or search for .htpasswd in the requested directory. */
  4263. static void
  4264. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4265. {
  4266. if (conn != NULL && conn->ctx != NULL) {
  4267. char name[PATH_MAX];
  4268. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4269. struct file file = STRUCT_FILE_INITIALIZER;
  4270. int truncated;
  4271. if (gpass != NULL) {
  4272. /* Use global passwords file */
  4273. if (!mg_fopen(conn, gpass, "r", filep)) {
  4274. #ifdef DEBUG
  4275. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4276. #endif
  4277. }
  4278. /* Important: using local struct file to test path for is_directory
  4279. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4280. * was opened. */
  4281. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4282. mg_snprintf(conn,
  4283. &truncated,
  4284. name,
  4285. sizeof(name),
  4286. "%s/%s",
  4287. path,
  4288. PASSWORDS_FILE_NAME);
  4289. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4290. #ifdef DEBUG
  4291. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4292. #endif
  4293. }
  4294. } else {
  4295. /* Try to find .htpasswd in requested directory. */
  4296. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4297. if (e[0] == '/') {
  4298. break;
  4299. }
  4300. }
  4301. mg_snprintf(conn,
  4302. &truncated,
  4303. name,
  4304. sizeof(name),
  4305. "%.*s%s",
  4306. (int)(e - p),
  4307. p,
  4308. PASSWORDS_FILE_NAME);
  4309. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4310. #ifdef DEBUG
  4311. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4312. #endif
  4313. }
  4314. }
  4315. }
  4316. }
  4317. /* Parsed Authorization header */
  4318. struct ah {
  4319. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4320. };
  4321. /* Return 1 on success. Always initializes the ah structure. */
  4322. static int
  4323. parse_auth_header(struct mg_connection *conn,
  4324. char *buf,
  4325. size_t buf_size,
  4326. struct ah *ah)
  4327. {
  4328. char *name, *value, *s;
  4329. const char *auth_header;
  4330. uint64_t nonce;
  4331. if (!ah || !conn) {
  4332. return 0;
  4333. }
  4334. (void)memset(ah, 0, sizeof(*ah));
  4335. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4336. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4337. return 0;
  4338. }
  4339. /* Make modifiable copy of the auth header */
  4340. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4341. s = buf;
  4342. /* Parse authorization header */
  4343. for (;;) {
  4344. /* Gobble initial spaces */
  4345. while (isspace(*(unsigned char *)s)) {
  4346. s++;
  4347. }
  4348. name = skip_quoted(&s, "=", " ", 0);
  4349. /* Value is either quote-delimited, or ends at first comma or space. */
  4350. if (s[0] == '\"') {
  4351. s++;
  4352. value = skip_quoted(&s, "\"", " ", '\\');
  4353. if (s[0] == ',') {
  4354. s++;
  4355. }
  4356. } else {
  4357. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4358. * spaces */
  4359. }
  4360. if (*name == '\0') {
  4361. break;
  4362. }
  4363. if (!strcmp(name, "username")) {
  4364. ah->user = value;
  4365. } else if (!strcmp(name, "cnonce")) {
  4366. ah->cnonce = value;
  4367. } else if (!strcmp(name, "response")) {
  4368. ah->response = value;
  4369. } else if (!strcmp(name, "uri")) {
  4370. ah->uri = value;
  4371. } else if (!strcmp(name, "qop")) {
  4372. ah->qop = value;
  4373. } else if (!strcmp(name, "nc")) {
  4374. ah->nc = value;
  4375. } else if (!strcmp(name, "nonce")) {
  4376. ah->nonce = value;
  4377. }
  4378. }
  4379. #ifndef NO_NONCE_CHECK
  4380. /* Read the nonce from the response. */
  4381. if (ah->nonce == NULL) {
  4382. return 0;
  4383. }
  4384. s = NULL;
  4385. nonce = strtoull(ah->nonce, &s, 10);
  4386. if ((s == NULL) || (*s != 0)) {
  4387. return 0;
  4388. }
  4389. /* Convert the nonce from the client to a number. */
  4390. nonce ^= conn->ctx->auth_nonce_mask;
  4391. /* The converted number corresponds to the time the nounce has been
  4392. * created. This should not be earlier than the server start. */
  4393. /* Server side nonce check is valuable in all situations but one:
  4394. * if the server restarts frequently, but the client should not see
  4395. * that, so the server should accept nonces from previous starts. */
  4396. /* However, the reasonable default is to not accept a nonce from a
  4397. * previous start, so if anyone changed the access rights between
  4398. * two restarts, a new login is required. */
  4399. if (nonce < (uint64_t)conn->ctx->start_time) {
  4400. /* nonce is from a previous start of the server and no longer valid
  4401. * (replay attack?) */
  4402. return 0;
  4403. }
  4404. /* Check if the nonce is too high, so it has not (yet) been used by the
  4405. * server. */
  4406. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4407. return 0;
  4408. }
  4409. #endif
  4410. /* CGI needs it as REMOTE_USER */
  4411. if (ah->user != NULL) {
  4412. conn->request_info.remote_user = mg_strdup(ah->user);
  4413. } else {
  4414. return 0;
  4415. }
  4416. return 1;
  4417. }
  4418. static char *
  4419. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4420. {
  4421. char *eof;
  4422. size_t len;
  4423. char *memend;
  4424. if (!filep) {
  4425. return NULL;
  4426. }
  4427. if (filep->membuf != NULL && *p != NULL) {
  4428. memend = (char *)&filep->membuf[filep->size];
  4429. /* Search for \n from p till the end of stream */
  4430. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4431. if (eof != NULL) {
  4432. eof += 1; /* Include \n */
  4433. } else {
  4434. eof = memend; /* Copy remaining data */
  4435. }
  4436. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4437. memcpy(buf, *p, len);
  4438. buf[len] = '\0';
  4439. *p += len;
  4440. return len ? eof : NULL;
  4441. } else if (filep->fp != NULL) {
  4442. return fgets(buf, (int)size, filep->fp);
  4443. } else {
  4444. return NULL;
  4445. }
  4446. }
  4447. struct read_auth_file_struct {
  4448. struct mg_connection *conn;
  4449. struct ah ah;
  4450. char *domain;
  4451. char buf[256 + 256 + 40];
  4452. char *f_user;
  4453. char *f_domain;
  4454. char *f_ha1;
  4455. };
  4456. static int
  4457. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4458. {
  4459. char *p;
  4460. int is_authorized = 0;
  4461. struct file fp;
  4462. size_t l;
  4463. if (!filep || !workdata) {
  4464. return 0;
  4465. }
  4466. /* Loop over passwords file */
  4467. p = (char *)filep->membuf;
  4468. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4469. l = strlen(workdata->buf);
  4470. while (l > 0) {
  4471. if (isspace(workdata->buf[l - 1])
  4472. || iscntrl(workdata->buf[l - 1])) {
  4473. l--;
  4474. workdata->buf[l] = 0;
  4475. } else
  4476. break;
  4477. }
  4478. if (l < 1) {
  4479. continue;
  4480. }
  4481. workdata->f_user = workdata->buf;
  4482. if (workdata->f_user[0] == ':') {
  4483. /* user names may not contain a ':' and may not be empty,
  4484. * so lines starting with ':' may be used for a special purpose */
  4485. if (workdata->f_user[1] == '#') {
  4486. /* :# is a comment */
  4487. continue;
  4488. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4489. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4490. is_authorized = read_auth_file(&fp, workdata);
  4491. mg_fclose(&fp);
  4492. } else {
  4493. mg_cry(workdata->conn,
  4494. "%s: cannot open authorization file: %s",
  4495. __func__,
  4496. workdata->buf);
  4497. }
  4498. continue;
  4499. }
  4500. /* everything is invalid for the moment (might change in the
  4501. * future) */
  4502. mg_cry(workdata->conn,
  4503. "%s: syntax error in authorization file: %s",
  4504. __func__,
  4505. workdata->buf);
  4506. continue;
  4507. }
  4508. workdata->f_domain = strchr(workdata->f_user, ':');
  4509. if (workdata->f_domain == NULL) {
  4510. mg_cry(workdata->conn,
  4511. "%s: syntax error in authorization file: %s",
  4512. __func__,
  4513. workdata->buf);
  4514. continue;
  4515. }
  4516. *(workdata->f_domain) = 0;
  4517. (workdata->f_domain)++;
  4518. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4519. if (workdata->f_ha1 == NULL) {
  4520. mg_cry(workdata->conn,
  4521. "%s: syntax error in authorization file: %s",
  4522. __func__,
  4523. workdata->buf);
  4524. continue;
  4525. }
  4526. *(workdata->f_ha1) = 0;
  4527. (workdata->f_ha1)++;
  4528. if (!strcmp(workdata->ah.user, workdata->f_user)
  4529. && !strcmp(workdata->domain, workdata->f_domain)) {
  4530. return check_password(workdata->conn->request_info.request_method,
  4531. workdata->f_ha1,
  4532. workdata->ah.uri,
  4533. workdata->ah.nonce,
  4534. workdata->ah.nc,
  4535. workdata->ah.cnonce,
  4536. workdata->ah.qop,
  4537. workdata->ah.response);
  4538. }
  4539. }
  4540. return is_authorized;
  4541. }
  4542. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4543. static int
  4544. authorize(struct mg_connection *conn, struct file *filep)
  4545. {
  4546. struct read_auth_file_struct workdata;
  4547. char buf[MG_BUF_LEN];
  4548. if (!conn || !conn->ctx) {
  4549. return 0;
  4550. }
  4551. memset(&workdata, 0, sizeof(workdata));
  4552. workdata.conn = conn;
  4553. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4554. return 0;
  4555. }
  4556. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4557. return read_auth_file(filep, &workdata);
  4558. }
  4559. /* Return 1 if request is authorised, 0 otherwise. */
  4560. static int
  4561. check_authorization(struct mg_connection *conn, const char *path)
  4562. {
  4563. char fname[PATH_MAX];
  4564. struct vec uri_vec, filename_vec;
  4565. const char *list;
  4566. struct file file = STRUCT_FILE_INITIALIZER;
  4567. int authorized = 1, truncated;
  4568. if (!conn || !conn->ctx) {
  4569. return 0;
  4570. }
  4571. list = conn->ctx->config[PROTECT_URI];
  4572. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4573. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4574. mg_snprintf(conn,
  4575. &truncated,
  4576. fname,
  4577. sizeof(fname),
  4578. "%.*s",
  4579. (int)filename_vec.len,
  4580. filename_vec.ptr);
  4581. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4582. mg_cry(conn,
  4583. "%s: cannot open %s: %s",
  4584. __func__,
  4585. fname,
  4586. strerror(errno));
  4587. }
  4588. break;
  4589. }
  4590. }
  4591. if (!is_file_opened(&file)) {
  4592. open_auth_file(conn, path, &file);
  4593. }
  4594. if (is_file_opened(&file)) {
  4595. authorized = authorize(conn, &file);
  4596. mg_fclose(&file);
  4597. }
  4598. return authorized;
  4599. }
  4600. static void
  4601. send_authorization_request(struct mg_connection *conn)
  4602. {
  4603. char date[64];
  4604. time_t curtime = time(NULL);
  4605. if (conn && conn->ctx) {
  4606. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4607. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4608. nonce += conn->ctx->nonce_count;
  4609. ++conn->ctx->nonce_count;
  4610. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4611. nonce ^= conn->ctx->auth_nonce_mask;
  4612. conn->status_code = 401;
  4613. conn->must_close = 1;
  4614. gmt_time_string(date, sizeof(date), &curtime);
  4615. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4616. send_no_cache_header(conn);
  4617. mg_printf(conn,
  4618. "Date: %s\r\n"
  4619. "Connection: %s\r\n"
  4620. "Content-Length: 0\r\n"
  4621. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4622. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4623. date,
  4624. suggest_connection_header(conn),
  4625. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4626. nonce);
  4627. }
  4628. }
  4629. #if !defined(NO_FILES)
  4630. static int
  4631. is_authorized_for_put(struct mg_connection *conn)
  4632. {
  4633. if (conn) {
  4634. struct file file = STRUCT_FILE_INITIALIZER;
  4635. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4636. int ret = 0;
  4637. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4638. ret = authorize(conn, &file);
  4639. mg_fclose(&file);
  4640. }
  4641. return ret;
  4642. }
  4643. return 0;
  4644. }
  4645. #endif
  4646. int
  4647. mg_modify_passwords_file(const char *fname,
  4648. const char *domain,
  4649. const char *user,
  4650. const char *pass)
  4651. {
  4652. int found, i;
  4653. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4654. FILE *fp, *fp2;
  4655. found = 0;
  4656. fp = fp2 = NULL;
  4657. /* Regard empty password as no password - remove user record. */
  4658. if (pass != NULL && pass[0] == '\0') {
  4659. pass = NULL;
  4660. }
  4661. /* Other arguments must not be empty */
  4662. if (fname == NULL || domain == NULL || user == NULL) {
  4663. return 0;
  4664. }
  4665. /* Using the given file format, user name and domain must not contain ':'
  4666. */
  4667. if (strchr(user, ':') != NULL) {
  4668. return 0;
  4669. }
  4670. if (strchr(domain, ':') != NULL) {
  4671. return 0;
  4672. }
  4673. /* Do not allow control characters like newline in user name and domain.
  4674. * Do not allow excessively long names either. */
  4675. for (i = 0; i < 255 && user[i] != 0; i++) {
  4676. if (iscntrl(user[i])) {
  4677. return 0;
  4678. }
  4679. }
  4680. if (user[i]) {
  4681. return 0;
  4682. }
  4683. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4684. if (iscntrl(domain[i])) {
  4685. return 0;
  4686. }
  4687. }
  4688. if (domain[i]) {
  4689. return 0;
  4690. }
  4691. /* The maximum length of the path to the password file is limited */
  4692. if ((strlen(fname) + 4) >= PATH_MAX) {
  4693. return 0;
  4694. }
  4695. /* Create a temporary file name. Length has been checked before. */
  4696. strcpy(tmp, fname);
  4697. strcat(tmp, ".tmp");
  4698. /* Create the file if does not exist */
  4699. if ((fp = fopen(fname, "a+")) != NULL) {
  4700. (void)fclose(fp);
  4701. }
  4702. /* Open the given file and temporary file */
  4703. if ((fp = fopen(fname, "r")) == NULL) {
  4704. return 0;
  4705. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4706. fclose(fp);
  4707. return 0;
  4708. }
  4709. /* Copy the stuff to temporary file */
  4710. while (fgets(line, sizeof(line), fp) != NULL) {
  4711. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4712. continue;
  4713. }
  4714. u[255] = 0;
  4715. d[255] = 0;
  4716. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4717. found++;
  4718. if (pass != NULL) {
  4719. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4720. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4721. }
  4722. } else {
  4723. fprintf(fp2, "%s", line);
  4724. }
  4725. }
  4726. /* If new user, just add it */
  4727. if (!found && pass != NULL) {
  4728. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4729. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4730. }
  4731. /* Close files */
  4732. fclose(fp);
  4733. fclose(fp2);
  4734. /* Put the temp file in place of real file */
  4735. IGNORE_UNUSED_RESULT(remove(fname));
  4736. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4737. return 1;
  4738. }
  4739. static int
  4740. is_valid_port(unsigned long port)
  4741. {
  4742. return port < 0xffff;
  4743. }
  4744. static int
  4745. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4746. {
  4747. struct addrinfo hints, *res, *ressave;
  4748. int ret = 0;
  4749. memset(&hints, 0, sizeof(struct addrinfo));
  4750. hints.ai_family = af;
  4751. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4752. /* bad src string or bad address family */
  4753. return 0;
  4754. }
  4755. ressave = res;
  4756. while (res) {
  4757. if (dstlen >= res->ai_addrlen) {
  4758. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4759. ret = 1;
  4760. }
  4761. res = res->ai_next;
  4762. }
  4763. freeaddrinfo(ressave);
  4764. return ret;
  4765. }
  4766. static int
  4767. connect_socket(struct mg_context *ctx /* may be NULL */,
  4768. const char *host,
  4769. int port,
  4770. int use_ssl,
  4771. char *ebuf,
  4772. size_t ebuf_len,
  4773. SOCKET *sock /* output: socket, must not be NULL */,
  4774. union usa *sa /* output: socket address, must not be NULL */
  4775. )
  4776. {
  4777. int ip_ver = 0;
  4778. *sock = INVALID_SOCKET;
  4779. memset(sa, 0, sizeof(*sa));
  4780. if (ebuf_len > 0) {
  4781. *ebuf = 0;
  4782. }
  4783. if (host == NULL) {
  4784. mg_snprintf(NULL,
  4785. NULL, /* No truncation check for ebuf */
  4786. ebuf,
  4787. ebuf_len,
  4788. "%s",
  4789. "NULL host");
  4790. return 0;
  4791. }
  4792. if (port < 0 || !is_valid_port((unsigned)port)) {
  4793. mg_snprintf(NULL,
  4794. NULL, /* No truncation check for ebuf */
  4795. ebuf,
  4796. ebuf_len,
  4797. "%s",
  4798. "invalid port");
  4799. return 0;
  4800. }
  4801. if (use_ssl && (SSLv23_client_method == NULL)) {
  4802. mg_snprintf(NULL,
  4803. NULL, /* No truncation check for ebuf */
  4804. ebuf,
  4805. ebuf_len,
  4806. "%s",
  4807. "SSL is not initialized");
  4808. return 0;
  4809. }
  4810. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4811. sa->sin.sin_port = htons((uint16_t)port);
  4812. ip_ver = 4;
  4813. #ifdef USE_IPV6
  4814. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4815. sa->sin6.sin6_port = htons((uint16_t)port);
  4816. ip_ver = 6;
  4817. } else if (host[0] == '[') {
  4818. /* While getaddrinfo on Windows will work with [::1],
  4819. * getaddrinfo on Linux only works with ::1 (without []). */
  4820. size_t l = strlen(host + 1);
  4821. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4822. if (h) {
  4823. h[l - 1] = 0;
  4824. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4825. sa->sin6.sin6_port = htons((uint16_t)port);
  4826. ip_ver = 6;
  4827. }
  4828. mg_free(h);
  4829. }
  4830. #endif
  4831. }
  4832. if (ip_ver == 0) {
  4833. mg_snprintf(NULL,
  4834. NULL, /* No truncation check for ebuf */
  4835. ebuf,
  4836. ebuf_len,
  4837. "%s",
  4838. "host not found");
  4839. return 0;
  4840. }
  4841. if (ip_ver == 4) {
  4842. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4843. }
  4844. #ifdef USE_IPV6
  4845. else if (ip_ver == 6) {
  4846. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4847. }
  4848. #endif
  4849. if (*sock == INVALID_SOCKET) {
  4850. mg_snprintf(NULL,
  4851. NULL, /* No truncation check for ebuf */
  4852. ebuf,
  4853. ebuf_len,
  4854. "socket(): %s",
  4855. strerror(ERRNO));
  4856. return 0;
  4857. }
  4858. set_close_on_exec(*sock, fc(ctx));
  4859. if ((ip_ver == 4)
  4860. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4861. == 0)) {
  4862. /* connected with IPv4 */
  4863. return 1;
  4864. }
  4865. #ifdef USE_IPV6
  4866. if ((ip_ver == 6)
  4867. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4868. == 0)) {
  4869. /* connected with IPv6 */
  4870. return 1;
  4871. }
  4872. #endif
  4873. /* Not connected */
  4874. mg_snprintf(NULL,
  4875. NULL, /* No truncation check for ebuf */
  4876. ebuf,
  4877. ebuf_len,
  4878. "connect(%s:%d): %s",
  4879. host,
  4880. port,
  4881. strerror(ERRNO));
  4882. closesocket(*sock);
  4883. *sock = INVALID_SOCKET;
  4884. return 0;
  4885. }
  4886. int
  4887. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4888. {
  4889. static const char *dont_escape = "._-$,;~()";
  4890. static const char *hex = "0123456789abcdef";
  4891. char *pos = dst;
  4892. const char *end = dst + dst_len - 1;
  4893. for (; *src != '\0' && pos < end; src++, pos++) {
  4894. if (isalnum(*(const unsigned char *)src)
  4895. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4896. *pos = *src;
  4897. } else if (pos + 2 < end) {
  4898. pos[0] = '%';
  4899. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4900. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4901. pos += 2;
  4902. } else {
  4903. break;
  4904. }
  4905. }
  4906. *pos = '\0';
  4907. return (*src == '\0') ? (int)(pos - dst) : -1;
  4908. }
  4909. static void
  4910. print_dir_entry(struct de *de)
  4911. {
  4912. char size[64], mod[64], href[PATH_MAX];
  4913. struct tm *tm;
  4914. if (de->file.is_directory) {
  4915. mg_snprintf(de->conn,
  4916. NULL, /* Buffer is big enough */
  4917. size,
  4918. sizeof(size),
  4919. "%s",
  4920. "[DIRECTORY]");
  4921. } else {
  4922. /* We use (signed) cast below because MSVC 6 compiler cannot
  4923. * convert unsigned __int64 to double. Sigh. */
  4924. if (de->file.size < 1024) {
  4925. mg_snprintf(de->conn,
  4926. NULL, /* Buffer is big enough */
  4927. size,
  4928. sizeof(size),
  4929. "%d",
  4930. (int)de->file.size);
  4931. } else if (de->file.size < 0x100000) {
  4932. mg_snprintf(de->conn,
  4933. NULL, /* Buffer is big enough */
  4934. size,
  4935. sizeof(size),
  4936. "%.1fk",
  4937. (double)de->file.size / 1024.0);
  4938. } else if (de->file.size < 0x40000000) {
  4939. mg_snprintf(de->conn,
  4940. NULL, /* Buffer is big enough */
  4941. size,
  4942. sizeof(size),
  4943. "%.1fM",
  4944. (double)de->file.size / 1048576);
  4945. } else {
  4946. mg_snprintf(de->conn,
  4947. NULL, /* Buffer is big enough */
  4948. size,
  4949. sizeof(size),
  4950. "%.1fG",
  4951. (double)de->file.size / 1073741824);
  4952. }
  4953. }
  4954. /* Note: mg_snprintf will not cause a buffer overflow above.
  4955. * So, string truncation checks are not required here. */
  4956. tm = localtime(&de->file.last_modified);
  4957. if (tm != NULL) {
  4958. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4959. } else {
  4960. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4961. mod[sizeof(mod) - 1] = '\0';
  4962. }
  4963. mg_url_encode(de->file_name, href, sizeof(href));
  4964. de->conn->num_bytes_sent +=
  4965. mg_printf(de->conn,
  4966. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4967. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4968. de->conn->request_info.local_uri,
  4969. href,
  4970. de->file.is_directory ? "/" : "",
  4971. de->file_name,
  4972. de->file.is_directory ? "/" : "",
  4973. mod,
  4974. size);
  4975. }
  4976. /* This function is called from send_directory() and used for
  4977. * sorting directory entries by size, or name, or modification time.
  4978. * On windows, __cdecl specification is needed in case if project is built
  4979. * with __stdcall convention. qsort always requires __cdels callback. */
  4980. static int WINCDECL
  4981. compare_dir_entries(const void *p1, const void *p2)
  4982. {
  4983. if (p1 && p2) {
  4984. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4985. const char *query_string = a->conn->request_info.query_string;
  4986. int cmp_result = 0;
  4987. if (query_string == NULL) {
  4988. query_string = "na";
  4989. }
  4990. if (a->file.is_directory && !b->file.is_directory) {
  4991. return -1; /* Always put directories on top */
  4992. } else if (!a->file.is_directory && b->file.is_directory) {
  4993. return 1; /* Always put directories on top */
  4994. } else if (*query_string == 'n') {
  4995. cmp_result = strcmp(a->file_name, b->file_name);
  4996. } else if (*query_string == 's') {
  4997. cmp_result = a->file.size == b->file.size
  4998. ? 0
  4999. : a->file.size > b->file.size ? 1 : -1;
  5000. } else if (*query_string == 'd') {
  5001. cmp_result =
  5002. (a->file.last_modified == b->file.last_modified)
  5003. ? 0
  5004. : ((a->file.last_modified > b->file.last_modified) ? 1
  5005. : -1);
  5006. }
  5007. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5008. }
  5009. return 0;
  5010. }
  5011. static int
  5012. must_hide_file(struct mg_connection *conn, const char *path)
  5013. {
  5014. if (conn && conn->ctx) {
  5015. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5016. const char *pattern = conn->ctx->config[HIDE_FILES];
  5017. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5018. || (pattern != NULL
  5019. && match_prefix(pattern, strlen(pattern), path) > 0);
  5020. }
  5021. return 0;
  5022. }
  5023. static int
  5024. scan_directory(struct mg_connection *conn,
  5025. const char *dir,
  5026. void *data,
  5027. void (*cb)(struct de *, void *))
  5028. {
  5029. char path[PATH_MAX];
  5030. struct dirent *dp;
  5031. DIR *dirp;
  5032. struct de de;
  5033. int truncated;
  5034. if ((dirp = opendir(dir)) == NULL) {
  5035. return 0;
  5036. } else {
  5037. de.conn = conn;
  5038. while ((dp = readdir(dirp)) != NULL) {
  5039. /* Do not show current dir and hidden files */
  5040. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5041. || must_hide_file(conn, dp->d_name)) {
  5042. continue;
  5043. }
  5044. mg_snprintf(
  5045. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5046. /* If we don't memset stat structure to zero, mtime will have
  5047. * garbage and strftime() will segfault later on in
  5048. * print_dir_entry(). memset is required only if mg_stat()
  5049. * fails. For more details, see
  5050. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5051. memset(&de.file, 0, sizeof(de.file));
  5052. if (truncated) {
  5053. /* If the path is not complete, skip processing. */
  5054. continue;
  5055. }
  5056. if (!mg_stat(conn, path, &de.file)) {
  5057. mg_cry(conn,
  5058. "%s: mg_stat(%s) failed: %s",
  5059. __func__,
  5060. path,
  5061. strerror(ERRNO));
  5062. }
  5063. de.file_name = dp->d_name;
  5064. cb(&de, data);
  5065. }
  5066. (void)closedir(dirp);
  5067. }
  5068. return 1;
  5069. }
  5070. #if !defined(NO_FILES)
  5071. static int
  5072. remove_directory(struct mg_connection *conn, const char *dir)
  5073. {
  5074. char path[PATH_MAX];
  5075. struct dirent *dp;
  5076. DIR *dirp;
  5077. struct de de;
  5078. int truncated;
  5079. int ok = 1;
  5080. if ((dirp = opendir(dir)) == NULL) {
  5081. return 0;
  5082. } else {
  5083. de.conn = conn;
  5084. while ((dp = readdir(dirp)) != NULL) {
  5085. /* Do not show current dir (but show hidden files as they will
  5086. * also be removed) */
  5087. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5088. continue;
  5089. }
  5090. mg_snprintf(
  5091. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5092. /* If we don't memset stat structure to zero, mtime will have
  5093. * garbage and strftime() will segfault later on in
  5094. * print_dir_entry(). memset is required only if mg_stat()
  5095. * fails. For more details, see
  5096. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5097. memset(&de.file, 0, sizeof(de.file));
  5098. if (truncated) {
  5099. /* Do not delete anything shorter */
  5100. ok = 0;
  5101. continue;
  5102. }
  5103. if (!mg_stat(conn, path, &de.file)) {
  5104. mg_cry(conn,
  5105. "%s: mg_stat(%s) failed: %s",
  5106. __func__,
  5107. path,
  5108. strerror(ERRNO));
  5109. ok = 0;
  5110. }
  5111. if (de.file.membuf == NULL) {
  5112. /* file is not in memory */
  5113. if (de.file.is_directory) {
  5114. if (remove_directory(conn, path) == 0) {
  5115. ok = 0;
  5116. }
  5117. } else {
  5118. if (mg_remove(path) == 0) {
  5119. ok = 0;
  5120. }
  5121. }
  5122. } else {
  5123. /* file is in memory. It can not be deleted. */
  5124. ok = 0;
  5125. }
  5126. }
  5127. (void)closedir(dirp);
  5128. IGNORE_UNUSED_RESULT(rmdir(dir));
  5129. }
  5130. return ok;
  5131. }
  5132. #endif
  5133. struct dir_scan_data {
  5134. struct de *entries;
  5135. unsigned int num_entries;
  5136. unsigned int arr_size;
  5137. };
  5138. /* Behaves like realloc(), but frees original pointer on failure */
  5139. static void *
  5140. realloc2(void *ptr, size_t size)
  5141. {
  5142. void *new_ptr = mg_realloc(ptr, size);
  5143. if (new_ptr == NULL) {
  5144. mg_free(ptr);
  5145. }
  5146. return new_ptr;
  5147. }
  5148. static void
  5149. dir_scan_callback(struct de *de, void *data)
  5150. {
  5151. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5152. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5153. dsd->arr_size *= 2;
  5154. dsd->entries =
  5155. (struct de *)realloc2(dsd->entries,
  5156. dsd->arr_size * sizeof(dsd->entries[0]));
  5157. }
  5158. if (dsd->entries == NULL) {
  5159. /* TODO(lsm, low): propagate an error to the caller */
  5160. dsd->num_entries = 0;
  5161. } else {
  5162. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5163. dsd->entries[dsd->num_entries].file = de->file;
  5164. dsd->entries[dsd->num_entries].conn = de->conn;
  5165. dsd->num_entries++;
  5166. }
  5167. }
  5168. static void
  5169. handle_directory_request(struct mg_connection *conn, const char *dir)
  5170. {
  5171. unsigned int i;
  5172. int sort_direction;
  5173. struct dir_scan_data data = {NULL, 0, 128};
  5174. char date[64];
  5175. time_t curtime = time(NULL);
  5176. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5177. send_http_error(conn,
  5178. 500,
  5179. "Error: Cannot open directory\nopendir(%s): %s",
  5180. dir,
  5181. strerror(ERRNO));
  5182. return;
  5183. }
  5184. gmt_time_string(date, sizeof(date), &curtime);
  5185. if (!conn) {
  5186. return;
  5187. }
  5188. sort_direction = conn->request_info.query_string != NULL
  5189. && conn->request_info.query_string[1] == 'd'
  5190. ? 'a'
  5191. : 'd';
  5192. conn->must_close = 1;
  5193. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5194. send_static_cache_header(conn);
  5195. mg_printf(conn,
  5196. "Date: %s\r\n"
  5197. "Connection: close\r\n"
  5198. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5199. date);
  5200. conn->num_bytes_sent +=
  5201. mg_printf(conn,
  5202. "<html><head><title>Index of %s</title>"
  5203. "<style>th {text-align: left;}</style></head>"
  5204. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5205. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5206. "<th><a href=\"?d%c\">Modified</a></th>"
  5207. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5208. "<tr><td colspan=\"3\"><hr></td></tr>",
  5209. conn->request_info.local_uri,
  5210. conn->request_info.local_uri,
  5211. sort_direction,
  5212. sort_direction,
  5213. sort_direction);
  5214. /* Print first entry - link to a parent directory */
  5215. conn->num_bytes_sent +=
  5216. mg_printf(conn,
  5217. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5218. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5219. conn->request_info.local_uri,
  5220. "..",
  5221. "Parent directory",
  5222. "-",
  5223. "-");
  5224. /* Sort and print directory entries */
  5225. if (data.entries != NULL) {
  5226. qsort(data.entries,
  5227. (size_t)data.num_entries,
  5228. sizeof(data.entries[0]),
  5229. compare_dir_entries);
  5230. for (i = 0; i < data.num_entries; i++) {
  5231. print_dir_entry(&data.entries[i]);
  5232. mg_free(data.entries[i].file_name);
  5233. }
  5234. mg_free(data.entries);
  5235. }
  5236. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5237. conn->status_code = 200;
  5238. }
  5239. /* Send len bytes from the opened file to the client. */
  5240. static void
  5241. send_file_data(struct mg_connection *conn,
  5242. struct file *filep,
  5243. int64_t offset,
  5244. int64_t len)
  5245. {
  5246. char buf[MG_BUF_LEN];
  5247. int to_read, num_read, num_written;
  5248. int64_t size;
  5249. if (!filep || !conn) {
  5250. return;
  5251. }
  5252. /* Sanity check the offset */
  5253. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5254. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5255. if (len > 0 && filep->membuf != NULL && size > 0) {
  5256. /* file stored in memory */
  5257. if (len > size - offset) {
  5258. len = size - offset;
  5259. }
  5260. mg_write(conn, filep->membuf + offset, (size_t)len);
  5261. } else if (len > 0 && filep->fp != NULL) {
  5262. /* file stored on disk */
  5263. #if defined(__linux__)
  5264. /* sendfile is only available for Linux */
  5265. if (conn->throttle == 0 && conn->ssl == 0) {
  5266. off_t sf_offs = (off_t)offset;
  5267. ssize_t sf_sent;
  5268. int sf_file = fileno(filep->fp);
  5269. int loop_cnt = 0;
  5270. do {
  5271. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5272. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5273. size_t sf_tosend =
  5274. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5275. sf_sent =
  5276. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5277. if (sf_sent > 0) {
  5278. conn->num_bytes_sent += sf_sent;
  5279. len -= sf_sent;
  5280. offset += sf_sent;
  5281. } else if (loop_cnt == 0) {
  5282. /* This file can not be sent using sendfile.
  5283. * This might be the case for pseudo-files in the
  5284. * /sys/ and /proc/ file system.
  5285. * Use the regular user mode copy code instead. */
  5286. break;
  5287. } else if (sf_sent == 0) {
  5288. /* No error, but 0 bytes sent. May be EOF? */
  5289. return;
  5290. }
  5291. loop_cnt++;
  5292. } while ((len > 0) && (sf_sent >= 0));
  5293. if (sf_sent > 0) {
  5294. return; /* OK */
  5295. }
  5296. /* sf_sent<0 means error, thus fall back to the classic way */
  5297. /* This is always the case, if sf_file is not a "normal" file,
  5298. * e.g., for sending data from the output of a CGI process. */
  5299. offset = (int64_t)sf_offs;
  5300. }
  5301. #endif
  5302. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5303. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5304. send_http_error(
  5305. conn,
  5306. 500,
  5307. "%s",
  5308. "Error: Unable to access file at requested position.");
  5309. } else {
  5310. while (len > 0) {
  5311. /* Calculate how much to read from the file in the buffer */
  5312. to_read = sizeof(buf);
  5313. if ((int64_t)to_read > len) {
  5314. to_read = (int)len;
  5315. }
  5316. /* Read from file, exit the loop on error */
  5317. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5318. <= 0) {
  5319. break;
  5320. }
  5321. /* Send read bytes to the client, exit the loop on error */
  5322. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5323. != num_read) {
  5324. break;
  5325. }
  5326. /* Both read and were successful, adjust counters */
  5327. conn->num_bytes_sent += num_written;
  5328. len -= num_written;
  5329. }
  5330. }
  5331. }
  5332. }
  5333. static int
  5334. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5335. {
  5336. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5337. }
  5338. static void
  5339. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5340. {
  5341. if (filep != NULL && buf != NULL) {
  5342. mg_snprintf(NULL,
  5343. NULL, /* All calls to construct_etag use 64 byte buffer */
  5344. buf,
  5345. buf_len,
  5346. "\"%lx.%" INT64_FMT "\"",
  5347. (unsigned long)filep->last_modified,
  5348. filep->size);
  5349. }
  5350. }
  5351. static void
  5352. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5353. {
  5354. if (filep != NULL && filep->fp != NULL) {
  5355. #ifdef _WIN32
  5356. (void)conn; /* Unused. */
  5357. #else
  5358. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5359. mg_cry(conn,
  5360. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5361. __func__,
  5362. strerror(ERRNO));
  5363. }
  5364. #endif
  5365. }
  5366. }
  5367. static void
  5368. handle_static_file_request(struct mg_connection *conn,
  5369. const char *path,
  5370. struct file *filep)
  5371. {
  5372. char date[64], lm[64], etag[64];
  5373. char range[128]; /* large enough, so there will be no overflow */
  5374. const char *msg = "OK", *hdr;
  5375. time_t curtime = time(NULL);
  5376. int64_t cl, r1, r2;
  5377. struct vec mime_vec;
  5378. int n, truncated;
  5379. char gz_path[PATH_MAX];
  5380. const char *encoding = "";
  5381. const char *cors1, *cors2, *cors3;
  5382. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5383. return;
  5384. }
  5385. get_mime_type(conn->ctx, path, &mime_vec);
  5386. if (filep->size > INT64_MAX) {
  5387. send_http_error(conn,
  5388. 500,
  5389. "Error: File size is too large to send\n%" INT64_FMT,
  5390. filep->size);
  5391. }
  5392. cl = (int64_t)filep->size;
  5393. conn->status_code = 200;
  5394. range[0] = '\0';
  5395. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5396. * it's important to rewrite the filename after resolving
  5397. * the mime type from it, to preserve the actual file's type */
  5398. if (filep->gzipped) {
  5399. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5400. if (truncated) {
  5401. send_http_error(conn,
  5402. 500,
  5403. "Error: Path of zipped file too long (%s)",
  5404. path);
  5405. return;
  5406. }
  5407. path = gz_path;
  5408. encoding = "Content-Encoding: gzip\r\n";
  5409. }
  5410. if (!mg_fopen(conn, path, "rb", filep)) {
  5411. send_http_error(conn,
  5412. 500,
  5413. "Error: Cannot open file\nfopen(%s): %s",
  5414. path,
  5415. strerror(ERRNO));
  5416. return;
  5417. }
  5418. fclose_on_exec(filep, conn);
  5419. /* If Range: header specified, act accordingly */
  5420. r1 = r2 = 0;
  5421. hdr = mg_get_header(conn, "Range");
  5422. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5423. && r2 >= 0) {
  5424. /* actually, range requests don't play well with a pre-gzipped
  5425. * file (since the range is specified in the uncompressed space) */
  5426. if (filep->gzipped) {
  5427. send_http_error(
  5428. conn,
  5429. 501,
  5430. "%s",
  5431. "Error: Range requests in gzipped files are not supported");
  5432. mg_fclose(filep);
  5433. return;
  5434. }
  5435. conn->status_code = 206;
  5436. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5437. mg_snprintf(conn,
  5438. NULL, /* range buffer is big enough */
  5439. range,
  5440. sizeof(range),
  5441. "Content-Range: bytes "
  5442. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5443. r1,
  5444. r1 + cl - 1,
  5445. filep->size);
  5446. msg = "Partial Content";
  5447. }
  5448. hdr = mg_get_header(conn, "Origin");
  5449. if (hdr) {
  5450. /* Cross-origin resource sharing (CORS), see
  5451. * http://www.html5rocks.com/en/tutorials/cors/,
  5452. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5453. * preflight is not supported for files. */
  5454. cors1 = "Access-Control-Allow-Origin: ";
  5455. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5456. cors3 = "\r\n";
  5457. } else {
  5458. cors1 = cors2 = cors3 = "";
  5459. }
  5460. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5461. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5462. gmt_time_string(date, sizeof(date), &curtime);
  5463. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5464. construct_etag(etag, sizeof(etag), filep);
  5465. (void)mg_printf(conn,
  5466. "HTTP/1.1 %d %s\r\n"
  5467. "%s%s%s"
  5468. "Date: %s\r\n",
  5469. conn->status_code,
  5470. msg,
  5471. cors1,
  5472. cors2,
  5473. cors3,
  5474. date);
  5475. send_static_cache_header(conn);
  5476. (void)mg_printf(conn,
  5477. "Last-Modified: %s\r\n"
  5478. "Etag: %s\r\n"
  5479. "Content-Type: %.*s\r\n"
  5480. "Content-Length: %" INT64_FMT "\r\n"
  5481. "Connection: %s\r\n"
  5482. "Accept-Ranges: bytes\r\n"
  5483. "%s%s\r\n",
  5484. lm,
  5485. etag,
  5486. (int)mime_vec.len,
  5487. mime_vec.ptr,
  5488. cl,
  5489. suggest_connection_header(conn),
  5490. range,
  5491. encoding);
  5492. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5493. send_file_data(conn, filep, r1, cl);
  5494. }
  5495. mg_fclose(filep);
  5496. }
  5497. void
  5498. mg_send_file(struct mg_connection *conn, const char *path)
  5499. {
  5500. struct file file = STRUCT_FILE_INITIALIZER;
  5501. if (mg_stat(conn, path, &file)) {
  5502. if (file.is_directory) {
  5503. if (!conn) {
  5504. return;
  5505. }
  5506. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5507. "yes")) {
  5508. handle_directory_request(conn, path);
  5509. } else {
  5510. send_http_error(conn,
  5511. 403,
  5512. "%s",
  5513. "Error: Directory listing denied");
  5514. }
  5515. } else {
  5516. handle_static_file_request(conn, path, &file);
  5517. }
  5518. } else {
  5519. send_http_error(conn, 404, "%s", "Error: File not found");
  5520. }
  5521. }
  5522. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5523. * where parsing stopped. */
  5524. static void
  5525. parse_http_headers(char **buf, struct mg_request_info *ri)
  5526. {
  5527. int i;
  5528. if (!ri) {
  5529. return;
  5530. }
  5531. ri->num_headers = 0;
  5532. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5533. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5534. ri->http_headers[i].value = skip(buf, "\r\n");
  5535. if (ri->http_headers[i].name[0] == '\0') {
  5536. break;
  5537. }
  5538. ri->num_headers = i + 1;
  5539. }
  5540. }
  5541. static int
  5542. is_valid_http_method(const char *method)
  5543. {
  5544. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5545. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5546. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5547. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5548. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5549. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5550. /* TRACE method (RFC 2616) is not supported for security reasons */
  5551. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5552. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5553. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5554. /* Unsupported WEBDAV Methods: */
  5555. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5556. /* + 11 methods from RFC 3253 */
  5557. /* ORDERPATCH (RFC 3648) */
  5558. /* ACL (RFC 3744) */
  5559. /* SEARCH (RFC 5323) */
  5560. /* + MicroSoft extensions
  5561. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5562. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5563. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5564. }
  5565. /* Parse HTTP request, fill in mg_request_info structure.
  5566. * This function modifies the buffer by NUL-terminating
  5567. * HTTP request components, header names and header values. */
  5568. static int
  5569. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5570. {
  5571. int is_request, request_length;
  5572. if (!ri) {
  5573. return 0;
  5574. }
  5575. request_length = get_request_len(buf, len);
  5576. if (request_length > 0) {
  5577. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5578. * remote_port */
  5579. ri->remote_user = ri->request_method = ri->request_uri =
  5580. ri->http_version = NULL;
  5581. ri->num_headers = 0;
  5582. buf[request_length - 1] = '\0';
  5583. /* RFC says that all initial whitespaces should be ingored */
  5584. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5585. buf++;
  5586. }
  5587. ri->request_method = skip(&buf, " ");
  5588. ri->request_uri = skip(&buf, " ");
  5589. ri->http_version = skip(&buf, "\r\n");
  5590. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5591. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5592. is_request = is_valid_http_method(ri->request_method);
  5593. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5594. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5595. request_length = -1;
  5596. } else {
  5597. if (is_request) {
  5598. ri->http_version += 5;
  5599. }
  5600. parse_http_headers(&buf, ri);
  5601. }
  5602. }
  5603. return request_length;
  5604. }
  5605. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5606. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5607. * buffer (which marks the end of HTTP request). Buffer buf may already
  5608. * have some data. The length of the data is stored in nread.
  5609. * Upon every read operation, increase nread by the number of bytes read. */
  5610. static int
  5611. read_request(FILE *fp,
  5612. struct mg_connection *conn,
  5613. char *buf,
  5614. int bufsiz,
  5615. int *nread)
  5616. {
  5617. int request_len, n = 0;
  5618. struct timespec last_action_time;
  5619. double request_timeout;
  5620. if (!conn) {
  5621. return 0;
  5622. }
  5623. memset(&last_action_time, 0, sizeof(last_action_time));
  5624. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5625. /* value of request_timeout is in seconds, config in milliseconds */
  5626. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5627. } else {
  5628. request_timeout = -1.0;
  5629. }
  5630. request_len = get_request_len(buf, *nread);
  5631. while (
  5632. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5633. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5634. <= request_timeout) || (request_timeout < 0))
  5635. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5636. > 0)) {
  5637. *nread += n;
  5638. /* assert(*nread <= bufsiz); */
  5639. if (*nread > bufsiz) {
  5640. return -2;
  5641. }
  5642. request_len = get_request_len(buf, *nread);
  5643. if (request_timeout > 0.0) {
  5644. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5645. }
  5646. }
  5647. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5648. }
  5649. #if !defined(NO_FILES)
  5650. /* For given directory path, substitute it to valid index file.
  5651. * Return 1 if index file has been found, 0 if not found.
  5652. * If the file is found, it's stats is returned in stp. */
  5653. static int
  5654. substitute_index_file(struct mg_connection *conn,
  5655. char *path,
  5656. size_t path_len,
  5657. struct file *filep)
  5658. {
  5659. if (conn && conn->ctx) {
  5660. const char *list = conn->ctx->config[INDEX_FILES];
  5661. struct file file = STRUCT_FILE_INITIALIZER;
  5662. struct vec filename_vec;
  5663. size_t n = strlen(path);
  5664. int found = 0;
  5665. /* The 'path' given to us points to the directory. Remove all trailing
  5666. * directory separator characters from the end of the path, and
  5667. * then append single directory separator character. */
  5668. while (n > 0 && path[n - 1] == '/') {
  5669. n--;
  5670. }
  5671. path[n] = '/';
  5672. /* Traverse index files list. For each entry, append it to the given
  5673. * path and see if the file exists. If it exists, break the loop */
  5674. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5675. /* Ignore too long entries that may overflow path buffer */
  5676. if (filename_vec.len > path_len - (n + 2)) {
  5677. continue;
  5678. }
  5679. /* Prepare full path to the index file */
  5680. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5681. /* Does it exist? */
  5682. if (mg_stat(conn, path, &file)) {
  5683. /* Yes it does, break the loop */
  5684. *filep = file;
  5685. found = 1;
  5686. break;
  5687. }
  5688. }
  5689. /* If no index file exists, restore directory path */
  5690. if (!found) {
  5691. path[n] = '\0';
  5692. }
  5693. return found;
  5694. }
  5695. return 0;
  5696. }
  5697. #endif
  5698. /* Return True if we should reply 304 Not Modified. */
  5699. static int
  5700. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5701. {
  5702. char etag[64];
  5703. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5704. const char *inm = mg_get_header(conn, "If-None-Match");
  5705. construct_etag(etag, sizeof(etag), filep);
  5706. if (!filep) {
  5707. return 0;
  5708. }
  5709. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5710. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5711. }
  5712. #if !defined(NO_CGI) || !defined(NO_FILES)
  5713. static int
  5714. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5715. {
  5716. const char *expect, *body;
  5717. char buf[MG_BUF_LEN];
  5718. int to_read, nread, success = 0;
  5719. int64_t buffered_len;
  5720. double timeout = -1.0;
  5721. if (!conn) {
  5722. return 0;
  5723. }
  5724. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5725. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5726. }
  5727. expect = mg_get_header(conn, "Expect");
  5728. /* assert(fp != NULL); */
  5729. if (!fp) {
  5730. send_http_error(conn, 500, "%s", "Error: NULL File");
  5731. return 0;
  5732. }
  5733. if (conn->content_len == -1 && !conn->is_chunked) {
  5734. /* Content length is not specified by the client. */
  5735. send_http_error(conn,
  5736. 411,
  5737. "%s",
  5738. "Error: Client did not specify content length");
  5739. } else if ((expect != NULL)
  5740. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5741. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5742. send_http_error(conn,
  5743. 417,
  5744. "Error: Can not fulfill expectation %s",
  5745. expect);
  5746. } else {
  5747. if (expect != NULL) {
  5748. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5749. conn->status_code = 100;
  5750. } else {
  5751. conn->status_code = 200;
  5752. }
  5753. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5754. - conn->consumed_content;
  5755. /* assert(buffered_len >= 0); */
  5756. /* assert(conn->consumed_content == 0); */
  5757. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5758. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5759. return 0;
  5760. }
  5761. if (buffered_len > 0) {
  5762. if ((int64_t)buffered_len > conn->content_len) {
  5763. buffered_len = (int)conn->content_len;
  5764. }
  5765. body = conn->buf + conn->request_len + conn->consumed_content;
  5766. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5767. conn->consumed_content += buffered_len;
  5768. }
  5769. nread = 0;
  5770. while (conn->consumed_content < conn->content_len) {
  5771. to_read = sizeof(buf);
  5772. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5773. to_read = (int)(conn->content_len - conn->consumed_content);
  5774. }
  5775. nread = pull(NULL, conn, buf, to_read, timeout);
  5776. if (nread <= 0
  5777. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5778. break;
  5779. }
  5780. conn->consumed_content += nread;
  5781. }
  5782. if (conn->consumed_content == conn->content_len) {
  5783. success = nread >= 0;
  5784. }
  5785. /* Each error code path in this function must send an error */
  5786. if (!success) {
  5787. /* NOTE: Maybe some data has already been sent. */
  5788. /* TODO (low): If some data has been sent, a correct error
  5789. * reply can no longer be sent, so just close the connection */
  5790. send_http_error(conn, 500, "%s", "");
  5791. }
  5792. }
  5793. return success;
  5794. }
  5795. #endif
  5796. #if !defined(NO_CGI)
  5797. /* This structure helps to create an environment for the spawned CGI program.
  5798. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5799. * last element must be NULL.
  5800. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5801. * strings must reside in a contiguous buffer. The end of the buffer is
  5802. * marked by two '\0' characters.
  5803. * We satisfy both worlds: we create an envp array (which is vars), all
  5804. * entries are actually pointers inside buf. */
  5805. struct cgi_environment {
  5806. struct mg_connection *conn;
  5807. /* Data block */
  5808. char *buf; /* Environment buffer */
  5809. size_t buflen; /* Space available in buf */
  5810. size_t bufused; /* Space taken in buf */
  5811. /* Index block */
  5812. char **var; /* char **envp */
  5813. size_t varlen; /* Number of variables available in var */
  5814. size_t varused; /* Number of variables stored in var */
  5815. };
  5816. static void addenv(struct cgi_environment *env,
  5817. PRINTF_FORMAT_STRING(const char *fmt),
  5818. ...) PRINTF_ARGS(2, 3);
  5819. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5820. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  5821. static void
  5822. addenv(struct cgi_environment *env, const char *fmt, ...)
  5823. {
  5824. size_t n, space;
  5825. int truncated;
  5826. char *added;
  5827. va_list ap;
  5828. /* Calculate how much space is left in the buffer */
  5829. space = (env->buflen - env->bufused);
  5830. /* Calculate an estimate for the required space */
  5831. n = strlen(fmt) + 2 + 128;
  5832. do {
  5833. if (space <= n) {
  5834. /* Allocate new buffer */
  5835. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5836. added = (char *)mg_realloc(env->buf, n);
  5837. if (!added) {
  5838. /* Out of memory */
  5839. mg_cry(env->conn,
  5840. "%s: Cannot allocate memory for CGI variable [%s]",
  5841. __func__,
  5842. fmt);
  5843. return;
  5844. }
  5845. env->buf = added;
  5846. env->buflen = n;
  5847. space = (env->buflen - env->bufused);
  5848. }
  5849. /* Make a pointer to the free space int the buffer */
  5850. added = env->buf + env->bufused;
  5851. /* Copy VARIABLE=VALUE\0 string into the free space */
  5852. va_start(ap, fmt);
  5853. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5854. va_end(ap);
  5855. /* Do not add truncated strings to the environment */
  5856. if (truncated) {
  5857. /* Reallocate the buffer */
  5858. space = 0;
  5859. n = 1;
  5860. }
  5861. } while (truncated);
  5862. /* Calculate number of bytes added to the environment */
  5863. n = strlen(added) + 1;
  5864. env->bufused += n;
  5865. /* Now update the variable index */
  5866. space = (env->varlen - env->varused);
  5867. if (space < 2) {
  5868. mg_cry(env->conn,
  5869. "%s: Cannot register CGI variable [%s]",
  5870. __func__,
  5871. fmt);
  5872. return;
  5873. }
  5874. /* Append a pointer to the added string into the envp array */
  5875. env->var[env->varused] = added;
  5876. env->varused++;
  5877. }
  5878. static void
  5879. prepare_cgi_environment(struct mg_connection *conn,
  5880. const char *prog,
  5881. struct cgi_environment *env)
  5882. {
  5883. const char *s;
  5884. struct vec var_vec;
  5885. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5886. int i, truncated;
  5887. if (conn == NULL || prog == NULL || env == NULL) {
  5888. return;
  5889. }
  5890. env->conn = conn;
  5891. env->buflen = CGI_ENVIRONMENT_SIZE;
  5892. env->bufused = 0;
  5893. env->buf = (char *)mg_malloc(env->buflen);
  5894. env->varlen = MAX_CGI_ENVIR_VARS;
  5895. env->varused = 0;
  5896. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5897. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5898. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5899. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5900. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5901. /* Prepare the environment block */
  5902. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5903. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5904. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5905. #if defined(USE_IPV6)
  5906. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5907. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5908. } else
  5909. #endif
  5910. {
  5911. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5912. }
  5913. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5914. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5915. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5916. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5917. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  5918. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  5919. /* SCRIPT_NAME */
  5920. addenv(env,
  5921. "SCRIPT_NAME=%.*s",
  5922. (int)strlen(conn->request_info.local_uri)
  5923. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5924. conn->request_info.local_uri);
  5925. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5926. if (conn->path_info == NULL) {
  5927. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5928. } else {
  5929. addenv(env,
  5930. "PATH_TRANSLATED=%s%s",
  5931. conn->ctx->config[DOCUMENT_ROOT],
  5932. conn->path_info);
  5933. }
  5934. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5935. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5936. addenv(env, "CONTENT_TYPE=%s", s);
  5937. }
  5938. if (conn->request_info.query_string != NULL) {
  5939. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5940. }
  5941. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5942. addenv(env, "CONTENT_LENGTH=%s", s);
  5943. }
  5944. if ((s = getenv("PATH")) != NULL) {
  5945. addenv(env, "PATH=%s", s);
  5946. }
  5947. if (conn->path_info != NULL) {
  5948. addenv(env, "PATH_INFO=%s", conn->path_info);
  5949. }
  5950. if (conn->status_code > 0) {
  5951. /* CGI error handler should show the status code */
  5952. addenv(env, "STATUS=%d", conn->status_code);
  5953. }
  5954. #if defined(_WIN32)
  5955. if ((s = getenv("COMSPEC")) != NULL) {
  5956. addenv(env, "COMSPEC=%s", s);
  5957. }
  5958. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5959. addenv(env, "SYSTEMROOT=%s", s);
  5960. }
  5961. if ((s = getenv("SystemDrive")) != NULL) {
  5962. addenv(env, "SystemDrive=%s", s);
  5963. }
  5964. if ((s = getenv("ProgramFiles")) != NULL) {
  5965. addenv(env, "ProgramFiles=%s", s);
  5966. }
  5967. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5968. addenv(env, "ProgramFiles(x86)=%s", s);
  5969. }
  5970. #else
  5971. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5972. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5973. }
  5974. #endif /* _WIN32 */
  5975. if ((s = getenv("PERLLIB")) != NULL) {
  5976. addenv(env, "PERLLIB=%s", s);
  5977. }
  5978. if (conn->request_info.remote_user != NULL) {
  5979. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5980. addenv(env, "%s", "AUTH_TYPE=Digest");
  5981. }
  5982. /* Add all headers as HTTP_* variables */
  5983. for (i = 0; i < conn->request_info.num_headers; i++) {
  5984. (void)mg_snprintf(conn,
  5985. &truncated,
  5986. http_var_name,
  5987. sizeof(http_var_name),
  5988. "HTTP_%s",
  5989. conn->request_info.http_headers[i].name);
  5990. if (truncated) {
  5991. mg_cry(conn,
  5992. "%s: HTTP header variable too long [%s]",
  5993. __func__,
  5994. conn->request_info.http_headers[i].name);
  5995. continue;
  5996. }
  5997. /* Convert variable name into uppercase, and change - to _ */
  5998. for (p = http_var_name; *p != '\0'; p++) {
  5999. if (*p == '-') {
  6000. *p = '_';
  6001. }
  6002. *p = (char)toupper(*(unsigned char *)p);
  6003. }
  6004. addenv(env,
  6005. "%s=%s",
  6006. http_var_name,
  6007. conn->request_info.http_headers[i].value);
  6008. }
  6009. /* Add user-specified variables */
  6010. s = conn->ctx->config[CGI_ENVIRONMENT];
  6011. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6012. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6013. }
  6014. env->var[env->varused] = NULL;
  6015. env->buf[env->bufused] = '\0';
  6016. }
  6017. static void
  6018. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6019. {
  6020. char *buf;
  6021. size_t buflen;
  6022. int headers_len, data_len, i, truncated;
  6023. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6024. const char *status, *status_text, *connection_state;
  6025. char *pbuf, dir[PATH_MAX], *p;
  6026. struct mg_request_info ri;
  6027. struct cgi_environment blk;
  6028. FILE *in = NULL, *out = NULL, *err = NULL;
  6029. struct file fout = STRUCT_FILE_INITIALIZER;
  6030. pid_t pid = (pid_t)-1;
  6031. if (conn == NULL) {
  6032. return;
  6033. }
  6034. buf = NULL;
  6035. buflen = 16384;
  6036. prepare_cgi_environment(conn, prog, &blk);
  6037. /* CGI must be executed in its own directory. 'dir' must point to the
  6038. * directory containing executable program, 'p' must point to the
  6039. * executable program name relative to 'dir'. */
  6040. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6041. if (truncated) {
  6042. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6043. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6044. goto done;
  6045. }
  6046. if ((p = strrchr(dir, '/')) != NULL) {
  6047. *p++ = '\0';
  6048. } else {
  6049. dir[0] = '.', dir[1] = '\0';
  6050. p = (char *)prog;
  6051. }
  6052. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6053. status = strerror(ERRNO);
  6054. mg_cry(conn,
  6055. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6056. prog,
  6057. status);
  6058. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6059. goto done;
  6060. }
  6061. pid = spawn_process(
  6062. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  6063. if (pid == (pid_t)-1) {
  6064. status = strerror(ERRNO);
  6065. mg_cry(conn,
  6066. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6067. prog,
  6068. status);
  6069. send_http_error(conn,
  6070. 500,
  6071. "Error: Cannot spawn CGI process [%s]: %s",
  6072. prog,
  6073. status);
  6074. goto done;
  6075. }
  6076. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6077. set_close_on_exec((SOCKET)fdin[0], conn);
  6078. set_close_on_exec((SOCKET)fdin[1], conn);
  6079. set_close_on_exec((SOCKET)fdout[0], conn);
  6080. set_close_on_exec((SOCKET)fdout[1], conn);
  6081. set_close_on_exec((SOCKET)fderr[0], conn);
  6082. set_close_on_exec((SOCKET)fderr[1], conn);
  6083. /* Parent closes only one side of the pipes.
  6084. * If we don't mark them as closed, close() attempt before
  6085. * return from this function throws an exception on Windows.
  6086. * Windows does not like when closed descriptor is closed again. */
  6087. (void)close(fdin[0]);
  6088. (void)close(fdout[1]);
  6089. (void)close(fderr[1]);
  6090. fdin[0] = fdout[1] = fderr[1] = -1;
  6091. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6092. status = strerror(ERRNO);
  6093. mg_cry(conn,
  6094. "Error: CGI program \"%s\": Can not open stdin: %s",
  6095. prog,
  6096. status);
  6097. send_http_error(conn,
  6098. 500,
  6099. "Error: CGI can not open fdin\nfopen: %s",
  6100. status);
  6101. goto done;
  6102. }
  6103. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6104. status = strerror(ERRNO);
  6105. mg_cry(conn,
  6106. "Error: CGI program \"%s\": Can not open stdout: %s",
  6107. prog,
  6108. status);
  6109. send_http_error(conn,
  6110. 500,
  6111. "Error: CGI can not open fdout\nfopen: %s",
  6112. status);
  6113. goto done;
  6114. }
  6115. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6116. status = strerror(ERRNO);
  6117. mg_cry(conn,
  6118. "Error: CGI program \"%s\": Can not open stderr: %s",
  6119. prog,
  6120. status);
  6121. send_http_error(conn,
  6122. 500,
  6123. "Error: CGI can not open fdout\nfopen: %s",
  6124. status);
  6125. goto done;
  6126. }
  6127. setbuf(in, NULL);
  6128. setbuf(out, NULL);
  6129. setbuf(err, NULL);
  6130. fout.fp = out;
  6131. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6132. /* This is a POST/PUT request, or another request with body data. */
  6133. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6134. /* Error sending the body data */
  6135. mg_cry(conn,
  6136. "Error: CGI program \"%s\": Forward body data failed",
  6137. prog);
  6138. goto done;
  6139. }
  6140. }
  6141. /* Close so child gets an EOF. */
  6142. fclose(in);
  6143. in = NULL;
  6144. fdin[1] = -1;
  6145. /* Now read CGI reply into a buffer. We need to set correct
  6146. * status code, thus we need to see all HTTP headers first.
  6147. * Do not send anything back to client, until we buffer in all
  6148. * HTTP headers. */
  6149. data_len = 0;
  6150. buf = (char *)mg_malloc(buflen);
  6151. if (buf == NULL) {
  6152. send_http_error(conn,
  6153. 500,
  6154. "Error: Not enough memory for CGI buffer (%u bytes)",
  6155. (unsigned int)buflen);
  6156. mg_cry(conn,
  6157. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6158. "bytes)",
  6159. prog,
  6160. (unsigned int)buflen);
  6161. goto done;
  6162. }
  6163. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6164. if (headers_len <= 0) {
  6165. /* Could not parse the CGI response. Check if some error message on
  6166. * stderr. */
  6167. i = pull_all(err, conn, buf, (int)buflen);
  6168. if (i > 0) {
  6169. mg_cry(conn,
  6170. "Error: CGI program \"%s\" sent error "
  6171. "message: [%.*s]",
  6172. prog,
  6173. i,
  6174. buf);
  6175. send_http_error(conn,
  6176. 500,
  6177. "Error: CGI program \"%s\" sent error "
  6178. "message: [%.*s]",
  6179. prog,
  6180. i,
  6181. buf);
  6182. } else {
  6183. mg_cry(conn,
  6184. "Error: CGI program sent malformed or too big "
  6185. "(>%u bytes) HTTP headers: [%.*s]",
  6186. (unsigned)buflen,
  6187. data_len,
  6188. buf);
  6189. send_http_error(conn,
  6190. 500,
  6191. "Error: CGI program sent malformed or too big "
  6192. "(>%u bytes) HTTP headers: [%.*s]",
  6193. (unsigned)buflen,
  6194. data_len,
  6195. buf);
  6196. }
  6197. goto done;
  6198. }
  6199. pbuf = buf;
  6200. buf[headers_len - 1] = '\0';
  6201. parse_http_headers(&pbuf, &ri);
  6202. /* Make up and send the status line */
  6203. status_text = "OK";
  6204. if ((status = get_header(&ri, "Status")) != NULL) {
  6205. conn->status_code = atoi(status);
  6206. status_text = status;
  6207. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6208. status_text++;
  6209. }
  6210. } else if (get_header(&ri, "Location") != NULL) {
  6211. conn->status_code = 302;
  6212. } else {
  6213. conn->status_code = 200;
  6214. }
  6215. connection_state = get_header(&ri, "Connection");
  6216. if (connection_state == NULL
  6217. || mg_strcasecmp(connection_state, "keep-alive")) {
  6218. conn->must_close = 1;
  6219. }
  6220. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6221. /* Send headers */
  6222. for (i = 0; i < ri.num_headers; i++) {
  6223. mg_printf(conn,
  6224. "%s: %s\r\n",
  6225. ri.http_headers[i].name,
  6226. ri.http_headers[i].value);
  6227. }
  6228. mg_write(conn, "\r\n", 2);
  6229. /* Send chunk of data that may have been read after the headers */
  6230. conn->num_bytes_sent +=
  6231. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6232. /* Read the rest of CGI output and send to the client */
  6233. send_file_data(conn, &fout, 0, INT64_MAX);
  6234. done:
  6235. mg_free(blk.var);
  6236. mg_free(blk.buf);
  6237. if (pid != (pid_t)-1) {
  6238. kill(pid, SIGKILL);
  6239. #if !defined(_WIN32)
  6240. {
  6241. int st;
  6242. while (waitpid(pid, &st, 0) != -1)
  6243. ; /* clean zombies */
  6244. }
  6245. #endif
  6246. }
  6247. if (fdin[0] != -1) {
  6248. close(fdin[0]);
  6249. }
  6250. if (fdout[1] != -1) {
  6251. close(fdout[1]);
  6252. }
  6253. if (in != NULL) {
  6254. fclose(in);
  6255. } else if (fdin[1] != -1) {
  6256. close(fdin[1]);
  6257. }
  6258. if (out != NULL) {
  6259. fclose(out);
  6260. } else if (fdout[0] != -1) {
  6261. close(fdout[0]);
  6262. }
  6263. if (err != NULL) {
  6264. fclose(err);
  6265. } else if (fderr[0] != -1) {
  6266. close(fderr[0]);
  6267. }
  6268. if (buf != NULL) {
  6269. mg_free(buf);
  6270. }
  6271. }
  6272. #endif /* !NO_CGI */
  6273. #if !defined(NO_FILES)
  6274. /* For a given PUT path, create all intermediate subdirectories.
  6275. * Return 0 if the path itself is a directory.
  6276. * Return 1 if the path leads to a file.
  6277. * Return -1 for if the path is too long.
  6278. * Return -2 if path can not be created.
  6279. */
  6280. static int
  6281. put_dir(struct mg_connection *conn, const char *path)
  6282. {
  6283. char buf[PATH_MAX];
  6284. const char *s, *p;
  6285. struct file file = STRUCT_FILE_INITIALIZER;
  6286. size_t len;
  6287. int res = 1;
  6288. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6289. len = (size_t)(p - path);
  6290. if (len >= sizeof(buf)) {
  6291. /* path too long */
  6292. res = -1;
  6293. break;
  6294. }
  6295. memcpy(buf, path, len);
  6296. buf[len] = '\0';
  6297. /* Try to create intermediate directory */
  6298. DEBUG_TRACE("mkdir(%s)", buf);
  6299. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  6300. /* path does not exixt and can not be created */
  6301. res = -2;
  6302. break;
  6303. }
  6304. /* Is path itself a directory? */
  6305. if (p[1] == '\0') {
  6306. res = 0;
  6307. }
  6308. }
  6309. return res;
  6310. }
  6311. static void
  6312. mkcol(struct mg_connection *conn, const char *path)
  6313. {
  6314. int rc, body_len;
  6315. struct de de;
  6316. char date[64];
  6317. time_t curtime = time(NULL);
  6318. if (conn == NULL) {
  6319. return;
  6320. }
  6321. /* TODO (mid): Check the send_http_error situations in this function */
  6322. memset(&de.file, 0, sizeof(de.file));
  6323. if (!mg_stat(conn, path, &de.file)) {
  6324. mg_cry(conn,
  6325. "%s: mg_stat(%s) failed: %s",
  6326. __func__,
  6327. path,
  6328. strerror(ERRNO));
  6329. }
  6330. if (de.file.last_modified) {
  6331. /* TODO (high): This check does not seem to make any sense ! */
  6332. send_http_error(
  6333. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6334. return;
  6335. }
  6336. body_len = conn->data_len - conn->request_len;
  6337. if (body_len > 0) {
  6338. send_http_error(
  6339. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6340. return;
  6341. }
  6342. rc = mg_mkdir(path, 0755);
  6343. if (rc == 0) {
  6344. conn->status_code = 201;
  6345. gmt_time_string(date, sizeof(date), &curtime);
  6346. mg_printf(conn,
  6347. "HTTP/1.1 %d Created\r\n"
  6348. "Date: %s\r\n",
  6349. conn->status_code,
  6350. date);
  6351. send_static_cache_header(conn);
  6352. mg_printf(conn,
  6353. "Content-Length: 0\r\n"
  6354. "Connection: %s\r\n\r\n",
  6355. suggest_connection_header(conn));
  6356. } else if (rc == -1) {
  6357. if (errno == EEXIST) {
  6358. send_http_error(
  6359. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6360. } else if (errno == EACCES) {
  6361. send_http_error(
  6362. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6363. } else if (errno == ENOENT) {
  6364. send_http_error(
  6365. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6366. } else {
  6367. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6368. }
  6369. }
  6370. }
  6371. static void
  6372. put_file(struct mg_connection *conn, const char *path)
  6373. {
  6374. struct file file = STRUCT_FILE_INITIALIZER;
  6375. const char *range;
  6376. int64_t r1, r2;
  6377. int rc;
  6378. char date[64];
  6379. time_t curtime = time(NULL);
  6380. if (conn == NULL) {
  6381. return;
  6382. }
  6383. if (mg_stat(conn, path, &file)) {
  6384. /* File already exists */
  6385. conn->status_code = 200;
  6386. if (file.is_directory) {
  6387. /* This is an already existing directory,
  6388. * so there is nothing to do for the server. */
  6389. rc = 0;
  6390. } else {
  6391. /* File exists and is not a directory. */
  6392. /* Can it be replaced? */
  6393. if (file.membuf != NULL) {
  6394. /* This is an "in-memory" file, that can not be replaced */
  6395. send_http_error(
  6396. conn,
  6397. 405,
  6398. "Error: Put not possible\nReplacing %s is not supported",
  6399. path);
  6400. return;
  6401. }
  6402. /* Check if the server may write this file */
  6403. if (access(path, W_OK) == 0) {
  6404. /* Access granted */
  6405. conn->status_code = 200;
  6406. rc = 1;
  6407. } else {
  6408. send_http_error(
  6409. conn,
  6410. 403,
  6411. "Error: Put not possible\nReplacing %s is not allowed",
  6412. path);
  6413. return;
  6414. }
  6415. }
  6416. } else {
  6417. /* File should be created */
  6418. conn->status_code = 201;
  6419. rc = put_dir(conn, path);
  6420. }
  6421. if (rc == 0) {
  6422. /* put_dir returns 0 if path is a directory */
  6423. gmt_time_string(date, sizeof(date), &curtime);
  6424. mg_printf(conn,
  6425. "HTTP/1.1 %d %s\r\n",
  6426. conn->status_code,
  6427. mg_get_response_code_text(conn->status_code, NULL));
  6428. send_no_cache_header(conn);
  6429. mg_printf(conn,
  6430. "Date: %s\r\n"
  6431. "Content-Length: 0\r\n"
  6432. "Connection: %s\r\n\r\n",
  6433. date,
  6434. suggest_connection_header(conn));
  6435. /* Request to create a directory has been fulfilled successfully.
  6436. * No need to put a file. */
  6437. return;
  6438. }
  6439. if (rc == -1) {
  6440. /* put_dir returns -1 if the path is too long */
  6441. send_http_error(conn,
  6442. 414,
  6443. "Error: Path too long\nput_dir(%s): %s",
  6444. path,
  6445. strerror(ERRNO));
  6446. return;
  6447. }
  6448. if (rc == -2) {
  6449. /* put_dir returns -2 if the directory can not be created */
  6450. send_http_error(conn,
  6451. 500,
  6452. "Error: Can not create directory\nput_dir(%s): %s",
  6453. path,
  6454. strerror(ERRNO));
  6455. return;
  6456. }
  6457. /* A file should be created or overwritten. */
  6458. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6459. mg_fclose(&file);
  6460. send_http_error(conn,
  6461. 500,
  6462. "Error: Can not create file\nfopen(%s): %s",
  6463. path,
  6464. strerror(ERRNO));
  6465. return;
  6466. }
  6467. fclose_on_exec(&file, conn);
  6468. range = mg_get_header(conn, "Content-Range");
  6469. r1 = r2 = 0;
  6470. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6471. conn->status_code = 206; /* Partial content */
  6472. fseeko(file.fp, r1, SEEK_SET);
  6473. }
  6474. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6475. /* forward_body_data failed.
  6476. * The error code has already been sent to the client,
  6477. * and conn->status_code is already set. */
  6478. return;
  6479. }
  6480. gmt_time_string(date, sizeof(date), &curtime);
  6481. mg_printf(conn,
  6482. "HTTP/1.1 %d %s\r\n",
  6483. conn->status_code,
  6484. mg_get_response_code_text(conn->status_code, NULL));
  6485. send_no_cache_header(conn);
  6486. mg_printf(conn,
  6487. "Date: %s\r\n"
  6488. "Content-Length: 0\r\n"
  6489. "Connection: %s\r\n\r\n",
  6490. date,
  6491. suggest_connection_header(conn));
  6492. mg_fclose(&file);
  6493. }
  6494. static void
  6495. delete_file(struct mg_connection *conn, const char *path)
  6496. {
  6497. struct de de;
  6498. memset(&de.file, 0, sizeof(de.file));
  6499. if (!mg_stat(conn, path, &de.file)) {
  6500. /* mg_stat returns 0 if the file does not exist */
  6501. send_http_error(conn,
  6502. 404,
  6503. "Error: Cannot delete file\nFile %s not found",
  6504. path);
  6505. return;
  6506. }
  6507. if (de.file.membuf != NULL) {
  6508. /* the file is cached in memory */
  6509. send_http_error(
  6510. conn,
  6511. 405,
  6512. "Error: Delete not possible\nDeleting %s is not supported",
  6513. path);
  6514. return;
  6515. }
  6516. if (de.file.is_directory) {
  6517. if (remove_directory(conn, path)) {
  6518. /* Delete is successful: Return 204 without content. */
  6519. send_http_error(conn, 204, "%s", "");
  6520. } else {
  6521. /* Delete is not successful: Return 500 (Server error). */
  6522. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6523. }
  6524. return;
  6525. }
  6526. /* This is an existing file (not a directory).
  6527. * Check if write permission is granted. */
  6528. if (access(path, W_OK) != 0) {
  6529. /* File is read only */
  6530. send_http_error(
  6531. conn,
  6532. 403,
  6533. "Error: Delete not possible\nDeleting %s is not allowed",
  6534. path);
  6535. return;
  6536. }
  6537. /* Try to delete it. */
  6538. if (mg_remove(path) == 0) {
  6539. /* Delete was successful: Return 204 without content. */
  6540. send_http_error(conn, 204, "%s", "");
  6541. } else {
  6542. /* Delete not successful (file locked). */
  6543. send_http_error(conn,
  6544. 423,
  6545. "Error: Cannot delete file\nremove(%s): %s",
  6546. path,
  6547. strerror(ERRNO));
  6548. }
  6549. }
  6550. #endif /* !NO_FILES */
  6551. static void
  6552. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6553. static void
  6554. do_ssi_include(struct mg_connection *conn,
  6555. const char *ssi,
  6556. char *tag,
  6557. int include_level)
  6558. {
  6559. char file_name[MG_BUF_LEN], path[512], *p;
  6560. struct file file = STRUCT_FILE_INITIALIZER;
  6561. size_t len;
  6562. int truncated = 0;
  6563. if (conn == NULL) {
  6564. return;
  6565. }
  6566. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6567. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6568. * always < MG_BUF_LEN. */
  6569. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6570. /* File name is relative to the webserver root */
  6571. file_name[511] = 0;
  6572. (void)mg_snprintf(conn,
  6573. &truncated,
  6574. path,
  6575. sizeof(path),
  6576. "%s/%s",
  6577. conn->ctx->config[DOCUMENT_ROOT],
  6578. file_name);
  6579. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6580. /* File name is relative to the webserver working directory
  6581. * or it is absolute system path */
  6582. file_name[511] = 0;
  6583. (void)
  6584. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6585. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6586. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6587. /* File name is relative to the currect document */
  6588. file_name[511] = 0;
  6589. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6590. if (!truncated) {
  6591. if ((p = strrchr(path, '/')) != NULL) {
  6592. p[1] = '\0';
  6593. }
  6594. len = strlen(path);
  6595. (void)mg_snprintf(conn,
  6596. &truncated,
  6597. path + len,
  6598. sizeof(path) - len,
  6599. "%s",
  6600. file_name);
  6601. }
  6602. } else {
  6603. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6604. return;
  6605. }
  6606. if (truncated) {
  6607. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6608. return;
  6609. }
  6610. if (!mg_fopen(conn, path, "rb", &file)) {
  6611. mg_cry(conn,
  6612. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6613. tag,
  6614. path,
  6615. strerror(ERRNO));
  6616. } else {
  6617. fclose_on_exec(&file, conn);
  6618. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6619. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6620. path) > 0) {
  6621. send_ssi_file(conn, path, &file, include_level + 1);
  6622. } else {
  6623. send_file_data(conn, &file, 0, INT64_MAX);
  6624. }
  6625. mg_fclose(&file);
  6626. }
  6627. }
  6628. #if !defined(NO_POPEN)
  6629. static void
  6630. do_ssi_exec(struct mg_connection *conn, char *tag)
  6631. {
  6632. char cmd[1024] = "";
  6633. struct file file = STRUCT_FILE_INITIALIZER;
  6634. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6635. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6636. } else {
  6637. cmd[1023] = 0;
  6638. if ((file.fp = popen(cmd, "r")) == NULL) {
  6639. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6640. } else {
  6641. send_file_data(conn, &file, 0, INT64_MAX);
  6642. pclose(file.fp);
  6643. }
  6644. }
  6645. }
  6646. #endif /* !NO_POPEN */
  6647. static int
  6648. mg_fgetc(struct file *filep, int offset)
  6649. {
  6650. if (filep == NULL) {
  6651. return EOF;
  6652. }
  6653. if (filep->membuf != NULL && offset >= 0
  6654. && ((unsigned int)(offset)) < filep->size) {
  6655. return ((unsigned char *)filep->membuf)[offset];
  6656. } else if (filep->fp != NULL) {
  6657. return fgetc(filep->fp);
  6658. } else {
  6659. return EOF;
  6660. }
  6661. }
  6662. static void
  6663. send_ssi_file(struct mg_connection *conn,
  6664. const char *path,
  6665. struct file *filep,
  6666. int include_level)
  6667. {
  6668. char buf[MG_BUF_LEN];
  6669. int ch, offset, len, in_ssi_tag;
  6670. if (include_level > 10) {
  6671. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6672. return;
  6673. }
  6674. in_ssi_tag = len = offset = 0;
  6675. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6676. if (in_ssi_tag && ch == '>') {
  6677. in_ssi_tag = 0;
  6678. buf[len++] = (char)ch;
  6679. buf[len] = '\0';
  6680. /* assert(len <= (int) sizeof(buf)); */
  6681. if (len > (int)sizeof(buf)) {
  6682. break;
  6683. }
  6684. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6685. /* Not an SSI tag, pass it */
  6686. (void)mg_write(conn, buf, (size_t)len);
  6687. } else {
  6688. if (!memcmp(buf + 5, "include", 7)) {
  6689. do_ssi_include(conn, path, buf + 12, include_level);
  6690. #if !defined(NO_POPEN)
  6691. } else if (!memcmp(buf + 5, "exec", 4)) {
  6692. do_ssi_exec(conn, buf + 9);
  6693. #endif /* !NO_POPEN */
  6694. } else {
  6695. mg_cry(conn,
  6696. "%s: unknown SSI "
  6697. "command: \"%s\"",
  6698. path,
  6699. buf);
  6700. }
  6701. }
  6702. len = 0;
  6703. } else if (in_ssi_tag) {
  6704. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6705. /* Not an SSI tag */
  6706. in_ssi_tag = 0;
  6707. } else if (len == (int)sizeof(buf) - 2) {
  6708. mg_cry(conn, "%s: SSI tag is too large", path);
  6709. len = 0;
  6710. }
  6711. buf[len++] = (char)(ch & 0xff);
  6712. } else if (ch == '<') {
  6713. in_ssi_tag = 1;
  6714. if (len > 0) {
  6715. mg_write(conn, buf, (size_t)len);
  6716. }
  6717. len = 0;
  6718. buf[len++] = (char)(ch & 0xff);
  6719. } else {
  6720. buf[len++] = (char)(ch & 0xff);
  6721. if (len == (int)sizeof(buf)) {
  6722. mg_write(conn, buf, (size_t)len);
  6723. len = 0;
  6724. }
  6725. }
  6726. }
  6727. /* Send the rest of buffered data */
  6728. if (len > 0) {
  6729. mg_write(conn, buf, (size_t)len);
  6730. }
  6731. }
  6732. static void
  6733. handle_ssi_file_request(struct mg_connection *conn,
  6734. const char *path,
  6735. struct file *filep)
  6736. {
  6737. char date[64];
  6738. time_t curtime = time(NULL);
  6739. const char *cors1, *cors2, *cors3;
  6740. if (conn == NULL || path == NULL || filep == NULL) {
  6741. return;
  6742. }
  6743. if (mg_get_header(conn, "Origin")) {
  6744. /* Cross-origin resource sharing (CORS). */
  6745. cors1 = "Access-Control-Allow-Origin: ";
  6746. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6747. cors3 = "\r\n";
  6748. } else {
  6749. cors1 = cors2 = cors3 = "";
  6750. }
  6751. if (!mg_fopen(conn, path, "rb", filep)) {
  6752. /* File exists (precondition for calling this function),
  6753. * but can not be opened by the server. */
  6754. send_http_error(conn,
  6755. 500,
  6756. "Error: Cannot read file\nfopen(%s): %s",
  6757. path,
  6758. strerror(ERRNO));
  6759. } else {
  6760. conn->must_close = 1;
  6761. gmt_time_string(date, sizeof(date), &curtime);
  6762. fclose_on_exec(filep, conn);
  6763. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6764. send_no_cache_header(conn);
  6765. mg_printf(conn,
  6766. "%s%s%s"
  6767. "Date: %s\r\n"
  6768. "Content-Type: text/html\r\n"
  6769. "Connection: %s\r\n\r\n",
  6770. cors1,
  6771. cors2,
  6772. cors3,
  6773. date,
  6774. suggest_connection_header(conn));
  6775. send_ssi_file(conn, path, filep, 0);
  6776. mg_fclose(filep);
  6777. }
  6778. }
  6779. #if !defined(NO_FILES)
  6780. static void
  6781. send_options(struct mg_connection *conn)
  6782. {
  6783. char date[64];
  6784. time_t curtime = time(NULL);
  6785. if (!conn) {
  6786. return;
  6787. }
  6788. conn->status_code = 200;
  6789. conn->must_close = 1;
  6790. gmt_time_string(date, sizeof(date), &curtime);
  6791. mg_printf(conn,
  6792. "HTTP/1.1 200 OK\r\n"
  6793. "Date: %s\r\n"
  6794. /* TODO: "Cache-Control" (?) */
  6795. "Connection: %s\r\n"
  6796. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6797. "PROPFIND, MKCOL\r\n"
  6798. "DAV: 1\r\n\r\n",
  6799. date,
  6800. suggest_connection_header(conn));
  6801. }
  6802. /* Writes PROPFIND properties for a collection element */
  6803. static void
  6804. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6805. {
  6806. char mtime[64];
  6807. if (conn == NULL || uri == NULL || filep == NULL) {
  6808. return;
  6809. }
  6810. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6811. conn->num_bytes_sent +=
  6812. mg_printf(conn,
  6813. "<d:response>"
  6814. "<d:href>%s</d:href>"
  6815. "<d:propstat>"
  6816. "<d:prop>"
  6817. "<d:resourcetype>%s</d:resourcetype>"
  6818. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6819. "<d:getlastmodified>%s</d:getlastmodified>"
  6820. "</d:prop>"
  6821. "<d:status>HTTP/1.1 200 OK</d:status>"
  6822. "</d:propstat>"
  6823. "</d:response>\n",
  6824. uri,
  6825. filep->is_directory ? "<d:collection/>" : "",
  6826. filep->size,
  6827. mtime);
  6828. }
  6829. static void
  6830. print_dav_dir_entry(struct de *de, void *data)
  6831. {
  6832. char href[PATH_MAX];
  6833. char href_encoded[PATH_MAX];
  6834. int truncated;
  6835. struct mg_connection *conn = (struct mg_connection *)data;
  6836. if (!de || !conn) {
  6837. return;
  6838. }
  6839. mg_snprintf(conn,
  6840. &truncated,
  6841. href,
  6842. sizeof(href),
  6843. "%s%s",
  6844. conn->request_info.local_uri,
  6845. de->file_name);
  6846. if (!truncated) {
  6847. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6848. print_props(conn, href_encoded, &de->file);
  6849. }
  6850. }
  6851. static void
  6852. handle_propfind(struct mg_connection *conn,
  6853. const char *path,
  6854. struct file *filep)
  6855. {
  6856. const char *depth = mg_get_header(conn, "Depth");
  6857. char date[64];
  6858. time_t curtime = time(NULL);
  6859. gmt_time_string(date, sizeof(date), &curtime);
  6860. if (!conn || !path || !filep) {
  6861. return;
  6862. }
  6863. conn->must_close = 1;
  6864. conn->status_code = 207;
  6865. mg_printf(conn,
  6866. "HTTP/1.1 207 Multi-Status\r\n"
  6867. "Date: %s\r\n",
  6868. date);
  6869. send_static_cache_header(conn);
  6870. mg_printf(conn,
  6871. "Connection: %s\r\n"
  6872. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6873. suggest_connection_header(conn));
  6874. conn->num_bytes_sent +=
  6875. mg_printf(conn,
  6876. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6877. "<d:multistatus xmlns:d='DAV:'>\n");
  6878. /* Print properties for the requested resource itself */
  6879. print_props(conn, conn->request_info.local_uri, filep);
  6880. /* If it is a directory, print directory entries too if Depth is not 0 */
  6881. if (filep && conn->ctx && filep->is_directory
  6882. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  6883. && (depth == NULL || strcmp(depth, "0") != 0)) {
  6884. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6885. }
  6886. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6887. }
  6888. #endif
  6889. void
  6890. mg_lock_connection(struct mg_connection *conn)
  6891. {
  6892. if (conn) {
  6893. (void)pthread_mutex_lock(&conn->mutex);
  6894. }
  6895. }
  6896. void
  6897. mg_unlock_connection(struct mg_connection *conn)
  6898. {
  6899. if (conn) {
  6900. (void)pthread_mutex_unlock(&conn->mutex);
  6901. }
  6902. }
  6903. void
  6904. mg_lock_context(struct mg_context *ctx)
  6905. {
  6906. if (ctx) {
  6907. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6908. }
  6909. }
  6910. void
  6911. mg_unlock_context(struct mg_context *ctx)
  6912. {
  6913. if (ctx) {
  6914. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6915. }
  6916. }
  6917. #if defined(USE_TIMERS)
  6918. #include "timer.inl"
  6919. #endif /* USE_TIMERS */
  6920. #ifdef USE_LUA
  6921. #include "mod_lua.inl"
  6922. #endif /* USE_LUA */
  6923. #ifdef USE_DUKTAPE
  6924. #include "mod_duktape.inl"
  6925. #endif /* USE_DUKTAPE */
  6926. #if defined(USE_WEBSOCKET)
  6927. /* START OF SHA-1 code
  6928. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6929. #define SHA1HANDSOFF
  6930. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6931. *
  6932. * #if defined(__sun)
  6933. * #include "solarisfixes.h"
  6934. * #endif
  6935. */
  6936. static int
  6937. is_big_endian(void)
  6938. {
  6939. static const int n = 1;
  6940. return ((char *)&n)[0] == 0;
  6941. }
  6942. union char64long16 {
  6943. unsigned char c[64];
  6944. uint32_t l[16];
  6945. };
  6946. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6947. static uint32_t
  6948. blk0(union char64long16 *block, int i)
  6949. {
  6950. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6951. if (!is_big_endian()) {
  6952. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  6953. | (rol(block->l[i], 8) & 0x00FF00FF);
  6954. }
  6955. return block->l[i];
  6956. }
  6957. #define blk(i) \
  6958. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  6959. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6960. 1))
  6961. #define R0(v, w, x, y, z, i) \
  6962. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6963. w = rol(w, 30);
  6964. #define R1(v, w, x, y, z, i) \
  6965. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6966. w = rol(w, 30);
  6967. #define R2(v, w, x, y, z, i) \
  6968. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6969. w = rol(w, 30);
  6970. #define R3(v, w, x, y, z, i) \
  6971. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6972. w = rol(w, 30);
  6973. #define R4(v, w, x, y, z, i) \
  6974. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6975. w = rol(w, 30);
  6976. typedef struct {
  6977. uint32_t state[5];
  6978. uint32_t count[2];
  6979. unsigned char buffer[64];
  6980. } SHA1_CTX;
  6981. static void
  6982. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6983. {
  6984. uint32_t a, b, c, d, e;
  6985. union char64long16 block[1];
  6986. memcpy(block, buffer, 64);
  6987. a = state[0];
  6988. b = state[1];
  6989. c = state[2];
  6990. d = state[3];
  6991. e = state[4];
  6992. R0(a, b, c, d, e, 0);
  6993. R0(e, a, b, c, d, 1);
  6994. R0(d, e, a, b, c, 2);
  6995. R0(c, d, e, a, b, 3);
  6996. R0(b, c, d, e, a, 4);
  6997. R0(a, b, c, d, e, 5);
  6998. R0(e, a, b, c, d, 6);
  6999. R0(d, e, a, b, c, 7);
  7000. R0(c, d, e, a, b, 8);
  7001. R0(b, c, d, e, a, 9);
  7002. R0(a, b, c, d, e, 10);
  7003. R0(e, a, b, c, d, 11);
  7004. R0(d, e, a, b, c, 12);
  7005. R0(c, d, e, a, b, 13);
  7006. R0(b, c, d, e, a, 14);
  7007. R0(a, b, c, d, e, 15);
  7008. R1(e, a, b, c, d, 16);
  7009. R1(d, e, a, b, c, 17);
  7010. R1(c, d, e, a, b, 18);
  7011. R1(b, c, d, e, a, 19);
  7012. R2(a, b, c, d, e, 20);
  7013. R2(e, a, b, c, d, 21);
  7014. R2(d, e, a, b, c, 22);
  7015. R2(c, d, e, a, b, 23);
  7016. R2(b, c, d, e, a, 24);
  7017. R2(a, b, c, d, e, 25);
  7018. R2(e, a, b, c, d, 26);
  7019. R2(d, e, a, b, c, 27);
  7020. R2(c, d, e, a, b, 28);
  7021. R2(b, c, d, e, a, 29);
  7022. R2(a, b, c, d, e, 30);
  7023. R2(e, a, b, c, d, 31);
  7024. R2(d, e, a, b, c, 32);
  7025. R2(c, d, e, a, b, 33);
  7026. R2(b, c, d, e, a, 34);
  7027. R2(a, b, c, d, e, 35);
  7028. R2(e, a, b, c, d, 36);
  7029. R2(d, e, a, b, c, 37);
  7030. R2(c, d, e, a, b, 38);
  7031. R2(b, c, d, e, a, 39);
  7032. R3(a, b, c, d, e, 40);
  7033. R3(e, a, b, c, d, 41);
  7034. R3(d, e, a, b, c, 42);
  7035. R3(c, d, e, a, b, 43);
  7036. R3(b, c, d, e, a, 44);
  7037. R3(a, b, c, d, e, 45);
  7038. R3(e, a, b, c, d, 46);
  7039. R3(d, e, a, b, c, 47);
  7040. R3(c, d, e, a, b, 48);
  7041. R3(b, c, d, e, a, 49);
  7042. R3(a, b, c, d, e, 50);
  7043. R3(e, a, b, c, d, 51);
  7044. R3(d, e, a, b, c, 52);
  7045. R3(c, d, e, a, b, 53);
  7046. R3(b, c, d, e, a, 54);
  7047. R3(a, b, c, d, e, 55);
  7048. R3(e, a, b, c, d, 56);
  7049. R3(d, e, a, b, c, 57);
  7050. R3(c, d, e, a, b, 58);
  7051. R3(b, c, d, e, a, 59);
  7052. R4(a, b, c, d, e, 60);
  7053. R4(e, a, b, c, d, 61);
  7054. R4(d, e, a, b, c, 62);
  7055. R4(c, d, e, a, b, 63);
  7056. R4(b, c, d, e, a, 64);
  7057. R4(a, b, c, d, e, 65);
  7058. R4(e, a, b, c, d, 66);
  7059. R4(d, e, a, b, c, 67);
  7060. R4(c, d, e, a, b, 68);
  7061. R4(b, c, d, e, a, 69);
  7062. R4(a, b, c, d, e, 70);
  7063. R4(e, a, b, c, d, 71);
  7064. R4(d, e, a, b, c, 72);
  7065. R4(c, d, e, a, b, 73);
  7066. R4(b, c, d, e, a, 74);
  7067. R4(a, b, c, d, e, 75);
  7068. R4(e, a, b, c, d, 76);
  7069. R4(d, e, a, b, c, 77);
  7070. R4(c, d, e, a, b, 78);
  7071. R4(b, c, d, e, a, 79);
  7072. state[0] += a;
  7073. state[1] += b;
  7074. state[2] += c;
  7075. state[3] += d;
  7076. state[4] += e;
  7077. a = b = c = d = e = 0;
  7078. memset(block, '\0', sizeof(block));
  7079. }
  7080. static void
  7081. SHA1Init(SHA1_CTX *context)
  7082. {
  7083. context->state[0] = 0x67452301;
  7084. context->state[1] = 0xEFCDAB89;
  7085. context->state[2] = 0x98BADCFE;
  7086. context->state[3] = 0x10325476;
  7087. context->state[4] = 0xC3D2E1F0;
  7088. context->count[0] = context->count[1] = 0;
  7089. }
  7090. static void
  7091. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7092. {
  7093. uint32_t i, j;
  7094. j = context->count[0];
  7095. if ((context->count[0] += len << 3) < j) {
  7096. context->count[1]++;
  7097. }
  7098. context->count[1] += (len >> 29);
  7099. j = (j >> 3) & 63;
  7100. if ((j + len) > 63) {
  7101. memcpy(&context->buffer[j], data, (i = 64 - j));
  7102. SHA1Transform(context->state, context->buffer);
  7103. for (; i + 63 < len; i += 64) {
  7104. SHA1Transform(context->state, &data[i]);
  7105. }
  7106. j = 0;
  7107. } else
  7108. i = 0;
  7109. memcpy(&context->buffer[j], &data[i], len - i);
  7110. }
  7111. static void
  7112. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7113. {
  7114. unsigned i;
  7115. unsigned char finalcount[8], c;
  7116. for (i = 0; i < 8; i++) {
  7117. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7118. >> ((3 - (i & 3)) * 8)) & 255);
  7119. }
  7120. c = 0200;
  7121. SHA1Update(context, &c, 1);
  7122. while ((context->count[0] & 504) != 448) {
  7123. c = 0000;
  7124. SHA1Update(context, &c, 1);
  7125. }
  7126. SHA1Update(context, finalcount, 8);
  7127. for (i = 0; i < 20; i++) {
  7128. digest[i] = (unsigned char)((context->state[i >> 2]
  7129. >> ((3 - (i & 3)) * 8)) & 255);
  7130. }
  7131. memset(context, '\0', sizeof(*context));
  7132. memset(&finalcount, '\0', sizeof(finalcount));
  7133. }
  7134. /* END OF SHA1 CODE */
  7135. static int
  7136. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7137. {
  7138. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7139. const char *protocol = NULL;
  7140. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7141. SHA1_CTX sha_ctx;
  7142. int truncated;
  7143. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7144. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7145. if (truncated) {
  7146. conn->must_close = 1;
  7147. return 0;
  7148. }
  7149. SHA1Init(&sha_ctx);
  7150. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7151. SHA1Final((unsigned char *)sha, &sha_ctx);
  7152. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7153. mg_printf(conn,
  7154. "HTTP/1.1 101 Switching Protocols\r\n"
  7155. "Upgrade: websocket\r\n"
  7156. "Connection: Upgrade\r\n"
  7157. "Sec-WebSocket-Accept: %s\r\n",
  7158. b64_sha);
  7159. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7160. if (protocol) {
  7161. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7162. } else {
  7163. mg_printf(conn, "%s", "\r\n");
  7164. }
  7165. return 1;
  7166. }
  7167. static void
  7168. read_websocket(struct mg_connection *conn,
  7169. mg_websocket_data_handler ws_data_handler,
  7170. void *callback_data)
  7171. {
  7172. /* Pointer to the beginning of the portion of the incoming websocket
  7173. * message queue.
  7174. * The original websocket upgrade request is never removed, so the queue
  7175. * begins after it. */
  7176. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7177. int n, error, exit_by_callback;
  7178. /* body_len is the length of the entire queue in bytes
  7179. * len is the length of the current message
  7180. * data_len is the length of the current message's data payload
  7181. * header_len is the length of the current message's header */
  7182. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7183. /* "The masking key is a 32-bit value chosen at random by the client."
  7184. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7185. */
  7186. unsigned char mask[4];
  7187. /* data points to the place where the message is stored when passed to the
  7188. * websocket_data callback. This is either mem on the stack, or a
  7189. * dynamically allocated buffer if it is too large. */
  7190. char mem[4096];
  7191. char *data = mem;
  7192. unsigned char mop; /* mask flag and opcode */
  7193. double timeout = -1.0;
  7194. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7195. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7196. }
  7197. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7198. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7199. }
  7200. mg_set_thread_name("wsock");
  7201. /* Loop continuously, reading messages from the socket, invoking the
  7202. * callback, and waiting repeatedly until an error occurs. */
  7203. while (!conn->ctx->stop_flag) {
  7204. header_len = 0;
  7205. assert(conn->data_len >= conn->request_len);
  7206. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7207. len = buf[1] & 127;
  7208. mask_len = buf[1] & 128 ? 4 : 0;
  7209. if (len < 126 && body_len >= mask_len) {
  7210. data_len = len;
  7211. header_len = 2 + mask_len;
  7212. } else if (len == 126 && body_len >= 4 + mask_len) {
  7213. header_len = 4 + mask_len;
  7214. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7215. } else if (body_len >= 10 + mask_len) {
  7216. header_len = 10 + mask_len;
  7217. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7218. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7219. }
  7220. }
  7221. if (header_len > 0 && body_len >= header_len) {
  7222. /* Allocate space to hold websocket payload */
  7223. data = mem;
  7224. if (data_len > sizeof(mem)) {
  7225. data = (char *)mg_malloc(data_len);
  7226. if (data == NULL) {
  7227. /* Allocation failed, exit the loop and then close the
  7228. * connection */
  7229. mg_cry(conn, "websocket out of memory; closing connection");
  7230. break;
  7231. }
  7232. }
  7233. /* Copy the mask before we shift the queue and destroy it */
  7234. if (mask_len > 0) {
  7235. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7236. } else {
  7237. memset(mask, 0, sizeof(mask));
  7238. }
  7239. /* Read frame payload from the first message in the queue into
  7240. * data and advance the queue by moving the memory in place. */
  7241. assert(body_len >= header_len);
  7242. if (data_len + header_len > body_len) {
  7243. mop = buf[0]; /* current mask and opcode */
  7244. /* Overflow case */
  7245. len = body_len - header_len;
  7246. memcpy(data, buf + header_len, len);
  7247. error = 0;
  7248. while (len < data_len) {
  7249. n = pull(
  7250. NULL, conn, data + len, (int)(data_len - len), timeout);
  7251. if (n <= 0) {
  7252. error = 1;
  7253. break;
  7254. }
  7255. len += (size_t)n;
  7256. }
  7257. if (error) {
  7258. mg_cry(conn, "Websocket pull failed; closing connection");
  7259. break;
  7260. }
  7261. conn->data_len = conn->request_len;
  7262. } else {
  7263. mop = buf[0]; /* current mask and opcode, overwritten by
  7264. * memmove() */
  7265. /* Length of the message being read at the front of the
  7266. * queue */
  7267. len = data_len + header_len;
  7268. /* Copy the data payload into the data pointer for the
  7269. * callback */
  7270. memcpy(data, buf + header_len, data_len);
  7271. /* Move the queue forward len bytes */
  7272. memmove(buf, buf + len, body_len - len);
  7273. /* Mark the queue as advanced */
  7274. conn->data_len -= (int)len;
  7275. }
  7276. /* Apply mask if necessary */
  7277. if (mask_len > 0) {
  7278. for (i = 0; i < data_len; ++i) {
  7279. data[i] ^= mask[i & 3];
  7280. }
  7281. }
  7282. /* Exit the loop if callback signals to exit (server side),
  7283. * or "connection close" opcode received (client side). */
  7284. exit_by_callback = 0;
  7285. if ((ws_data_handler != NULL)
  7286. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7287. exit_by_callback = 1;
  7288. }
  7289. if (data != mem) {
  7290. mg_free(data);
  7291. }
  7292. if (exit_by_callback
  7293. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7294. /* Opcode == 8, connection close */
  7295. break;
  7296. }
  7297. /* Not breaking the loop, process next websocket frame. */
  7298. } else {
  7299. /* Read from the socket into the next available location in the
  7300. * message queue. */
  7301. if ((n = pull(NULL,
  7302. conn,
  7303. conn->buf + conn->data_len,
  7304. conn->buf_size - conn->data_len,
  7305. timeout)) <= 0) {
  7306. /* Error, no bytes read */
  7307. break;
  7308. }
  7309. conn->data_len += n;
  7310. }
  7311. }
  7312. mg_set_thread_name("worker");
  7313. }
  7314. static int
  7315. mg_websocket_write_exec(struct mg_connection *conn,
  7316. int opcode,
  7317. const char *data,
  7318. size_t dataLen,
  7319. uint32_t masking_key)
  7320. {
  7321. unsigned char header[14];
  7322. size_t headerLen = 1;
  7323. int retval = -1;
  7324. header[0] = 0x80 + (opcode & 0xF);
  7325. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7326. if (dataLen < 126) {
  7327. /* inline 7-bit length field */
  7328. header[1] = (unsigned char)dataLen;
  7329. headerLen = 2;
  7330. } else if (dataLen <= 0xFFFF) {
  7331. /* 16-bit length field */
  7332. header[1] = 126;
  7333. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7334. headerLen = 4;
  7335. } else {
  7336. /* 64-bit length field */
  7337. header[1] = 127;
  7338. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7339. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7340. headerLen = 10;
  7341. }
  7342. if (masking_key) {
  7343. /* add mask */
  7344. header[1] |= 0x80;
  7345. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7346. headerLen += 4;
  7347. }
  7348. /* Note that POSIX/Winsock's send() is threadsafe
  7349. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7350. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7351. * push(), although that is only a problem if the packet is large or
  7352. * outgoing buffer is full). */
  7353. (void)mg_lock_connection(conn);
  7354. retval = mg_write(conn, header, headerLen);
  7355. if (dataLen > 0) {
  7356. retval = mg_write(conn, data, dataLen);
  7357. }
  7358. mg_unlock_connection(conn);
  7359. return retval;
  7360. }
  7361. int
  7362. mg_websocket_write(struct mg_connection *conn,
  7363. int opcode,
  7364. const char *data,
  7365. size_t dataLen)
  7366. {
  7367. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7368. }
  7369. static void
  7370. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7371. {
  7372. size_t i = 0;
  7373. i = 0;
  7374. if (((ptrdiff_t)in % 4) == 0) {
  7375. /* Convert in 32 bit words, if data is 4 byte aligned */
  7376. while (i < (in_len - 3)) {
  7377. *(uint32_t *)(void *)(out + i) =
  7378. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7379. i += 4;
  7380. }
  7381. }
  7382. if (i != in_len) {
  7383. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7384. while (i < in_len) {
  7385. *(uint8_t *)(void *)(out + i) =
  7386. *(uint8_t *)(void *)(in + i)
  7387. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7388. i++;
  7389. }
  7390. }
  7391. }
  7392. int
  7393. mg_websocket_client_write(struct mg_connection *conn,
  7394. int opcode,
  7395. const char *data,
  7396. size_t dataLen)
  7397. {
  7398. int retval = -1;
  7399. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7400. uint32_t masking_key = (uint32_t)get_random();
  7401. if (masked_data == NULL) {
  7402. /* Return -1 in an error case */
  7403. mg_cry(conn,
  7404. "Cannot allocate buffer for masked websocket response: "
  7405. "Out of memory");
  7406. return -1;
  7407. }
  7408. mask_data(data, dataLen, masking_key, masked_data);
  7409. retval = mg_websocket_write_exec(
  7410. conn, opcode, masked_data, dataLen, masking_key);
  7411. mg_free(masked_data);
  7412. return retval;
  7413. }
  7414. static void
  7415. handle_websocket_request(struct mg_connection *conn,
  7416. const char *path,
  7417. int is_callback_resource,
  7418. mg_websocket_connect_handler ws_connect_handler,
  7419. mg_websocket_ready_handler ws_ready_handler,
  7420. mg_websocket_data_handler ws_data_handler,
  7421. mg_websocket_close_handler ws_close_handler,
  7422. void *cbData)
  7423. {
  7424. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7425. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7426. int lua_websock = 0;
  7427. #if !defined(USE_LUA)
  7428. (void)path;
  7429. #endif
  7430. /* Step 1: Check websocket protocol version. */
  7431. /* Step 1.1: Check Sec-WebSocket-Key. */
  7432. if (!websock_key) {
  7433. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7434. * requires a Sec-WebSocket-Key header.
  7435. */
  7436. /* It could be the hixie draft version
  7437. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7438. */
  7439. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7440. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7441. char key3[8];
  7442. if ((key1 != NULL) && (key2 != NULL)) {
  7443. /* This version uses 8 byte body data in a GET request */
  7444. conn->content_len = 8;
  7445. if (8 == mg_read(conn, key3, 8)) {
  7446. /* This is the hixie version */
  7447. send_http_error(conn,
  7448. 426,
  7449. "%s",
  7450. "Protocol upgrade to RFC 6455 required");
  7451. return;
  7452. }
  7453. }
  7454. /* This is an unknown version */
  7455. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7456. return;
  7457. }
  7458. /* Step 1.2: Check websocket protocol version. */
  7459. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7460. if (version == NULL || strcmp(version, "13") != 0) {
  7461. /* Reject wrong versions */
  7462. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7463. return;
  7464. }
  7465. /* Step 1.3: Could check for "Host", but we do not really nead this
  7466. * value for anything, so just ignore it. */
  7467. /* Step 2: If a callback is responsible, call it. */
  7468. if (is_callback_resource) {
  7469. if (ws_connect_handler != NULL
  7470. && ws_connect_handler(conn, cbData) != 0) {
  7471. /* C callback has returned non-zero, do not proceed with
  7472. * handshake.
  7473. */
  7474. /* Note that C callbacks are no longer called when Lua is
  7475. * responsible, so C can no longer filter callbacks for Lua. */
  7476. return;
  7477. }
  7478. }
  7479. #if defined(USE_LUA)
  7480. /* Step 3: No callback. Check if Lua is responsible. */
  7481. else {
  7482. /* Step 3.1: Check if Lua is responsible. */
  7483. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7484. lua_websock =
  7485. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7486. strlen(
  7487. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7488. path);
  7489. }
  7490. if (lua_websock) {
  7491. /* Step 3.2: Lua is responsible: call it. */
  7492. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7493. if (!conn->lua_websocket_state) {
  7494. /* Lua rejected the new client */
  7495. return;
  7496. }
  7497. }
  7498. }
  7499. #endif
  7500. /* Step 4: Check if there is a responsible websocket handler. */
  7501. if (!is_callback_resource && !lua_websock) {
  7502. /* There is no callback, an Lua is not responsible either. */
  7503. /* Reply with a 404 Not Found or with nothing at all?
  7504. * TODO (mid): check the websocket standards, how to reply to
  7505. * requests to invalid websocket addresses. */
  7506. send_http_error(conn, 404, "%s", "Not found");
  7507. return;
  7508. }
  7509. /* Step 5: The websocket connection has been accepted */
  7510. if (!send_websocket_handshake(conn, websock_key)) {
  7511. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7512. return;
  7513. }
  7514. /* Step 6: Call the ready handler */
  7515. if (is_callback_resource) {
  7516. if (ws_ready_handler != NULL) {
  7517. ws_ready_handler(conn, cbData);
  7518. }
  7519. #if defined(USE_LUA)
  7520. } else if (lua_websock) {
  7521. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7522. /* the ready handler returned false */
  7523. return;
  7524. }
  7525. #endif
  7526. }
  7527. /* Step 7: Enter the read loop */
  7528. if (is_callback_resource) {
  7529. read_websocket(conn, ws_data_handler, cbData);
  7530. #if defined(USE_LUA)
  7531. } else if (lua_websock) {
  7532. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7533. #endif
  7534. }
  7535. /* Step 8: Call the close handler */
  7536. if (ws_close_handler) {
  7537. ws_close_handler(conn, cbData);
  7538. }
  7539. }
  7540. static int
  7541. is_websocket_protocol(const struct mg_connection *conn)
  7542. {
  7543. const char *upgrade, *connection;
  7544. /* A websocket protocoll has the following HTTP headers:
  7545. *
  7546. * Connection: Upgrade
  7547. * Upgrade: Websocket
  7548. */
  7549. upgrade = mg_get_header(conn, "Upgrade");
  7550. if (upgrade == NULL) {
  7551. return 0; /* fail early, don't waste time checking other header
  7552. * fields
  7553. */
  7554. }
  7555. if (!mg_strcasestr(upgrade, "websocket")) {
  7556. return 0;
  7557. }
  7558. connection = mg_get_header(conn, "Connection");
  7559. if (connection == NULL) {
  7560. return 0;
  7561. }
  7562. if (!mg_strcasestr(connection, "upgrade")) {
  7563. return 0;
  7564. }
  7565. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7566. * "Sec-WebSocket-Version" are also required.
  7567. * Don't check them here, since even an unsupported websocket protocol
  7568. * request still IS a websocket request (in contrast to a standard HTTP
  7569. * request). It will fail later in handle_websocket_request.
  7570. */
  7571. return 1;
  7572. }
  7573. #endif /* !USE_WEBSOCKET */
  7574. static int
  7575. isbyte(int n)
  7576. {
  7577. return n >= 0 && n <= 255;
  7578. }
  7579. static int
  7580. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7581. {
  7582. int n, a, b, c, d, slash = 32, len = 0;
  7583. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7584. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7585. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7586. && slash < 33) {
  7587. len = n;
  7588. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7589. | (uint32_t)d;
  7590. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7591. }
  7592. return len;
  7593. }
  7594. static int
  7595. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7596. {
  7597. int throttle = 0;
  7598. struct vec vec, val;
  7599. uint32_t net, mask;
  7600. char mult;
  7601. double v;
  7602. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7603. mult = ',';
  7604. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7605. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7606. && mult != ',')) {
  7607. continue;
  7608. }
  7609. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7610. : 1;
  7611. if (vec.len == 1 && vec.ptr[0] == '*') {
  7612. throttle = (int)v;
  7613. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7614. if ((remote_ip & mask) == net) {
  7615. throttle = (int)v;
  7616. }
  7617. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7618. throttle = (int)v;
  7619. }
  7620. }
  7621. return throttle;
  7622. }
  7623. static uint32_t
  7624. get_remote_ip(const struct mg_connection *conn)
  7625. {
  7626. if (!conn) {
  7627. return 0;
  7628. }
  7629. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7630. }
  7631. /* Experimental replacement for mg_upload. */
  7632. #include "handle_form.inl"
  7633. int
  7634. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7635. {
  7636. /* TODO (high): completely rewrite this function. See issue #180. */
  7637. /* TODO (mid): set a timeout */
  7638. const char *content_type_header, *boundary_start, *sc;
  7639. char *s;
  7640. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  7641. char fname[1024], boundary[100];
  7642. FILE *fp;
  7643. int bl, n, i, headers_len, boundary_len, eof, truncated;
  7644. int len = 0, num_uploaded_files = 0;
  7645. struct mg_request_info part_request_info;
  7646. /* Request looks like this:
  7647. *
  7648. * POST /upload HTTP/1.1
  7649. * Host: 127.0.0.1:8080
  7650. * Content-Length: 244894
  7651. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  7652. *
  7653. * ------WebKitFormBoundaryRVr
  7654. * Content-Disposition: form-data; name="file"; filename="accum.png"
  7655. * Content-Type: image/png
  7656. *
  7657. * <89>PNG
  7658. * <PNG DATA>
  7659. * ------WebKitFormBoundaryRVr */
  7660. /* Extract boundary string from the Content-Type header */
  7661. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL
  7662. || (boundary_start = mg_strcasestr(content_type_header, "boundary="))
  7663. == NULL
  7664. || (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0
  7665. && sscanf(boundary_start, "boundary=%99s", boundary) == 0)
  7666. || boundary[0] == '\0') {
  7667. return num_uploaded_files;
  7668. }
  7669. boundary[99] = 0;
  7670. boundary_len = (int)strlen(boundary);
  7671. bl = boundary_len + 4; /* \r\n--<boundary> */
  7672. for (;;) {
  7673. /* Pull in headers */
  7674. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  7675. if ((len < 0) || (len > (int)sizeof(buf))) {
  7676. break;
  7677. }
  7678. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  7679. len += n;
  7680. /* assert(len <= (int) sizeof(buf)); */
  7681. if (len > (int)sizeof(buf)) {
  7682. break;
  7683. }
  7684. }
  7685. if ((headers_len = get_request_len(buf, len)) <= 0) {
  7686. break;
  7687. }
  7688. /* terminate header */
  7689. buf[headers_len - 1] = 0;
  7690. /* Scan for the boundary string and skip it */
  7691. if (buf[0] == '-' && buf[1] == '-'
  7692. && !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  7693. s = &buf[bl];
  7694. } else {
  7695. s = &buf[2];
  7696. }
  7697. /* Get headers for this part of the multipart message */
  7698. memset(&part_request_info, 0, sizeof(part_request_info));
  7699. parse_http_headers(&s, &part_request_info);
  7700. /* assert(&buf[headers_len-1] == s); */
  7701. if (&buf[headers_len - 1] != s) {
  7702. break;
  7703. }
  7704. /* Fetch file name. */
  7705. sc = get_header(&part_request_info, "Content-Disposition");
  7706. if (!sc) {
  7707. /* invalid part of a multipart message */
  7708. break;
  7709. }
  7710. sc = strstr(sc, "filename");
  7711. if (!sc) {
  7712. /* no filename set */
  7713. break;
  7714. }
  7715. sc += 8; /* skip "filename" */
  7716. fname[0] = '\0';
  7717. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  7718. fname[1023] = 0;
  7719. /* Give up if the headers are not what we expect */
  7720. if (fname[0] == '\0') {
  7721. break;
  7722. }
  7723. /* Construct destination file name. Do not allow paths to have
  7724. * slashes. */
  7725. if ((s = strrchr(fname, '/')) == NULL
  7726. && (s = strrchr(fname, '\\')) == NULL) {
  7727. s = fname;
  7728. } else {
  7729. s++;
  7730. }
  7731. /* There data is written to a temporary file first. */
  7732. /* Different users should use a different destination_dir. */
  7733. mg_snprintf(conn,
  7734. &truncated,
  7735. path,
  7736. sizeof(path) - 1,
  7737. "%s/%s",
  7738. destination_dir,
  7739. s);
  7740. /* TODO(high): kick client on buffer overflow */
  7741. strcpy(tmp_path, path);
  7742. strcat(tmp_path, "~");
  7743. /* We open the file with exclusive lock held. This guarantee us
  7744. * there is no other thread can save into the same file
  7745. * simultaneously. */
  7746. fp = NULL;
  7747. /* Open file in binary mode. */
  7748. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7749. break;
  7750. }
  7751. /* Move data to the beginning of the buffer */
  7752. /* part_request_info is no longer valid after this operation */
  7753. /* assert(len >= headers_len); */
  7754. if (len < headers_len) {
  7755. break;
  7756. }
  7757. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7758. len -= headers_len;
  7759. /* Read POST data, write into file until boundary is found. */
  7760. eof = n = 0;
  7761. do {
  7762. len += n;
  7763. for (i = 0; i < len - bl; i++) {
  7764. if (!memcmp(&buf[i], "\r\n--", 4)
  7765. && !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7766. /* Found boundary, that's the end of file data. */
  7767. fwrite(buf, 1, (size_t)i, fp);
  7768. eof = 1;
  7769. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7770. len -= i + bl;
  7771. break;
  7772. }
  7773. }
  7774. if (!eof && len > bl) {
  7775. fwrite(buf, 1, (size_t)(len - bl), fp);
  7776. memmove(buf, &buf[len - bl], (size_t)bl);
  7777. len = bl;
  7778. }
  7779. if (!eof) {
  7780. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7781. }
  7782. } while (!eof && (n > 0));
  7783. fclose(fp);
  7784. if (eof) {
  7785. remove(path);
  7786. rename(tmp_path, path);
  7787. num_uploaded_files++;
  7788. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7789. conn->ctx->callbacks.upload(conn, path);
  7790. }
  7791. } else {
  7792. remove(tmp_path);
  7793. }
  7794. }
  7795. return num_uploaded_files;
  7796. }
  7797. static int
  7798. get_first_ssl_listener_index(const struct mg_context *ctx)
  7799. {
  7800. unsigned int i;
  7801. int idx = -1;
  7802. if (ctx) {
  7803. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7804. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7805. }
  7806. }
  7807. return idx;
  7808. }
  7809. static void
  7810. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7811. {
  7812. char host[1025];
  7813. const char *host_header;
  7814. size_t hostlen;
  7815. host_header = mg_get_header(conn, "Host");
  7816. hostlen = sizeof(host);
  7817. if (host_header != NULL) {
  7818. char *pos;
  7819. mg_strlcpy(host, host_header, hostlen);
  7820. host[hostlen - 1] = '\0';
  7821. pos = strchr(host, ':');
  7822. if (pos != NULL) {
  7823. *pos = '\0';
  7824. }
  7825. } else {
  7826. /* Cannot get host from the Host: header.
  7827. * Fallback to our IP address. */
  7828. if (conn) {
  7829. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7830. }
  7831. }
  7832. /* Send host, port, uri and (if it exists) ?query_string */
  7833. if (conn) {
  7834. mg_printf(conn,
  7835. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7836. host,
  7837. (int)ntohs(
  7838. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7839. conn->request_info.local_uri,
  7840. (conn->request_info.query_string == NULL) ? "" : "?",
  7841. (conn->request_info.query_string == NULL)
  7842. ? ""
  7843. : conn->request_info.query_string);
  7844. }
  7845. }
  7846. static void
  7847. mg_set_handler_type(struct mg_context *ctx,
  7848. const char *uri,
  7849. int handler_type,
  7850. int is_delete_request,
  7851. mg_request_handler handler,
  7852. mg_websocket_connect_handler connect_handler,
  7853. mg_websocket_ready_handler ready_handler,
  7854. mg_websocket_data_handler data_handler,
  7855. mg_websocket_close_handler close_handler,
  7856. mg_authorization_handler auth_handler,
  7857. void *cbdata)
  7858. {
  7859. struct mg_handler_info *tmp_rh, **lastref;
  7860. size_t urilen = strlen(uri);
  7861. if (handler_type == WEBSOCKET_HANDLER) {
  7862. /* assert(handler == NULL); */
  7863. /* assert(is_delete_request || connect_handler!=NULL ||
  7864. * ready_handler!=NULL || data_handler!=NULL ||
  7865. * close_handler!=NULL);
  7866. */
  7867. /* assert(auth_handler == NULL); */
  7868. if (handler != NULL) {
  7869. return;
  7870. }
  7871. if (!is_delete_request && connect_handler == NULL
  7872. && ready_handler == NULL
  7873. && data_handler == NULL
  7874. && close_handler == NULL) {
  7875. return;
  7876. }
  7877. if (auth_handler != NULL) {
  7878. return;
  7879. }
  7880. } else if (handler_type == REQUEST_HANDLER) {
  7881. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7882. * data_handler==NULL && close_handler==NULL); */
  7883. /* assert(is_delete_request || (handler!=NULL));
  7884. */
  7885. /* assert(auth_handler == NULL); */
  7886. if (connect_handler != NULL || ready_handler != NULL
  7887. || data_handler != NULL
  7888. || close_handler != NULL) {
  7889. return;
  7890. }
  7891. if (!is_delete_request && (handler == NULL)) {
  7892. return;
  7893. }
  7894. if (auth_handler != NULL) {
  7895. return;
  7896. }
  7897. } else { /* AUTH_HANDLER */
  7898. /* assert(handler == NULL); */
  7899. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7900. * data_handler==NULL && close_handler==NULL); */
  7901. /* assert(auth_handler != NULL); */
  7902. if (handler != NULL) {
  7903. return;
  7904. }
  7905. if (connect_handler != NULL || ready_handler != NULL
  7906. || data_handler != NULL
  7907. || close_handler != NULL) {
  7908. return;
  7909. }
  7910. if (!is_delete_request && (auth_handler == NULL)) {
  7911. return;
  7912. }
  7913. }
  7914. if (!ctx) {
  7915. return;
  7916. }
  7917. mg_lock_context(ctx);
  7918. /* first try to find an existing handler */
  7919. lastref = &(ctx->handlers);
  7920. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  7921. if (tmp_rh->handler_type == handler_type) {
  7922. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7923. if (!is_delete_request) {
  7924. /* update existing handler */
  7925. if (handler_type == REQUEST_HANDLER) {
  7926. tmp_rh->handler = handler;
  7927. } else if (handler_type == WEBSOCKET_HANDLER) {
  7928. tmp_rh->connect_handler = connect_handler;
  7929. tmp_rh->ready_handler = ready_handler;
  7930. tmp_rh->data_handler = data_handler;
  7931. tmp_rh->close_handler = close_handler;
  7932. } else { /* AUTH_HANDLER */
  7933. tmp_rh->auth_handler = auth_handler;
  7934. }
  7935. tmp_rh->cbdata = cbdata;
  7936. } else {
  7937. /* remove existing handler */
  7938. *lastref = tmp_rh->next;
  7939. mg_free(tmp_rh->uri);
  7940. mg_free(tmp_rh);
  7941. }
  7942. mg_unlock_context(ctx);
  7943. return;
  7944. }
  7945. }
  7946. lastref = &(tmp_rh->next);
  7947. }
  7948. if (is_delete_request) {
  7949. /* no handler to set, this was a remove request to a non-existing
  7950. * handler */
  7951. mg_unlock_context(ctx);
  7952. return;
  7953. }
  7954. tmp_rh =
  7955. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  7956. if (tmp_rh == NULL) {
  7957. mg_unlock_context(ctx);
  7958. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7959. return;
  7960. }
  7961. tmp_rh->uri = mg_strdup(uri);
  7962. if (!tmp_rh->uri) {
  7963. mg_unlock_context(ctx);
  7964. mg_free(tmp_rh);
  7965. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7966. return;
  7967. }
  7968. tmp_rh->uri_len = urilen;
  7969. if (handler_type == REQUEST_HANDLER) {
  7970. tmp_rh->handler = handler;
  7971. } else if (handler_type == WEBSOCKET_HANDLER) {
  7972. tmp_rh->connect_handler = connect_handler;
  7973. tmp_rh->ready_handler = ready_handler;
  7974. tmp_rh->data_handler = data_handler;
  7975. tmp_rh->close_handler = close_handler;
  7976. } else { /* AUTH_HANDLER */
  7977. tmp_rh->auth_handler = auth_handler;
  7978. }
  7979. tmp_rh->cbdata = cbdata;
  7980. tmp_rh->handler_type = handler_type;
  7981. tmp_rh->next = NULL;
  7982. *lastref = tmp_rh;
  7983. mg_unlock_context(ctx);
  7984. }
  7985. void
  7986. mg_set_request_handler(struct mg_context *ctx,
  7987. const char *uri,
  7988. mg_request_handler handler,
  7989. void *cbdata)
  7990. {
  7991. mg_set_handler_type(ctx,
  7992. uri,
  7993. REQUEST_HANDLER,
  7994. handler == NULL,
  7995. handler,
  7996. NULL,
  7997. NULL,
  7998. NULL,
  7999. NULL,
  8000. NULL,
  8001. cbdata);
  8002. }
  8003. void
  8004. mg_set_websocket_handler(struct mg_context *ctx,
  8005. const char *uri,
  8006. mg_websocket_connect_handler connect_handler,
  8007. mg_websocket_ready_handler ready_handler,
  8008. mg_websocket_data_handler data_handler,
  8009. mg_websocket_close_handler close_handler,
  8010. void *cbdata)
  8011. {
  8012. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8013. && (data_handler == NULL)
  8014. && (close_handler == NULL);
  8015. mg_set_handler_type(ctx,
  8016. uri,
  8017. WEBSOCKET_HANDLER,
  8018. is_delete_request,
  8019. NULL,
  8020. connect_handler,
  8021. ready_handler,
  8022. data_handler,
  8023. close_handler,
  8024. NULL,
  8025. cbdata);
  8026. }
  8027. void
  8028. mg_set_auth_handler(struct mg_context *ctx,
  8029. const char *uri,
  8030. mg_request_handler handler,
  8031. void *cbdata)
  8032. {
  8033. mg_set_handler_type(ctx,
  8034. uri,
  8035. AUTH_HANDLER,
  8036. handler == NULL,
  8037. NULL,
  8038. NULL,
  8039. NULL,
  8040. NULL,
  8041. NULL,
  8042. handler,
  8043. cbdata);
  8044. }
  8045. static int
  8046. get_request_handler(struct mg_connection *conn,
  8047. int handler_type,
  8048. mg_request_handler *handler,
  8049. mg_websocket_connect_handler *connect_handler,
  8050. mg_websocket_ready_handler *ready_handler,
  8051. mg_websocket_data_handler *data_handler,
  8052. mg_websocket_close_handler *close_handler,
  8053. mg_authorization_handler *auth_handler,
  8054. void **cbdata)
  8055. {
  8056. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8057. if (request_info) {
  8058. const char *uri = request_info->local_uri;
  8059. size_t urilen = strlen(uri);
  8060. struct mg_handler_info *tmp_rh;
  8061. if (!conn || !conn->ctx) {
  8062. return 0;
  8063. }
  8064. mg_lock_context(conn->ctx);
  8065. /* first try for an exact match */
  8066. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8067. tmp_rh = tmp_rh->next) {
  8068. if (tmp_rh->handler_type == handler_type) {
  8069. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8070. if (handler_type == WEBSOCKET_HANDLER) {
  8071. *connect_handler = tmp_rh->connect_handler;
  8072. *ready_handler = tmp_rh->ready_handler;
  8073. *data_handler = tmp_rh->data_handler;
  8074. *close_handler = tmp_rh->close_handler;
  8075. } else if (handler_type == REQUEST_HANDLER) {
  8076. *handler = tmp_rh->handler;
  8077. } else { /* AUTH_HANDLER */
  8078. *auth_handler = tmp_rh->auth_handler;
  8079. }
  8080. *cbdata = tmp_rh->cbdata;
  8081. mg_unlock_context(conn->ctx);
  8082. return 1;
  8083. }
  8084. }
  8085. }
  8086. /* next try for a partial match, we will accept uri/something */
  8087. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8088. tmp_rh = tmp_rh->next) {
  8089. if (tmp_rh->handler_type == handler_type) {
  8090. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8091. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8092. if (handler_type == WEBSOCKET_HANDLER) {
  8093. *connect_handler = tmp_rh->connect_handler;
  8094. *ready_handler = tmp_rh->ready_handler;
  8095. *data_handler = tmp_rh->data_handler;
  8096. *close_handler = tmp_rh->close_handler;
  8097. } else if (handler_type == REQUEST_HANDLER) {
  8098. *handler = tmp_rh->handler;
  8099. } else { /* AUTH_HANDLER */
  8100. *auth_handler = tmp_rh->auth_handler;
  8101. }
  8102. *cbdata = tmp_rh->cbdata;
  8103. mg_unlock_context(conn->ctx);
  8104. return 1;
  8105. }
  8106. }
  8107. }
  8108. /* finally try for pattern match */
  8109. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8110. tmp_rh = tmp_rh->next) {
  8111. if (tmp_rh->handler_type == handler_type) {
  8112. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8113. if (handler_type == WEBSOCKET_HANDLER) {
  8114. *connect_handler = tmp_rh->connect_handler;
  8115. *ready_handler = tmp_rh->ready_handler;
  8116. *data_handler = tmp_rh->data_handler;
  8117. *close_handler = tmp_rh->close_handler;
  8118. } else if (handler_type == REQUEST_HANDLER) {
  8119. *handler = tmp_rh->handler;
  8120. } else { /* AUTH_HANDLER */
  8121. *auth_handler = tmp_rh->auth_handler;
  8122. }
  8123. *cbdata = tmp_rh->cbdata;
  8124. mg_unlock_context(conn->ctx);
  8125. return 1;
  8126. }
  8127. }
  8128. }
  8129. mg_unlock_context(conn->ctx);
  8130. }
  8131. return 0; /* none found */
  8132. }
  8133. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8134. static int
  8135. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8136. void *cbdata)
  8137. {
  8138. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8139. if (pcallbacks->websocket_connect) {
  8140. return pcallbacks->websocket_connect(conn);
  8141. }
  8142. /* No handler set - assume "OK" */
  8143. return 0;
  8144. }
  8145. static void
  8146. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8147. {
  8148. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8149. if (pcallbacks->websocket_ready) {
  8150. pcallbacks->websocket_ready(conn);
  8151. }
  8152. }
  8153. static int
  8154. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8155. int bits,
  8156. char *data,
  8157. size_t len,
  8158. void *cbdata)
  8159. {
  8160. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8161. if (pcallbacks->websocket_data) {
  8162. return pcallbacks->websocket_data(conn, bits, data, len);
  8163. }
  8164. /* No handler set - assume "OK" */
  8165. return 1;
  8166. }
  8167. #endif
  8168. /* This is the heart of the Civetweb's logic.
  8169. * This function is called when the request is read, parsed and validated,
  8170. * and Civetweb must decide what action to take: serve a file, or
  8171. * a directory, or call embedded function, etcetera. */
  8172. static void
  8173. handle_request(struct mg_connection *conn)
  8174. {
  8175. if (conn) {
  8176. struct mg_request_info *ri = &conn->request_info;
  8177. char path[PATH_MAX];
  8178. int uri_len, ssl_index;
  8179. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8180. is_put_or_delete_request = 0, is_callback_resource = 0;
  8181. int i;
  8182. struct file file = STRUCT_FILE_INITIALIZER;
  8183. mg_request_handler callback_handler = NULL;
  8184. mg_websocket_connect_handler ws_connect_handler = NULL;
  8185. mg_websocket_ready_handler ws_ready_handler = NULL;
  8186. mg_websocket_data_handler ws_data_handler = NULL;
  8187. mg_websocket_close_handler ws_close_handler = NULL;
  8188. void *callback_data = NULL;
  8189. mg_authorization_handler auth_handler = NULL;
  8190. void *auth_callback_data = NULL;
  8191. #if !defined(NO_FILES)
  8192. time_t curtime = time(NULL);
  8193. char date[64];
  8194. #endif
  8195. path[0] = 0;
  8196. if (!ri) {
  8197. return;
  8198. }
  8199. /* 1. get the request url */
  8200. /* 1.1. split into url and query string */
  8201. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8202. != NULL) {
  8203. *((char *)conn->request_info.query_string++) = '\0';
  8204. }
  8205. uri_len = (int)strlen(ri->local_uri);
  8206. /* 1.2. decode url (if config says so) */
  8207. if (should_decode_url(conn)) {
  8208. mg_url_decode(
  8209. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8210. }
  8211. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8212. * not
  8213. * possible */
  8214. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8215. /* step 1. completed, the url is known now */
  8216. DEBUG_TRACE("URL: %s", ri->local_uri);
  8217. /* 2. do a https redirect, if required */
  8218. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8219. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8220. if (ssl_index >= 0) {
  8221. redirect_to_https_port(conn, ssl_index);
  8222. } else {
  8223. /* A http to https forward port has been specified,
  8224. * but no https port to forward to. */
  8225. send_http_error(conn,
  8226. 503,
  8227. "%s",
  8228. "Error: SSL forward not configured properly");
  8229. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8230. }
  8231. return;
  8232. }
  8233. /* 3. if this ip has limited speed, set it for this connection */
  8234. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8235. get_remote_ip(conn),
  8236. ri->local_uri);
  8237. /* 4. call a "handle everything" callback, if registered */
  8238. if (conn->ctx->callbacks.begin_request != NULL) {
  8239. /* Note that since V1.7 the "begin_request" function is called
  8240. * before an authorization check. If an authorization check is
  8241. * required, use a request_handler instead. */
  8242. i = conn->ctx->callbacks.begin_request(conn);
  8243. if (i > 0) {
  8244. /* callback already processed the request. Store the
  8245. return value as a status code for the access log. */
  8246. conn->status_code = i;
  8247. return;
  8248. } else if (i == 0) {
  8249. /* civetweb should process the request */
  8250. } else {
  8251. /* unspecified - may change with the next version */
  8252. return;
  8253. }
  8254. }
  8255. /* request not yet handled by a handler or redirect, so the request
  8256. * is processed here */
  8257. /* 5. interpret the url to find out how the request must be handled
  8258. */
  8259. /* 5.1. first test, if the request targets the regular http(s)://
  8260. * protocol namespace or the websocket ws(s):// protocol namespace.
  8261. */
  8262. is_websocket_request = is_websocket_protocol(conn);
  8263. /* 5.2. check if the request will be handled by a callback */
  8264. if (get_request_handler(conn,
  8265. is_websocket_request ? WEBSOCKET_HANDLER
  8266. : REQUEST_HANDLER,
  8267. &callback_handler,
  8268. &ws_connect_handler,
  8269. &ws_ready_handler,
  8270. &ws_data_handler,
  8271. &ws_close_handler,
  8272. NULL,
  8273. &callback_data)) {
  8274. /* 5.2.1. A callback will handle this request. All requests
  8275. * handled
  8276. * by a callback have to be considered as requests to a script
  8277. * resource. */
  8278. is_callback_resource = 1;
  8279. is_script_resource = 1;
  8280. is_put_or_delete_request = is_put_or_delete_method(conn);
  8281. } else {
  8282. no_callback_resource:
  8283. /* 5.2.2. No callback is responsible for this request. The URI
  8284. * addresses a file based resource (static content or Lua/cgi
  8285. * scripts in the file system). */
  8286. is_callback_resource = 0;
  8287. interpret_uri(conn,
  8288. path,
  8289. sizeof(path),
  8290. &file,
  8291. &is_found,
  8292. &is_script_resource,
  8293. &is_websocket_request,
  8294. &is_put_or_delete_request);
  8295. }
  8296. /* 6. authorization check */
  8297. /* 6.1. a custom authorization handler is installed */
  8298. if (get_request_handler(conn,
  8299. AUTH_HANDLER,
  8300. NULL,
  8301. NULL,
  8302. NULL,
  8303. NULL,
  8304. NULL,
  8305. &auth_handler,
  8306. &auth_callback_data)) {
  8307. if (!auth_handler(conn, auth_callback_data)) {
  8308. return;
  8309. }
  8310. } else if (is_put_or_delete_request && !is_script_resource
  8311. && !is_callback_resource) {
  8312. /* 6.2. this request is a PUT/DELETE to a real file */
  8313. /* 6.2.1. thus, the server must have real files */
  8314. #if defined(NO_FILES)
  8315. if (1) {
  8316. #else
  8317. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8318. #endif
  8319. /* This server does not have any real files, thus the
  8320. * PUT/DELETE methods are not valid. */
  8321. send_http_error(conn,
  8322. 405,
  8323. "%s method not allowed",
  8324. conn->request_info.request_method);
  8325. return;
  8326. }
  8327. #if !defined(NO_FILES)
  8328. /* 6.2.2. Check if put authorization for static files is available.
  8329. */
  8330. if (!is_authorized_for_put(conn)) {
  8331. send_authorization_request(conn);
  8332. return;
  8333. }
  8334. #endif
  8335. } else {
  8336. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8337. * or it is a PUT or DELETE request to a resource that does not
  8338. * correspond to a file. Check authorization. */
  8339. if (!check_authorization(conn, path)) {
  8340. send_authorization_request(conn);
  8341. return;
  8342. }
  8343. }
  8344. /* request is authorized or does not need authorization */
  8345. /* 7. check if there are request handlers for this uri */
  8346. if (is_callback_resource) {
  8347. if (!is_websocket_request) {
  8348. i = callback_handler(conn, callback_data);
  8349. if (i > 0) {
  8350. /* Do nothing, callback has served the request. Store
  8351. * the
  8352. * return value as status code for the log and discard
  8353. * all
  8354. * data from the client not used by the callback. */
  8355. conn->status_code = i;
  8356. discard_unread_request_data(conn);
  8357. } else {
  8358. /* TODO (high): what if the handler did NOT handle the
  8359. * request */
  8360. /* The last version did handle this as a file request,
  8361. * but
  8362. * since a file request is not always a script resource,
  8363. * the authorization check might be different */
  8364. interpret_uri(conn,
  8365. path,
  8366. sizeof(path),
  8367. &file,
  8368. &is_found,
  8369. &is_script_resource,
  8370. &is_websocket_request,
  8371. &is_put_or_delete_request);
  8372. callback_handler = NULL;
  8373. /* TODO (very low): goto is deprecated but for the
  8374. * moment,
  8375. * a goto is simpler than some curious loop. */
  8376. /* The situation "callback does not handle the request"
  8377. * needs to be reconsidered anyway. */
  8378. goto no_callback_resource;
  8379. }
  8380. } else {
  8381. #if defined(USE_WEBSOCKET)
  8382. handle_websocket_request(conn,
  8383. path,
  8384. is_callback_resource,
  8385. ws_connect_handler,
  8386. ws_ready_handler,
  8387. ws_data_handler,
  8388. ws_close_handler,
  8389. callback_data);
  8390. #endif
  8391. }
  8392. return;
  8393. }
  8394. /* 8. handle websocket requests */
  8395. #if defined(USE_WEBSOCKET)
  8396. if (is_websocket_request) {
  8397. if (is_script_resource) {
  8398. /* Websocket Lua script */
  8399. handle_websocket_request(conn,
  8400. path,
  8401. 0 /* Lua Script */,
  8402. NULL,
  8403. NULL,
  8404. NULL,
  8405. NULL,
  8406. &conn->ctx->callbacks);
  8407. } else {
  8408. #if defined(MG_LEGACY_INTERFACE)
  8409. handle_websocket_request(
  8410. conn,
  8411. path,
  8412. !is_script_resource /* could be deprecated global callback */,
  8413. deprecated_websocket_connect_wrapper,
  8414. deprecated_websocket_ready_wrapper,
  8415. deprecated_websocket_data_wrapper,
  8416. NULL,
  8417. &conn->ctx->callbacks);
  8418. #else
  8419. send_http_error(conn, 404, "%s", "Not found");
  8420. #endif
  8421. }
  8422. return;
  8423. } else
  8424. #endif
  8425. #if defined(NO_FILES)
  8426. /* 9a. In case the server uses only callbacks, this uri is
  8427. * unknown.
  8428. * Then, all request handling ends here. */
  8429. send_http_error(conn, 404, "%s", "Not Found");
  8430. #else
  8431. /* 9b. This request is either for a static file or resource handled
  8432. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8433. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8434. send_http_error(conn, 404, "%s", "Not Found");
  8435. return;
  8436. }
  8437. /* 10. File is handled by a script. */
  8438. if (is_script_resource) {
  8439. handle_file_based_request(conn, path, &file);
  8440. return;
  8441. }
  8442. /* 11. Handle put/delete/mkcol requests */
  8443. if (is_put_or_delete_request) {
  8444. /* 11.1. PUT method */
  8445. if (!strcmp(ri->request_method, "PUT")) {
  8446. put_file(conn, path);
  8447. return;
  8448. }
  8449. /* 11.2. DELETE method */
  8450. if (!strcmp(ri->request_method, "DELETE")) {
  8451. delete_file(conn, path);
  8452. return;
  8453. }
  8454. /* 11.3. MKCOL method */
  8455. if (!strcmp(ri->request_method, "MKCOL")) {
  8456. mkcol(conn, path);
  8457. return;
  8458. }
  8459. /* 11.4. PATCH method
  8460. * This method is not supported for static resources,
  8461. * only for scripts (Lua, CGI) and callbacks. */
  8462. send_http_error(conn,
  8463. 405,
  8464. "%s method not allowed",
  8465. conn->request_info.request_method);
  8466. return;
  8467. }
  8468. /* 11. File does not exist, or it was configured that it should be
  8469. * hidden */
  8470. if (!is_found || (must_hide_file(conn, path))) {
  8471. send_http_error(conn, 404, "%s", "Not found");
  8472. return;
  8473. }
  8474. /* 12. Directory uris should end with a slash */
  8475. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8476. gmt_time_string(date, sizeof(date), &curtime);
  8477. mg_printf(conn,
  8478. "HTTP/1.1 301 Moved Permanently\r\n"
  8479. "Location: %s/\r\n"
  8480. "Date: %s\r\n"
  8481. /* "Cache-Control: private\r\n" (= default) */
  8482. "Content-Length: 0\r\n"
  8483. "Connection: %s\r\n\r\n",
  8484. ri->request_uri,
  8485. date,
  8486. suggest_connection_header(conn));
  8487. return;
  8488. }
  8489. /* 13. Handle other methods than GET/HEAD */
  8490. /* 13.1. Handle PROPFIND */
  8491. if (!strcmp(ri->request_method, "PROPFIND")) {
  8492. handle_propfind(conn, path, &file);
  8493. return;
  8494. }
  8495. /* 13.2. Handle OPTIONS for files */
  8496. if (!strcmp(ri->request_method, "OPTIONS")) {
  8497. /* This standard handler is only used for real files.
  8498. * Scripts should support the OPTIONS method themselves, to allow a
  8499. * maximum flexibility.
  8500. * Lua and CGI scripts may fully support CORS this way (including
  8501. * preflights). */
  8502. send_options(conn);
  8503. return;
  8504. }
  8505. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8506. if (0 != strcmp(ri->request_method, "GET")
  8507. && 0 != strcmp(ri->request_method, "HEAD")) {
  8508. send_http_error(conn,
  8509. 405,
  8510. "%s method not allowed",
  8511. conn->request_info.request_method);
  8512. return;
  8513. }
  8514. /* 14. directories */
  8515. if (file.is_directory) {
  8516. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8517. /* 14.1. use a substitute file */
  8518. /* TODO (high): substitute index may be a script resource.
  8519. * define what should be possible in this case. */
  8520. } else {
  8521. /* 14.2. no substitute file */
  8522. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8523. "yes")) {
  8524. handle_directory_request(conn, path);
  8525. } else {
  8526. send_http_error(conn,
  8527. 403,
  8528. "%s",
  8529. "Error: Directory listing denied");
  8530. }
  8531. return;
  8532. }
  8533. }
  8534. handle_file_based_request(conn, path, &file);
  8535. #endif /* !defined(NO_FILES) */
  8536. #if 0
  8537. /* Perform redirect and auth checks before calling begin_request()
  8538. * handler.
  8539. * Otherwise, begin_request() would need to perform auth checks and
  8540. * redirects. */
  8541. #endif
  8542. }
  8543. return;
  8544. }
  8545. static void
  8546. handle_file_based_request(struct mg_connection *conn,
  8547. const char *path,
  8548. struct file *file)
  8549. {
  8550. if (!conn || !conn->ctx) {
  8551. return;
  8552. }
  8553. if (0) {
  8554. #ifdef USE_LUA
  8555. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8556. strlen(
  8557. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8558. path) > 0) {
  8559. /* Lua server page: an SSI like page containing mostly plain html
  8560. * code
  8561. * plus some tags with server generated contents. */
  8562. handle_lsp_request(conn, path, file, NULL);
  8563. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8564. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8565. path) > 0) {
  8566. /* Lua in-server module script: a CGI like script used to generate
  8567. * the
  8568. * entire reply. */
  8569. mg_exec_lua_script(conn, path, NULL);
  8570. #endif
  8571. #if defined(USE_DUKTAPE)
  8572. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8573. strlen(
  8574. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8575. path) > 0) {
  8576. /* Call duktape to generate the page */
  8577. mg_exec_duktape_script(conn, path);
  8578. #endif
  8579. #if !defined(NO_CGI)
  8580. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8581. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8582. path) > 0) {
  8583. /* CGI scripts may support all HTTP methods */
  8584. handle_cgi_request(conn, path);
  8585. #endif /* !NO_CGI */
  8586. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8587. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8588. path) > 0) {
  8589. handle_ssi_file_request(conn, path, file);
  8590. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8591. /* Send 304 "Not Modified" - this must not send any body data */
  8592. send_http_error(conn, 304, "%s", "");
  8593. } else {
  8594. handle_static_file_request(conn, path, file);
  8595. }
  8596. }
  8597. static void
  8598. close_all_listening_sockets(struct mg_context *ctx)
  8599. {
  8600. unsigned int i;
  8601. if (!ctx) {
  8602. return;
  8603. }
  8604. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8605. closesocket(ctx->listening_sockets[i].sock);
  8606. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8607. }
  8608. mg_free(ctx->listening_sockets);
  8609. ctx->listening_sockets = NULL;
  8610. mg_free(ctx->listening_ports);
  8611. ctx->listening_ports = NULL;
  8612. }
  8613. /* Valid listening port specification is: [ip_address:]port[s]
  8614. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8615. * Examples for IPv6: [::]:80, [::1]:80,
  8616. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8617. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8618. static int
  8619. parse_port_string(const struct vec *vec, struct socket *so)
  8620. {
  8621. unsigned int a, b, c, d, port;
  8622. int ch, len;
  8623. #if defined(USE_IPV6)
  8624. char buf[100] = {0};
  8625. #endif
  8626. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8627. * Also, all-zeroes in the socket address means binding to all addresses
  8628. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8629. memset(so, 0, sizeof(*so));
  8630. so->lsa.sin.sin_family = AF_INET;
  8631. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8632. == 5) {
  8633. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8634. so->lsa.sin.sin_addr.s_addr =
  8635. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8636. so->lsa.sin.sin_port = htons((uint16_t)port);
  8637. #if defined(USE_IPV6)
  8638. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8639. && mg_inet_pton(
  8640. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8641. /* IPv6 address, examples: see above */
  8642. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8643. */
  8644. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8645. #endif
  8646. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8647. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8648. so->lsa.sin.sin_port = htons((uint16_t)port);
  8649. } else {
  8650. /* Parsing failure. Make port invalid. */
  8651. port = 0;
  8652. len = 0;
  8653. }
  8654. /* sscanf and the option splitting code ensure the following condition
  8655. */
  8656. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8657. return 0;
  8658. }
  8659. ch = vec->ptr[len]; /* Next character after the port number */
  8660. so->is_ssl = (ch == 's');
  8661. so->ssl_redir = (ch == 'r');
  8662. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8663. return is_valid_port(port)
  8664. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8665. }
  8666. static int
  8667. set_ports_option(struct mg_context *ctx)
  8668. {
  8669. const char *list;
  8670. int on = 1;
  8671. #if defined(USE_IPV6)
  8672. int off = 0;
  8673. #endif
  8674. struct vec vec;
  8675. struct socket so, *ptr;
  8676. in_port_t *portPtr;
  8677. union usa usa;
  8678. socklen_t len;
  8679. int portsTotal = 0;
  8680. int portsOk = 0;
  8681. if (!ctx) {
  8682. return 0;
  8683. }
  8684. memset(&so, 0, sizeof(so));
  8685. memset(&usa, 0, sizeof(usa));
  8686. len = sizeof(usa);
  8687. list = ctx->config[LISTENING_PORTS];
  8688. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8689. portsTotal++;
  8690. if (!parse_port_string(&vec, &so)) {
  8691. mg_cry(fc(ctx),
  8692. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8693. (int)vec.len,
  8694. vec.ptr,
  8695. portsTotal,
  8696. "[IP_ADDRESS:]PORT[s|r]");
  8697. continue;
  8698. }
  8699. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8700. mg_cry(fc(ctx),
  8701. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8702. "option set?",
  8703. portsTotal);
  8704. continue;
  8705. }
  8706. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8707. == INVALID_SOCKET) {
  8708. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8709. continue;
  8710. }
  8711. #ifdef _WIN32
  8712. /* Windows SO_REUSEADDR lets many procs binds to a
  8713. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8714. * if someone already has the socket -- DTL */
  8715. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8716. * Windows might need a few seconds before
  8717. * the same port can be used again in the
  8718. * same process, so a short Sleep may be
  8719. * required between mg_stop and mg_start.
  8720. */
  8721. if (setsockopt(so.sock,
  8722. SOL_SOCKET,
  8723. SO_EXCLUSIVEADDRUSE,
  8724. (SOCK_OPT_TYPE)&on,
  8725. sizeof(on)) != 0) {
  8726. mg_cry(fc(ctx),
  8727. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8728. portsTotal);
  8729. }
  8730. #else
  8731. if (setsockopt(so.sock,
  8732. SOL_SOCKET,
  8733. SO_REUSEADDR,
  8734. (SOCK_OPT_TYPE)&on,
  8735. sizeof(on)) != 0) {
  8736. mg_cry(fc(ctx),
  8737. "cannot set socket option SO_REUSEADDR (entry %i)",
  8738. portsTotal);
  8739. }
  8740. #endif
  8741. #if defined(USE_IPV6)
  8742. if (so.lsa.sa.sa_family == AF_INET6
  8743. && setsockopt(so.sock,
  8744. IPPROTO_IPV6,
  8745. IPV6_V6ONLY,
  8746. (void *)&off,
  8747. sizeof(off)) != 0) {
  8748. mg_cry(fc(ctx),
  8749. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8750. portsTotal);
  8751. }
  8752. #endif
  8753. if (so.lsa.sa.sa_family == AF_INET) {
  8754. len = sizeof(so.lsa.sin);
  8755. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8756. mg_cry(fc(ctx),
  8757. "cannot bind to %.*s: %d (%s)",
  8758. (int)vec.len,
  8759. vec.ptr,
  8760. (int)ERRNO,
  8761. strerror(errno));
  8762. closesocket(so.sock);
  8763. so.sock = INVALID_SOCKET;
  8764. continue;
  8765. }
  8766. }
  8767. #if defined(USE_IPV6)
  8768. else if (so.lsa.sa.sa_family == AF_INET6) {
  8769. len = sizeof(so.lsa.sin6);
  8770. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8771. mg_cry(fc(ctx),
  8772. "cannot bind to IPv6 %.*s: %d (%s)",
  8773. (int)vec.len,
  8774. vec.ptr,
  8775. (int)ERRNO,
  8776. strerror(errno));
  8777. closesocket(so.sock);
  8778. so.sock = INVALID_SOCKET;
  8779. continue;
  8780. }
  8781. }
  8782. #endif
  8783. else {
  8784. mg_cry(fc(ctx),
  8785. "cannot bind: address family not supported (entry %i)",
  8786. portsTotal);
  8787. continue;
  8788. }
  8789. if (listen(so.sock, SOMAXCONN) != 0) {
  8790. mg_cry(fc(ctx),
  8791. "cannot listen to %.*s: %d (%s)",
  8792. (int)vec.len,
  8793. vec.ptr,
  8794. (int)ERRNO,
  8795. strerror(errno));
  8796. closesocket(so.sock);
  8797. so.sock = INVALID_SOCKET;
  8798. continue;
  8799. }
  8800. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8801. int err = (int)ERRNO;
  8802. mg_cry(fc(ctx),
  8803. "call to getsockname failed %.*s: %d (%s)",
  8804. (int)vec.len,
  8805. vec.ptr,
  8806. err,
  8807. strerror(errno));
  8808. closesocket(so.sock);
  8809. so.sock = INVALID_SOCKET;
  8810. continue;
  8811. }
  8812. if ((ptr = (struct socket *)
  8813. mg_realloc(ctx->listening_sockets,
  8814. (ctx->num_listening_sockets + 1)
  8815. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8816. mg_cry(fc(ctx), "%s", "Out of memory");
  8817. closesocket(so.sock);
  8818. so.sock = INVALID_SOCKET;
  8819. continue;
  8820. }
  8821. if ((portPtr =
  8822. (in_port_t *)mg_realloc(ctx->listening_ports,
  8823. (ctx->num_listening_sockets + 1)
  8824. * sizeof(ctx->listening_ports[0])))
  8825. == NULL) {
  8826. mg_cry(fc(ctx), "%s", "Out of memory");
  8827. closesocket(so.sock);
  8828. so.sock = INVALID_SOCKET;
  8829. mg_free(ptr);
  8830. continue;
  8831. }
  8832. set_close_on_exec(so.sock, fc(ctx));
  8833. ctx->listening_sockets = ptr;
  8834. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8835. ctx->listening_ports = portPtr;
  8836. ctx->listening_ports[ctx->num_listening_sockets] =
  8837. ntohs(usa.sin.sin_port);
  8838. ctx->num_listening_sockets++;
  8839. portsOk++;
  8840. }
  8841. if (portsOk != portsTotal) {
  8842. close_all_listening_sockets(ctx);
  8843. portsOk = 0;
  8844. }
  8845. return portsOk;
  8846. }
  8847. static const char *
  8848. header_val(const struct mg_connection *conn, const char *header)
  8849. {
  8850. const char *header_value;
  8851. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8852. return "-";
  8853. } else {
  8854. return header_value;
  8855. }
  8856. }
  8857. static void
  8858. log_access(const struct mg_connection *conn)
  8859. {
  8860. const struct mg_request_info *ri;
  8861. FILE *fp;
  8862. char date[64], src_addr[IP_ADDR_STR_LEN];
  8863. struct tm *tm;
  8864. const char *referer;
  8865. const char *user_agent;
  8866. char buf[4096];
  8867. if (!conn || !conn->ctx) {
  8868. return;
  8869. }
  8870. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8871. ? NULL
  8872. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8873. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8874. return;
  8875. }
  8876. tm = localtime(&conn->conn_birth_time);
  8877. if (tm != NULL) {
  8878. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8879. } else {
  8880. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8881. date[sizeof(date) - 1] = '\0';
  8882. }
  8883. ri = &conn->request_info;
  8884. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8885. referer = header_val(conn, "Referer");
  8886. user_agent = header_val(conn, "User-Agent");
  8887. mg_snprintf(conn,
  8888. NULL, /* Ignore truncation in access log */
  8889. buf,
  8890. sizeof(buf),
  8891. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8892. src_addr,
  8893. ri->remote_user == NULL ? "-" : ri->remote_user,
  8894. date,
  8895. ri->request_method ? ri->request_method : "-",
  8896. ri->request_uri ? ri->request_uri : "-",
  8897. ri->query_string ? "?" : "",
  8898. ri->query_string ? ri->query_string : "",
  8899. ri->http_version,
  8900. conn->status_code,
  8901. conn->num_bytes_sent,
  8902. referer,
  8903. user_agent);
  8904. if (conn->ctx->callbacks.log_access) {
  8905. conn->ctx->callbacks.log_access(conn, buf);
  8906. }
  8907. if (fp) {
  8908. flockfile(fp);
  8909. fprintf(fp, "%s", buf);
  8910. fputc('\n', fp);
  8911. fflush(fp);
  8912. funlockfile(fp);
  8913. fclose(fp);
  8914. }
  8915. }
  8916. /* Verify given socket address against the ACL.
  8917. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  8918. */
  8919. static int
  8920. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8921. {
  8922. int allowed, flag;
  8923. uint32_t net, mask;
  8924. struct vec vec;
  8925. if (ctx) {
  8926. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8927. /* If any ACL is set, deny by default */
  8928. allowed = list == NULL ? '+' : '-';
  8929. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8930. flag = vec.ptr[0];
  8931. if ((flag != '+' && flag != '-')
  8932. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8933. mg_cry(fc(ctx),
  8934. "%s: subnet must be [+|-]x.x.x.x[/x]",
  8935. __func__);
  8936. return -1;
  8937. }
  8938. if (net == (remote_ip & mask)) {
  8939. allowed = flag;
  8940. }
  8941. }
  8942. return allowed == '+';
  8943. }
  8944. return -1;
  8945. }
  8946. #if !defined(_WIN32)
  8947. static int
  8948. set_uid_option(struct mg_context *ctx)
  8949. {
  8950. struct passwd *pw;
  8951. if (ctx) {
  8952. const char *uid = ctx->config[RUN_AS_USER];
  8953. int success = 0;
  8954. if (uid == NULL) {
  8955. success = 1;
  8956. } else {
  8957. if ((pw = getpwnam(uid)) == NULL) {
  8958. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8959. } else if (setgid(pw->pw_gid) == -1) {
  8960. mg_cry(fc(ctx),
  8961. "%s: setgid(%s): %s",
  8962. __func__,
  8963. uid,
  8964. strerror(errno));
  8965. } else if (setgroups(0, NULL)) {
  8966. mg_cry(fc(ctx),
  8967. "%s: setgroups(): %s",
  8968. __func__,
  8969. strerror(errno));
  8970. } else if (setuid(pw->pw_uid) == -1) {
  8971. mg_cry(fc(ctx),
  8972. "%s: setuid(%s): %s",
  8973. __func__,
  8974. uid,
  8975. strerror(errno));
  8976. } else {
  8977. success = 1;
  8978. }
  8979. }
  8980. return success;
  8981. }
  8982. return 0;
  8983. }
  8984. #endif /* !_WIN32 */
  8985. static void
  8986. tls_dtor(void *key)
  8987. {
  8988. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  8989. /* key == pthread_getspecific(sTlsKey); */
  8990. if (tls) {
  8991. if (tls->is_master == 2) {
  8992. tls->is_master = -3; /* Mark memory as dead */
  8993. mg_free(tls);
  8994. }
  8995. }
  8996. pthread_setspecific(sTlsKey, NULL);
  8997. }
  8998. #if !defined(NO_SSL)
  8999. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9000. static unsigned long
  9001. ssl_id_callback(void)
  9002. {
  9003. #ifdef _WIN32
  9004. return GetCurrentThreadId();
  9005. #else
  9006. #ifdef __clang__
  9007. #pragma clang diagnostic push
  9008. #pragma clang diagnostic ignored "-Wunreachable-code"
  9009. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9010. * or not, so one of the two conditions will be unreachable by construction.
  9011. * Unfortunately the C standard does not define a way to check this at
  9012. * compile time, since the #if preprocessor conditions can not use the sizeof
  9013. * operator as an argument. */
  9014. #endif
  9015. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9016. /* This is the problematic case for CRYPTO_set_id_callback:
  9017. * The OS pthread_t can not be cast to unsigned long. */
  9018. struct mg_workerTLS *tls =
  9019. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9020. if (tls == NULL) {
  9021. /* SSL called from an unknown thread: Create some thread index.
  9022. */
  9023. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9024. tls->is_master = -2; /* -2 means "3rd party thread" */
  9025. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9026. pthread_setspecific(sTlsKey, tls);
  9027. }
  9028. return tls->thread_idx;
  9029. } else {
  9030. return (unsigned long)pthread_self();
  9031. }
  9032. #ifdef __clang__
  9033. #pragma clang diagnostic pop
  9034. #endif
  9035. #endif
  9036. }
  9037. static pthread_mutex_t *ssl_mutexes;
  9038. static int
  9039. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9040. {
  9041. int ret, err;
  9042. if (!conn) {
  9043. return 0;
  9044. }
  9045. conn->ssl = SSL_new(s);
  9046. if (conn->ssl == NULL) {
  9047. return 0;
  9048. }
  9049. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9050. if (ret != 1) {
  9051. err = SSL_get_error(conn->ssl, ret);
  9052. (void)err; /* TODO: set some error message */
  9053. SSL_free(conn->ssl);
  9054. conn->ssl = NULL;
  9055. return 0;
  9056. }
  9057. ret = func(conn->ssl);
  9058. if (ret != 1) {
  9059. err = SSL_get_error(conn->ssl, ret);
  9060. (void)err; /* TODO: set some error message */
  9061. SSL_free(conn->ssl);
  9062. conn->ssl = NULL;
  9063. return 0;
  9064. }
  9065. return 1;
  9066. }
  9067. /* Return OpenSSL error message (from CRYPTO lib) */
  9068. static const char *
  9069. ssl_error(void)
  9070. {
  9071. unsigned long err;
  9072. err = ERR_get_error();
  9073. return err == 0 ? "" : ERR_error_string(err, NULL);
  9074. }
  9075. static void
  9076. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9077. {
  9078. (void)line;
  9079. (void)file;
  9080. if (mode & 1) {
  9081. /* 1 is CRYPTO_LOCK */
  9082. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9083. } else {
  9084. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9085. }
  9086. }
  9087. #if !defined(NO_SSL_DL)
  9088. static void *
  9089. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9090. {
  9091. union {
  9092. void *p;
  9093. void (*fp)(void);
  9094. } u;
  9095. void *dll_handle;
  9096. struct ssl_func *fp;
  9097. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9098. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9099. return NULL;
  9100. }
  9101. for (fp = sw; fp->name != NULL; fp++) {
  9102. #ifdef _WIN32
  9103. /* GetProcAddress() returns pointer to function */
  9104. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9105. #else
  9106. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9107. * pointers to function pointers. We need to use a union to make a
  9108. * cast. */
  9109. u.p = dlsym(dll_handle, fp->name);
  9110. #endif /* _WIN32 */
  9111. if (u.fp == NULL) {
  9112. mg_cry(fc(ctx),
  9113. "%s: %s: cannot find %s",
  9114. __func__,
  9115. dll_name,
  9116. fp->name);
  9117. dlclose(dll_handle);
  9118. return NULL;
  9119. } else {
  9120. fp->ptr = u.fp;
  9121. }
  9122. }
  9123. return dll_handle;
  9124. }
  9125. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9126. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9127. #endif /* NO_SSL_DL */
  9128. #if defined(SSL_ALREADY_INITIALIZED)
  9129. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9130. #else
  9131. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9132. #endif
  9133. static int
  9134. initialize_ssl(struct mg_context *ctx)
  9135. {
  9136. int i;
  9137. size_t size;
  9138. #if !defined(NO_SSL_DL)
  9139. if (!cryptolib_dll_handle) {
  9140. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9141. if (!cryptolib_dll_handle) {
  9142. return 0;
  9143. }
  9144. }
  9145. #endif /* NO_SSL_DL */
  9146. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9147. return 1;
  9148. }
  9149. /* Initialize locking callbacks, needed for thread safety.
  9150. * http://www.openssl.org/support/faq.html#PROG1
  9151. */
  9152. i = CRYPTO_num_locks();
  9153. if (i < 0) {
  9154. i = 0;
  9155. }
  9156. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9157. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9158. mg_cry(fc(ctx),
  9159. "%s: cannot allocate mutexes: %s",
  9160. __func__,
  9161. ssl_error());
  9162. return 0;
  9163. }
  9164. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9165. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9166. }
  9167. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9168. CRYPTO_set_id_callback(&ssl_id_callback);
  9169. return 1;
  9170. }
  9171. static int
  9172. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9173. {
  9174. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9175. mg_cry(fc(ctx),
  9176. "%s: cannot open certificate file %s: %s",
  9177. __func__,
  9178. pem,
  9179. ssl_error());
  9180. return 0;
  9181. }
  9182. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9183. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9184. mg_cry(fc(ctx),
  9185. "%s: cannot open private key file %s: %s",
  9186. __func__,
  9187. pem,
  9188. ssl_error());
  9189. return 0;
  9190. }
  9191. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9192. mg_cry(fc(ctx),
  9193. "%s: certificate and private key do not match: %s",
  9194. __func__,
  9195. pem);
  9196. return 0;
  9197. }
  9198. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9199. mg_cry(fc(ctx),
  9200. "%s: cannot use certificate chain file %s: %s",
  9201. __func__,
  9202. pem,
  9203. ssl_error());
  9204. return 0;
  9205. }
  9206. return 1;
  9207. }
  9208. static long
  9209. ssl_get_protocol(int version_id)
  9210. {
  9211. long ret = SSL_OP_ALL;
  9212. if (version_id > 0)
  9213. ret |= SSL_OP_NO_SSLv2;
  9214. if (version_id > 1)
  9215. ret |= SSL_OP_NO_SSLv3;
  9216. if (version_id > 2)
  9217. ret |= SSL_OP_NO_TLSv1;
  9218. if(version_id > 3)
  9219. ret |= SSL_OP_NO_TLSv1_1;
  9220. return ret;
  9221. }
  9222. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9223. static int
  9224. set_ssl_option(struct mg_context *ctx)
  9225. {
  9226. const char *pem;
  9227. int callback_ret;
  9228. int should_verify_peer;
  9229. const char *ca_path;
  9230. const char *ca_file;
  9231. int use_default_verify_paths;
  9232. int verify_depth;
  9233. time_t now_rt = time(NULL);
  9234. struct timespec now_mt;
  9235. md5_byte_t ssl_context_id[16];
  9236. md5_state_t md5state;
  9237. int protocol_ver;
  9238. /* If PEM file is not specified and the init_ssl callback
  9239. * is not specified, skip SSL initialization. */
  9240. if (!ctx) {
  9241. return 0;
  9242. }
  9243. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9244. && ctx->callbacks.init_ssl == NULL) {
  9245. return 1;
  9246. }
  9247. if (!initialize_ssl(ctx)) {
  9248. return 0;
  9249. }
  9250. #if !defined(NO_SSL_DL)
  9251. if (!ssllib_dll_handle) {
  9252. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9253. if (!ssllib_dll_handle) {
  9254. return 0;
  9255. }
  9256. }
  9257. #endif /* NO_SSL_DL */
  9258. /* Initialize SSL library */
  9259. SSL_library_init();
  9260. SSL_load_error_strings();
  9261. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9262. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9263. return 0;
  9264. }
  9265. SSL_CTX_clear_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2 |
  9266. SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
  9267. SSL_OP_NO_TLSv1_1);
  9268. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9269. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9270. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9271. /* If a callback has been specified, call it. */
  9272. callback_ret =
  9273. (ctx->callbacks.init_ssl == NULL)
  9274. ? 0
  9275. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9276. /* If callback returns 0, civetweb sets up the SSL certificate.
  9277. * If it returns 1, civetweb assumes the calback already did this.
  9278. * If it returns -1, initializing ssl fails. */
  9279. if (callback_ret < 0) {
  9280. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9281. return 0;
  9282. }
  9283. if (callback_ret > 0) {
  9284. if (pem != NULL) {
  9285. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9286. }
  9287. return 1;
  9288. }
  9289. /* Use some UID as session context ID. */
  9290. md5_init(&md5state);
  9291. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9292. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9293. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9294. md5_append(&md5state,
  9295. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9296. strlen(ctx->config[LISTENING_PORTS]));
  9297. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9298. md5_finish(&md5state, ssl_context_id);
  9299. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9300. (const unsigned char *)&ssl_context_id,
  9301. sizeof(ssl_context_id));
  9302. if (pem != NULL) {
  9303. if (!ssl_use_pem_file(ctx, pem)) {
  9304. return 0;
  9305. }
  9306. }
  9307. should_verify_peer =
  9308. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9309. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9310. use_default_verify_paths =
  9311. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9312. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9313. if (should_verify_peer) {
  9314. ca_path = ctx->config[SSL_CA_PATH];
  9315. ca_file = ctx->config[SSL_CA_FILE];
  9316. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9317. != 1) {
  9318. mg_cry(fc(ctx),
  9319. "SSL_CTX_load_verify_locations error: %s "
  9320. "ssl_verify_peer requires setting "
  9321. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9322. "present in "
  9323. "the .conf file?",
  9324. ssl_error());
  9325. return 0;
  9326. }
  9327. SSL_CTX_set_verify(ctx->ssl_ctx,
  9328. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9329. NULL);
  9330. if (use_default_verify_paths
  9331. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9332. mg_cry(fc(ctx),
  9333. "SSL_CTX_set_default_verify_paths error: %s",
  9334. ssl_error());
  9335. return 0;
  9336. }
  9337. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9338. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9339. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9340. }
  9341. }
  9342. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9343. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST]) != 1) {
  9344. mg_cry(fc(ctx),
  9345. "SSL_CTX_set_cipher_list error: %s",
  9346. ssl_error());
  9347. }
  9348. }
  9349. return 1;
  9350. }
  9351. static void
  9352. uninitialize_ssl(struct mg_context *ctx)
  9353. {
  9354. int i;
  9355. (void)ctx;
  9356. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9357. CRYPTO_set_locking_callback(NULL);
  9358. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9359. pthread_mutex_destroy(&ssl_mutexes[i]);
  9360. }
  9361. CRYPTO_set_locking_callback(NULL);
  9362. CRYPTO_set_id_callback(NULL);
  9363. }
  9364. }
  9365. #endif /* !NO_SSL */
  9366. static int
  9367. set_gpass_option(struct mg_context *ctx)
  9368. {
  9369. if (ctx) {
  9370. struct file file = STRUCT_FILE_INITIALIZER;
  9371. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9372. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9373. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9374. return 0;
  9375. }
  9376. return 1;
  9377. }
  9378. return 0;
  9379. }
  9380. static int
  9381. set_acl_option(struct mg_context *ctx)
  9382. {
  9383. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9384. }
  9385. static void
  9386. reset_per_request_attributes(struct mg_connection *conn)
  9387. {
  9388. if (!conn) {
  9389. return;
  9390. }
  9391. conn->path_info = NULL;
  9392. conn->num_bytes_sent = conn->consumed_content = 0;
  9393. conn->status_code = -1;
  9394. conn->is_chunked = 0;
  9395. conn->must_close = conn->request_len = conn->throttle = 0;
  9396. conn->request_info.content_length = -1;
  9397. conn->request_info.remote_user = NULL;
  9398. conn->request_info.request_method = NULL;
  9399. conn->request_info.request_uri = NULL;
  9400. conn->request_info.local_uri = NULL;
  9401. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9402. * local_uri and request_uri */
  9403. conn->request_info.http_version = NULL;
  9404. conn->request_info.num_headers = 0;
  9405. conn->data_len = 0;
  9406. conn->chunk_remainder = 0;
  9407. conn->internal_error = 0;
  9408. }
  9409. static int
  9410. set_sock_timeout(SOCKET sock, int milliseconds)
  9411. {
  9412. int r1, r2;
  9413. #ifdef _WIN32
  9414. /* Windows specific */
  9415. DWORD tv = (DWORD)milliseconds;
  9416. #else
  9417. /* Linux, ... (not Windows) */
  9418. struct timeval tv;
  9419. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9420. * max. time waiting for the acknowledged of TCP data before the connection
  9421. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9422. * If this option is not set, the default timeout of 20-30 minutes is used.
  9423. */
  9424. /* #define TCP_USER_TIMEOUT (18) */
  9425. #if defined(TCP_USER_TIMEOUT)
  9426. unsigned int uto = (unsigned int)milliseconds;
  9427. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9428. #endif
  9429. memset(&tv, 0, sizeof(tv));
  9430. tv.tv_sec = milliseconds / 1000;
  9431. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9432. #endif /* _WIN32 */
  9433. r1 = setsockopt(
  9434. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9435. r2 = setsockopt(
  9436. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9437. return r1 || r2;
  9438. }
  9439. static void
  9440. close_socket_gracefully(struct mg_connection *conn)
  9441. {
  9442. #if defined(_WIN32)
  9443. char buf[MG_BUF_LEN];
  9444. int n;
  9445. #endif
  9446. struct linger linger;
  9447. if (!conn) {
  9448. return;
  9449. }
  9450. /* Set linger option to avoid socket hanging out after close. This
  9451. * prevent
  9452. * ephemeral port exhaust problem under high QPS. */
  9453. linger.l_onoff = 1;
  9454. linger.l_linger = 1;
  9455. if (setsockopt(conn->client.sock,
  9456. SOL_SOCKET,
  9457. SO_LINGER,
  9458. (char *)&linger,
  9459. sizeof(linger)) != 0) {
  9460. mg_cry(conn,
  9461. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9462. __func__,
  9463. strerror(ERRNO));
  9464. }
  9465. /* Send FIN to the client */
  9466. shutdown(conn->client.sock, SHUT_WR);
  9467. set_non_blocking_mode(conn->client.sock);
  9468. #if defined(_WIN32)
  9469. /* Read and discard pending incoming data. If we do not do that and
  9470. * close
  9471. * the socket, the data in the send buffer may be discarded. This
  9472. * behaviour is seen on Windows, when client keeps sending data
  9473. * when server decides to close the connection; then when client
  9474. * does recv() it gets no data back. */
  9475. do {
  9476. n = pull(
  9477. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9478. } while (n > 0);
  9479. #endif
  9480. /* Now we know that our FIN is ACK-ed, safe to close */
  9481. closesocket(conn->client.sock);
  9482. conn->client.sock = INVALID_SOCKET;
  9483. }
  9484. static void
  9485. close_connection(struct mg_connection *conn)
  9486. {
  9487. if (!conn || !conn->ctx) {
  9488. return;
  9489. }
  9490. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9491. if (conn->lua_websocket_state) {
  9492. lua_websocket_close(conn, conn->lua_websocket_state);
  9493. conn->lua_websocket_state = NULL;
  9494. }
  9495. #endif
  9496. /* call the connection_close callback if assigned */
  9497. if ((conn->ctx->callbacks.connection_close != NULL)
  9498. && (conn->ctx->context_type == 1)) {
  9499. conn->ctx->callbacks.connection_close(conn);
  9500. }
  9501. mg_lock_connection(conn);
  9502. conn->must_close = 1;
  9503. #ifndef NO_SSL
  9504. if (conn->ssl != NULL) {
  9505. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9506. */
  9507. SSL_shutdown(conn->ssl);
  9508. SSL_free(conn->ssl);
  9509. conn->ssl = NULL;
  9510. }
  9511. #endif
  9512. if (conn->client.sock != INVALID_SOCKET) {
  9513. close_socket_gracefully(conn);
  9514. conn->client.sock = INVALID_SOCKET;
  9515. }
  9516. mg_unlock_connection(conn);
  9517. }
  9518. void
  9519. mg_close_connection(struct mg_connection *conn)
  9520. {
  9521. struct mg_context *client_ctx = NULL;
  9522. unsigned int i;
  9523. if (conn == NULL) {
  9524. return;
  9525. }
  9526. if (conn->ctx->context_type == 2) {
  9527. client_ctx = conn->ctx;
  9528. /* client context: loops must end */
  9529. conn->ctx->stop_flag = 1;
  9530. }
  9531. #ifndef NO_SSL
  9532. if (conn->client_ssl_ctx != NULL) {
  9533. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9534. }
  9535. #endif
  9536. close_connection(conn);
  9537. if (client_ctx != NULL) {
  9538. /* join worker thread and free context */
  9539. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9540. if (client_ctx->workerthreadids[i] != 0) {
  9541. mg_join_thread(client_ctx->workerthreadids[i]);
  9542. }
  9543. }
  9544. mg_free(client_ctx->workerthreadids);
  9545. mg_free(client_ctx);
  9546. }
  9547. (void)pthread_mutex_destroy(&conn->mutex);
  9548. mg_free(conn);
  9549. }
  9550. static struct mg_connection *
  9551. mg_connect_client_impl(const struct mg_client_options *client_options,
  9552. int use_ssl,
  9553. char *ebuf,
  9554. size_t ebuf_len)
  9555. {
  9556. static struct mg_context fake_ctx;
  9557. struct mg_connection *conn = NULL;
  9558. SOCKET sock;
  9559. union usa sa;
  9560. if (!connect_socket(&fake_ctx,
  9561. client_options->host,
  9562. client_options->port,
  9563. use_ssl,
  9564. ebuf,
  9565. ebuf_len,
  9566. &sock,
  9567. &sa)) {
  9568. ;
  9569. } else if ((conn = (struct mg_connection *)
  9570. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9571. mg_snprintf(NULL,
  9572. NULL, /* No truncation check for ebuf */
  9573. ebuf,
  9574. ebuf_len,
  9575. "calloc(): %s",
  9576. strerror(ERRNO));
  9577. closesocket(sock);
  9578. #ifndef NO_SSL
  9579. } else if (use_ssl
  9580. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9581. == NULL) {
  9582. mg_snprintf(NULL,
  9583. NULL, /* No truncation check for ebuf */
  9584. ebuf,
  9585. ebuf_len,
  9586. "SSL_CTX_new error");
  9587. closesocket(sock);
  9588. mg_free(conn);
  9589. conn = NULL;
  9590. #endif /* NO_SSL */
  9591. } else {
  9592. #ifdef USE_IPV6
  9593. socklen_t len = (sa.sa.sa_family == AF_INET)
  9594. ? sizeof(conn->client.rsa.sin)
  9595. : sizeof(conn->client.rsa.sin6);
  9596. struct sockaddr *psa =
  9597. (sa.sa.sa_family == AF_INET)
  9598. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9599. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9600. #else
  9601. socklen_t len = sizeof(conn->client.rsa.sin);
  9602. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9603. #endif
  9604. conn->buf_size = MAX_REQUEST_SIZE;
  9605. conn->buf = (char *)(conn + 1);
  9606. conn->ctx = &fake_ctx;
  9607. conn->client.sock = sock;
  9608. conn->client.lsa = sa;
  9609. if (getsockname(sock, psa, &len) != 0) {
  9610. mg_cry(conn,
  9611. "%s: getsockname() failed: %s",
  9612. __func__,
  9613. strerror(ERRNO));
  9614. }
  9615. conn->client.is_ssl = use_ssl ? 1 : 0;
  9616. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9617. #ifndef NO_SSL
  9618. if (use_ssl) {
  9619. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9620. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9621. SSL_CTX_set_verify call is needed to switch off server
  9622. * certificate checking, which is off by default in OpenSSL and
  9623. on
  9624. * in yaSSL. */
  9625. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9626. // SSL_VERIFY_PEER,
  9627. // verify_ssl_server);
  9628. if (client_options->client_cert) {
  9629. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9630. mg_snprintf(NULL,
  9631. NULL, /* No truncation check for ebuf */
  9632. ebuf,
  9633. ebuf_len,
  9634. "Can not use SSL client certificate");
  9635. SSL_CTX_free(conn->client_ssl_ctx);
  9636. closesocket(sock);
  9637. mg_free(conn);
  9638. conn = NULL;
  9639. }
  9640. }
  9641. if (client_options->server_cert) {
  9642. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9643. client_options->server_cert,
  9644. NULL);
  9645. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9646. } else {
  9647. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9648. }
  9649. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9650. mg_snprintf(NULL,
  9651. NULL, /* No truncation check for ebuf */
  9652. ebuf,
  9653. ebuf_len,
  9654. "SSL connection error");
  9655. SSL_CTX_free(conn->client_ssl_ctx);
  9656. closesocket(sock);
  9657. mg_free(conn);
  9658. conn = NULL;
  9659. }
  9660. }
  9661. #endif
  9662. }
  9663. return conn;
  9664. }
  9665. CIVETWEB_API struct mg_connection *
  9666. mg_connect_client_secure(const struct mg_client_options *client_options,
  9667. char *error_buffer,
  9668. size_t error_buffer_size)
  9669. {
  9670. return mg_connect_client_impl(client_options,
  9671. 1,
  9672. error_buffer,
  9673. error_buffer_size);
  9674. }
  9675. struct mg_connection *
  9676. mg_connect_client(const char *host,
  9677. int port,
  9678. int use_ssl,
  9679. char *error_buffer,
  9680. size_t error_buffer_size)
  9681. {
  9682. struct mg_client_options opts;
  9683. memset(&opts, 0, sizeof(opts));
  9684. opts.host = host;
  9685. opts.port = port;
  9686. return mg_connect_client_impl(&opts,
  9687. use_ssl,
  9688. error_buffer,
  9689. error_buffer_size);
  9690. }
  9691. static const struct {
  9692. const char *proto;
  9693. size_t proto_len;
  9694. unsigned default_port;
  9695. } abs_uri_protocols[] = {{"http://", 7, 80},
  9696. {"https://", 8, 443},
  9697. {"ws://", 5, 80},
  9698. {"wss://", 6, 443},
  9699. {NULL, 0, 0}};
  9700. /* Check if the uri is valid.
  9701. * return 0 for invalid uri,
  9702. * return 1 for *,
  9703. * return 2 for relative uri,
  9704. * return 3 for absolute uri without port,
  9705. * return 4 for absolute uri with port */
  9706. static int
  9707. get_uri_type(const char *uri)
  9708. {
  9709. int i;
  9710. char *hostend, *portbegin, *portend;
  9711. unsigned long port;
  9712. /* According to the HTTP standard
  9713. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9714. * URI can be an asterisk (*) or should start with slash (relative uri),
  9715. * or it should start with the protocol (absolute uri). */
  9716. if (uri[0] == '*' && uri[1] == '\0') {
  9717. /* asterisk */
  9718. return 1;
  9719. }
  9720. if (uri[0] == '/') {
  9721. /* relative uri */
  9722. return 2;
  9723. }
  9724. /* It could be an absolute uri: */
  9725. /* This function only checks if the uri is valid, not if it is
  9726. * addressing the current server. So civetweb can also be used
  9727. * as a proxy server. */
  9728. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9729. if (mg_strncasecmp(uri,
  9730. abs_uri_protocols[i].proto,
  9731. abs_uri_protocols[i].proto_len) == 0) {
  9732. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9733. if (!hostend) {
  9734. return 0;
  9735. }
  9736. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9737. if (!portbegin) {
  9738. return 3;
  9739. }
  9740. port = strtoul(portbegin + 1, &portend, 10);
  9741. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9742. return 0;
  9743. }
  9744. return 4;
  9745. }
  9746. }
  9747. return 0;
  9748. }
  9749. /* Return NULL or the relative uri at the current server */
  9750. static const char *
  9751. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9752. {
  9753. const char *domain;
  9754. size_t domain_len;
  9755. unsigned long port = 0;
  9756. int i;
  9757. char *hostend = NULL;
  9758. char *portbegin, *portend;
  9759. /* DNS is case insensitive, so use case insensitive string compare here
  9760. */
  9761. domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9762. if (!domain) {
  9763. return 0;
  9764. }
  9765. domain_len = strlen(domain);
  9766. if (!domain_len) {
  9767. return 0;
  9768. }
  9769. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9770. if (mg_strncasecmp(uri,
  9771. abs_uri_protocols[i].proto,
  9772. abs_uri_protocols[i].proto_len) == 0) {
  9773. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9774. if (!hostend) {
  9775. return 0;
  9776. }
  9777. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9778. if (!portbegin) {
  9779. port = abs_uri_protocols[i].default_port;
  9780. } else {
  9781. port = strtoul(portbegin + 1, &portend, 10);
  9782. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9783. return 0;
  9784. }
  9785. }
  9786. /* protocol found, port set */
  9787. break;
  9788. }
  9789. }
  9790. if (!port) {
  9791. /* port remains 0 if the protocol is not found */
  9792. return 0;
  9793. }
  9794. #if defined(USE_IPV6)
  9795. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9796. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9797. return 0;
  9798. }
  9799. } else
  9800. #endif
  9801. {
  9802. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9803. return 0;
  9804. }
  9805. }
  9806. return hostend;
  9807. }
  9808. static int
  9809. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9810. {
  9811. const char *cl;
  9812. if (ebuf_len > 0) {
  9813. ebuf[0] = '\0';
  9814. }
  9815. *err = 0;
  9816. reset_per_request_attributes(conn);
  9817. if (!conn) {
  9818. mg_snprintf(conn,
  9819. NULL, /* No truncation check for ebuf */
  9820. ebuf,
  9821. ebuf_len,
  9822. "%s",
  9823. "Internal error");
  9824. *err = 500;
  9825. return 0;
  9826. }
  9827. /* Set the time the request was received. This value should be used for
  9828. * timeouts. */
  9829. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  9830. conn->request_len =
  9831. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  9832. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  9833. */
  9834. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  9835. mg_snprintf(conn,
  9836. NULL, /* No truncation check for ebuf */
  9837. ebuf,
  9838. ebuf_len,
  9839. "%s",
  9840. "Invalid request size");
  9841. *err = 500;
  9842. return 0;
  9843. }
  9844. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  9845. mg_snprintf(conn,
  9846. NULL, /* No truncation check for ebuf */
  9847. ebuf,
  9848. ebuf_len,
  9849. "%s",
  9850. "Request Too Large");
  9851. *err = 413;
  9852. return 0;
  9853. } else if (conn->request_len <= 0) {
  9854. if (conn->data_len > 0) {
  9855. mg_snprintf(conn,
  9856. NULL, /* No truncation check for ebuf */
  9857. ebuf,
  9858. ebuf_len,
  9859. "%s",
  9860. "Client sent malformed request");
  9861. *err = 400;
  9862. } else {
  9863. /* Server did not send anything -> just close the connection */
  9864. conn->must_close = 1;
  9865. mg_snprintf(conn,
  9866. NULL, /* No truncation check for ebuf */
  9867. ebuf,
  9868. ebuf_len,
  9869. "%s",
  9870. "Client did not send a request");
  9871. *err = 0;
  9872. }
  9873. return 0;
  9874. } else if (parse_http_message(conn->buf,
  9875. conn->buf_size,
  9876. &conn->request_info) <= 0) {
  9877. mg_snprintf(conn,
  9878. NULL, /* No truncation check for ebuf */
  9879. ebuf,
  9880. ebuf_len,
  9881. "%s",
  9882. "Bad Request");
  9883. *err = 400;
  9884. return 0;
  9885. } else {
  9886. /* Message is a valid request or response */
  9887. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9888. /* Request/response has content length set */
  9889. char *endptr = NULL;
  9890. conn->content_len = strtoll(cl, &endptr, 10);
  9891. if (endptr == cl) {
  9892. mg_snprintf(conn,
  9893. NULL, /* No truncation check for ebuf */
  9894. ebuf,
  9895. ebuf_len,
  9896. "%s",
  9897. "Bad Request");
  9898. *err = 411;
  9899. return 0;
  9900. }
  9901. /* Publish the content length back to the request info. */
  9902. conn->request_info.content_length = conn->content_len;
  9903. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  9904. != NULL
  9905. && strcmp(cl, "chunked") == 0) {
  9906. conn->is_chunked = 1;
  9907. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  9908. || !mg_strcasecmp(conn->request_info.request_method,
  9909. "PUT")) {
  9910. /* POST or PUT request without content length set */
  9911. conn->content_len = -1;
  9912. } else if (!mg_strncasecmp(conn->request_info.request_method,
  9913. "HTTP/",
  9914. 5)) {
  9915. /* Response without content length set */
  9916. conn->content_len = -1;
  9917. } else {
  9918. /* Other request */
  9919. conn->content_len = 0;
  9920. }
  9921. }
  9922. return 1;
  9923. }
  9924. int
  9925. mg_get_response(struct mg_connection *conn,
  9926. char *ebuf,
  9927. size_t ebuf_len,
  9928. int timeout)
  9929. {
  9930. if (conn) {
  9931. /* Implementation of API function for HTTP clients */
  9932. int err, ret;
  9933. struct mg_context *octx = conn->ctx;
  9934. struct mg_context rctx = *(conn->ctx);
  9935. char txt[32]; /* will not overflow */
  9936. if (timeout >= 0) {
  9937. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  9938. rctx.config[REQUEST_TIMEOUT] = txt;
  9939. set_sock_timeout(conn->client.sock, timeout);
  9940. } else {
  9941. rctx.config[REQUEST_TIMEOUT] = NULL;
  9942. }
  9943. conn->ctx = &rctx;
  9944. ret = getreq(conn, ebuf, ebuf_len, &err);
  9945. conn->ctx = octx;
  9946. /* TODO: 1) uri is deprecated;
  9947. * 2) here, ri.uri is the http response code */
  9948. conn->request_info.uri = conn->request_info.request_uri;
  9949. /* TODO (mid): Define proper return values - maybe return length?
  9950. * For the first test use <0 for error and >0 for OK */
  9951. return (ret == 0) ? -1 : +1;
  9952. }
  9953. return -1;
  9954. }
  9955. struct mg_connection *
  9956. mg_download(const char *host,
  9957. int port,
  9958. int use_ssl,
  9959. char *ebuf,
  9960. size_t ebuf_len,
  9961. const char *fmt,
  9962. ...)
  9963. {
  9964. struct mg_connection *conn;
  9965. va_list ap;
  9966. int i;
  9967. int reqerr;
  9968. va_start(ap, fmt);
  9969. ebuf[0] = '\0';
  9970. /* open a connection */
  9971. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  9972. if (conn != NULL) {
  9973. i = mg_vprintf(conn, fmt, ap);
  9974. if (i <= 0) {
  9975. mg_snprintf(conn,
  9976. NULL, /* No truncation check for ebuf */
  9977. ebuf,
  9978. ebuf_len,
  9979. "%s",
  9980. "Error sending request");
  9981. } else {
  9982. getreq(conn, ebuf, ebuf_len, &reqerr);
  9983. /* TODO: 1) uri is deprecated;
  9984. * 2) here, ri.uri is the http response code */
  9985. conn->request_info.uri = conn->request_info.request_uri;
  9986. }
  9987. }
  9988. /* if an error occured, close the connection */
  9989. if (ebuf[0] != '\0' && conn != NULL) {
  9990. mg_close_connection(conn);
  9991. conn = NULL;
  9992. }
  9993. va_end(ap);
  9994. return conn;
  9995. }
  9996. struct websocket_client_thread_data {
  9997. struct mg_connection *conn;
  9998. mg_websocket_data_handler data_handler;
  9999. mg_websocket_close_handler close_handler;
  10000. void *callback_data;
  10001. };
  10002. #if defined(USE_WEBSOCKET)
  10003. #ifdef _WIN32
  10004. static unsigned __stdcall websocket_client_thread(void *data)
  10005. #else
  10006. static void *
  10007. websocket_client_thread(void *data)
  10008. #endif
  10009. {
  10010. struct websocket_client_thread_data *cdata =
  10011. (struct websocket_client_thread_data *)data;
  10012. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10013. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10014. if (cdata->close_handler != NULL) {
  10015. cdata->close_handler(cdata->conn, cdata->callback_data);
  10016. }
  10017. mg_free((void *)cdata);
  10018. #ifdef _WIN32
  10019. return 0;
  10020. #else
  10021. return NULL;
  10022. #endif
  10023. }
  10024. #endif
  10025. struct mg_connection *
  10026. mg_connect_websocket_client(const char *host,
  10027. int port,
  10028. int use_ssl,
  10029. char *error_buffer,
  10030. size_t error_buffer_size,
  10031. const char *path,
  10032. const char *origin,
  10033. mg_websocket_data_handler data_func,
  10034. mg_websocket_close_handler close_func,
  10035. void *user_data)
  10036. {
  10037. struct mg_connection *conn = NULL;
  10038. #if defined(USE_WEBSOCKET)
  10039. struct mg_context *newctx = NULL;
  10040. struct websocket_client_thread_data *thread_data;
  10041. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10042. static const char *handshake_req;
  10043. if (origin != NULL) {
  10044. handshake_req = "GET %s HTTP/1.1\r\n"
  10045. "Host: %s\r\n"
  10046. "Upgrade: websocket\r\n"
  10047. "Connection: Upgrade\r\n"
  10048. "Sec-WebSocket-Key: %s\r\n"
  10049. "Sec-WebSocket-Version: 13\r\n"
  10050. "Origin: %s\r\n"
  10051. "\r\n";
  10052. } else {
  10053. handshake_req = "GET %s HTTP/1.1\r\n"
  10054. "Host: %s\r\n"
  10055. "Upgrade: websocket\r\n"
  10056. "Connection: Upgrade\r\n"
  10057. "Sec-WebSocket-Key: %s\r\n"
  10058. "Sec-WebSocket-Version: 13\r\n"
  10059. "\r\n";
  10060. }
  10061. /* Establish the client connection and request upgrade */
  10062. conn = mg_download(host,
  10063. port,
  10064. use_ssl,
  10065. error_buffer,
  10066. error_buffer_size,
  10067. handshake_req,
  10068. path,
  10069. host,
  10070. magic,
  10071. origin);
  10072. /* Connection object will be null if something goes wrong */
  10073. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10074. if (!*error_buffer) {
  10075. /* if there is a connection, but it did not return 101,
  10076. * error_buffer is not yet set */
  10077. mg_snprintf(conn,
  10078. NULL, /* No truncation check for ebuf */
  10079. error_buffer,
  10080. error_buffer_size,
  10081. "Unexpected server reply");
  10082. }
  10083. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10084. if (conn != NULL) {
  10085. mg_free(conn);
  10086. conn = NULL;
  10087. }
  10088. return conn;
  10089. }
  10090. /* For client connections, mg_context is fake. Since we need to set a
  10091. * callback function, we need to create a copy and modify it. */
  10092. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10093. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10094. newctx->user_data = user_data;
  10095. newctx->context_type = 2; /* client context type */
  10096. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10097. newctx->workerthreadids =
  10098. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10099. conn->ctx = newctx;
  10100. thread_data = (struct websocket_client_thread_data *)
  10101. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10102. thread_data->conn = conn;
  10103. thread_data->data_handler = data_func;
  10104. thread_data->close_handler = close_func;
  10105. thread_data->callback_data = NULL;
  10106. /* Start a thread to read the websocket client connection
  10107. * This thread will automatically stop when mg_disconnect is
  10108. * called on the client connection */
  10109. if (mg_start_thread_with_id(websocket_client_thread,
  10110. (void *)thread_data,
  10111. newctx->workerthreadids) != 0) {
  10112. mg_free((void *)thread_data);
  10113. mg_free((void *)newctx->workerthreadids);
  10114. mg_free((void *)newctx);
  10115. mg_free((void *)conn);
  10116. conn = NULL;
  10117. DEBUG_TRACE("%s",
  10118. "Websocket client connect thread could not be started\r\n");
  10119. }
  10120. #else
  10121. /* Appease "unused parameter" warnings */
  10122. (void)host;
  10123. (void)port;
  10124. (void)use_ssl;
  10125. (void)error_buffer;
  10126. (void)error_buffer_size;
  10127. (void)path;
  10128. (void)origin;
  10129. (void)user_data;
  10130. (void)data_func;
  10131. (void)close_func;
  10132. #endif
  10133. return conn;
  10134. }
  10135. static void
  10136. process_new_connection(struct mg_connection *conn)
  10137. {
  10138. if (conn && conn->ctx) {
  10139. struct mg_request_info *ri = &conn->request_info;
  10140. int keep_alive_enabled, keep_alive, discard_len;
  10141. char ebuf[100];
  10142. const char *hostend;
  10143. int reqerr, uri_type;
  10144. keep_alive_enabled =
  10145. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10146. /* Important: on new connection, reset the receiving buffer. Credit
  10147. * goes to crule42. */
  10148. conn->data_len = 0;
  10149. do {
  10150. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10151. /* The request sent by the client could not be understood by
  10152. * the server, or it was incomplete or a timeout. Send an
  10153. * error message and close the connection. */
  10154. if (reqerr > 0) {
  10155. /*assert(ebuf[0] != '\0');*/
  10156. send_http_error(conn, reqerr, "%s", ebuf);
  10157. }
  10158. } else if (strcmp(ri->http_version, "1.0")
  10159. && strcmp(ri->http_version, "1.1")) {
  10160. mg_snprintf(conn,
  10161. NULL, /* No truncation check for ebuf */
  10162. ebuf,
  10163. sizeof(ebuf),
  10164. "Bad HTTP version: [%s]",
  10165. ri->http_version);
  10166. send_http_error(conn, 505, "%s", ebuf);
  10167. }
  10168. if (ebuf[0] == '\0') {
  10169. uri_type = get_uri_type(conn->request_info.request_uri);
  10170. switch (uri_type) {
  10171. case 1:
  10172. /* Asterisk */
  10173. conn->request_info.local_uri = NULL;
  10174. break;
  10175. case 2:
  10176. /* relative uri */
  10177. conn->request_info.local_uri =
  10178. conn->request_info.request_uri;
  10179. break;
  10180. case 3:
  10181. case 4:
  10182. /* absolute uri (with/without port) */
  10183. hostend = get_rel_url_at_current_server(
  10184. conn->request_info.request_uri, conn);
  10185. if (hostend) {
  10186. conn->request_info.local_uri = hostend;
  10187. } else {
  10188. conn->request_info.local_uri = NULL;
  10189. }
  10190. break;
  10191. default:
  10192. mg_snprintf(conn,
  10193. NULL, /* No truncation check for ebuf */
  10194. ebuf,
  10195. sizeof(ebuf),
  10196. "Invalid URI: [%s]",
  10197. ri->request_uri);
  10198. send_http_error(conn, 400, "%s", ebuf);
  10199. break;
  10200. }
  10201. /* TODO: cleanup uri, local_uri and request_uri */
  10202. conn->request_info.uri = conn->request_info.local_uri;
  10203. }
  10204. if (ebuf[0] == '\0') {
  10205. handle_request(conn);
  10206. if (conn->ctx->callbacks.end_request != NULL) {
  10207. conn->ctx->callbacks.end_request(conn, conn->status_code);
  10208. }
  10209. log_access(conn);
  10210. } else {
  10211. conn->must_close = 1;
  10212. }
  10213. if (ri->remote_user != NULL) {
  10214. mg_free((void *)ri->remote_user);
  10215. /* Important! When having connections with and without auth
  10216. * would cause double free and then crash */
  10217. ri->remote_user = NULL;
  10218. }
  10219. /* NOTE(lsm): order is important here. should_keep_alive() call
  10220. * is
  10221. * using parsed request, which will be invalid after memmove's
  10222. * below.
  10223. * Therefore, memorize should_keep_alive() result now for later
  10224. * use
  10225. * in loop exit condition. */
  10226. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10227. && conn->content_len >= 0 && should_keep_alive(conn);
  10228. /* Discard all buffered data for this request */
  10229. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10230. && conn->request_len + conn->content_len
  10231. < (int64_t)conn->data_len
  10232. ? (int)(conn->request_len + conn->content_len)
  10233. : conn->data_len;
  10234. /*assert(discard_len >= 0);*/
  10235. if (discard_len < 0)
  10236. break;
  10237. conn->data_len -= discard_len;
  10238. if (conn->data_len > 0) {
  10239. memmove(conn->buf,
  10240. conn->buf + discard_len,
  10241. (size_t)conn->data_len);
  10242. }
  10243. /* assert(conn->data_len >= 0); */
  10244. /* assert(conn->data_len <= conn->buf_size); */
  10245. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10246. break;
  10247. }
  10248. } while (keep_alive);
  10249. }
  10250. }
  10251. /* Worker threads take accepted socket from the queue */
  10252. static int
  10253. consume_socket(struct mg_context *ctx, struct socket *sp)
  10254. {
  10255. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10256. if (!ctx) {
  10257. return 0;
  10258. }
  10259. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10260. DEBUG_TRACE("%s", "going idle");
  10261. /* If the queue is empty, wait. We're idle at this point. */
  10262. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10263. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10264. }
  10265. /* If we're stopping, sq_head may be equal to sq_tail. */
  10266. if (ctx->sq_head > ctx->sq_tail) {
  10267. /* Copy socket from the queue and increment tail */
  10268. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10269. ctx->sq_tail++;
  10270. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10271. /* Wrap pointers if needed */
  10272. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10273. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10274. ctx->sq_head -= QUEUE_SIZE(ctx);
  10275. }
  10276. }
  10277. (void)pthread_cond_signal(&ctx->sq_empty);
  10278. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10279. return !ctx->stop_flag;
  10280. #undef QUEUE_SIZE
  10281. }
  10282. static void *
  10283. worker_thread_run(void *thread_func_param)
  10284. {
  10285. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10286. struct mg_connection *conn;
  10287. struct mg_workerTLS tls;
  10288. #if defined(MG_LEGACY_INTERFACE)
  10289. uint32_t addr;
  10290. #endif
  10291. mg_set_thread_name("worker");
  10292. tls.is_master = 0;
  10293. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10294. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10295. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10296. #endif
  10297. conn =
  10298. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10299. if (conn == NULL) {
  10300. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10301. } else {
  10302. pthread_setspecific(sTlsKey, &tls);
  10303. conn->buf_size = MAX_REQUEST_SIZE;
  10304. conn->buf = (char *)(conn + 1);
  10305. conn->ctx = ctx;
  10306. conn->request_info.user_data = ctx->user_data;
  10307. /* Allocate a mutex for this connection to allow communication both
  10308. * within the request handler and from elsewhere in the application
  10309. */
  10310. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10311. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10312. * signal sq_empty condvar to wake up the master waiting in
  10313. * produce_socket() */
  10314. while (consume_socket(ctx, &conn->client)) {
  10315. conn->conn_birth_time = time(NULL);
  10316. /* Fill in IP, port info early so even if SSL setup below fails,
  10317. * error handler would have the corresponding info.
  10318. * Thanks to Johannes Winkelmann for the patch.
  10319. */
  10320. #if defined(USE_IPV6)
  10321. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10322. conn->request_info.remote_port =
  10323. ntohs(conn->client.rsa.sin6.sin6_port);
  10324. } else
  10325. #endif
  10326. {
  10327. conn->request_info.remote_port =
  10328. ntohs(conn->client.rsa.sin.sin_port);
  10329. }
  10330. sockaddr_to_string(conn->request_info.remote_addr,
  10331. sizeof(conn->request_info.remote_addr),
  10332. &conn->client.rsa);
  10333. #if defined(MG_LEGACY_INTERFACE)
  10334. /* This legacy interface only works for the IPv4 case */
  10335. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10336. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10337. #endif
  10338. conn->request_info.is_ssl = conn->client.is_ssl;
  10339. if (!conn->client.is_ssl
  10340. #ifndef NO_SSL
  10341. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10342. #endif
  10343. ) {
  10344. process_new_connection(conn);
  10345. }
  10346. close_connection(conn);
  10347. }
  10348. }
  10349. /* Signal master that we're done with connection and exiting */
  10350. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10351. ctx->running_worker_threads--;
  10352. (void)pthread_cond_signal(&ctx->thread_cond);
  10353. /* assert(ctx->running_worker_threads >= 0); */
  10354. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10355. pthread_setspecific(sTlsKey, NULL);
  10356. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10357. CloseHandle(tls.pthread_cond_helper_mutex);
  10358. #endif
  10359. pthread_mutex_destroy(&conn->mutex);
  10360. mg_free(conn);
  10361. DEBUG_TRACE("%s", "exiting");
  10362. return NULL;
  10363. }
  10364. /* Threads have different return types on Windows and Unix. */
  10365. #ifdef _WIN32
  10366. static unsigned __stdcall worker_thread(void *thread_func_param)
  10367. {
  10368. worker_thread_run(thread_func_param);
  10369. return 0;
  10370. }
  10371. #else
  10372. static void *
  10373. worker_thread(void *thread_func_param)
  10374. {
  10375. worker_thread_run(thread_func_param);
  10376. return NULL;
  10377. }
  10378. #endif /* _WIN32 */
  10379. /* Master thread adds accepted socket to a queue */
  10380. static void
  10381. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10382. {
  10383. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10384. if (!ctx) {
  10385. return;
  10386. }
  10387. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10388. /* If the queue is full, wait */
  10389. while (ctx->stop_flag == 0
  10390. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10391. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10392. }
  10393. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10394. /* Copy socket to the queue and increment head */
  10395. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10396. ctx->sq_head++;
  10397. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10398. }
  10399. (void)pthread_cond_signal(&ctx->sq_full);
  10400. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10401. #undef QUEUE_SIZE
  10402. }
  10403. static void
  10404. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10405. {
  10406. struct socket so;
  10407. char src_addr[IP_ADDR_STR_LEN];
  10408. socklen_t len = sizeof(so.rsa);
  10409. int on = 1;
  10410. int timeout;
  10411. if (!listener) {
  10412. return;
  10413. }
  10414. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10415. == INVALID_SOCKET) {
  10416. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10417. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10418. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10419. closesocket(so.sock);
  10420. so.sock = INVALID_SOCKET;
  10421. } else {
  10422. /* Put so socket structure into the queue */
  10423. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10424. set_close_on_exec(so.sock, fc(ctx));
  10425. so.is_ssl = listener->is_ssl;
  10426. so.ssl_redir = listener->ssl_redir;
  10427. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10428. mg_cry(fc(ctx),
  10429. "%s: getsockname() failed: %s",
  10430. __func__,
  10431. strerror(ERRNO));
  10432. }
  10433. /* Set TCP keep-alive. This is needed because if HTTP-level
  10434. * keep-alive
  10435. * is enabled, and client resets the connection, server won't get
  10436. * TCP FIN or RST and will keep the connection open forever. With
  10437. * TCP
  10438. * keep-alive, next keep-alive handshake will figure out that the
  10439. * client is down and will close the server end.
  10440. * Thanks to Igor Klopov who suggested the patch. */
  10441. if (setsockopt(so.sock,
  10442. SOL_SOCKET,
  10443. SO_KEEPALIVE,
  10444. (SOCK_OPT_TYPE)&on,
  10445. sizeof(on)) != 0) {
  10446. mg_cry(fc(ctx),
  10447. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10448. __func__,
  10449. strerror(ERRNO));
  10450. }
  10451. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10452. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10453. } else {
  10454. timeout = -1;
  10455. }
  10456. /* Set socket timeout to the given value, but not more than a
  10457. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10458. * so the server can exit after that time if requested. */
  10459. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10460. set_sock_timeout(so.sock, timeout);
  10461. } else {
  10462. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10463. }
  10464. produce_socket(ctx, &so);
  10465. }
  10466. }
  10467. static void
  10468. master_thread_run(void *thread_func_param)
  10469. {
  10470. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10471. struct mg_workerTLS tls;
  10472. struct pollfd *pfd;
  10473. unsigned int i;
  10474. unsigned int workerthreadcount;
  10475. if (!ctx) {
  10476. return;
  10477. }
  10478. mg_set_thread_name("master");
  10479. /* Increase priority of the master thread */
  10480. #if defined(_WIN32)
  10481. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10482. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10483. int min_prio = sched_get_priority_min(SCHED_RR);
  10484. int max_prio = sched_get_priority_max(SCHED_RR);
  10485. if ((min_prio >= 0) && (max_prio >= 0)
  10486. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10487. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10488. struct sched_param sched_param = {0};
  10489. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10490. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10491. }
  10492. #endif
  10493. /* Initialize thread local storage */
  10494. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10495. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10496. #endif
  10497. tls.is_master = 1;
  10498. pthread_setspecific(sTlsKey, &tls);
  10499. /* Server starts *now* */
  10500. ctx->start_time = time(NULL);
  10501. /* Allocate memory for the listening sockets, and start the server */
  10502. pfd =
  10503. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10504. while (pfd != NULL && ctx->stop_flag == 0) {
  10505. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10506. pfd[i].fd = ctx->listening_sockets[i].sock;
  10507. pfd[i].events = POLLIN;
  10508. }
  10509. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10510. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10511. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10512. * successful poll, and POLLIN is defined as
  10513. * (POLLRDNORM | POLLRDBAND)
  10514. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10515. * pfd[i].revents == POLLIN. */
  10516. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10517. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10518. }
  10519. }
  10520. }
  10521. }
  10522. mg_free(pfd);
  10523. DEBUG_TRACE("%s", "stopping workers");
  10524. /* Stop signal received: somebody called mg_stop. Quit. */
  10525. close_all_listening_sockets(ctx);
  10526. /* Wakeup workers that are waiting for connections to handle. */
  10527. pthread_cond_broadcast(&ctx->sq_full);
  10528. /* Wait until all threads finish */
  10529. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10530. while (ctx->running_worker_threads > 0) {
  10531. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10532. }
  10533. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10534. /* Join all worker threads to avoid leaking threads. */
  10535. workerthreadcount = ctx->cfg_worker_threads;
  10536. for (i = 0; i < workerthreadcount; i++) {
  10537. if (ctx->workerthreadids[i] != 0) {
  10538. mg_join_thread(ctx->workerthreadids[i]);
  10539. }
  10540. }
  10541. #if !defined(NO_SSL)
  10542. if (ctx->ssl_ctx != NULL) {
  10543. uninitialize_ssl(ctx);
  10544. }
  10545. #endif
  10546. DEBUG_TRACE("%s", "exiting");
  10547. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10548. CloseHandle(tls.pthread_cond_helper_mutex);
  10549. #endif
  10550. pthread_setspecific(sTlsKey, NULL);
  10551. /* Signal mg_stop() that we're done.
  10552. * WARNING: This must be the very last thing this
  10553. * thread does, as ctx becomes invalid after this line. */
  10554. ctx->stop_flag = 2;
  10555. }
  10556. /* Threads have different return types on Windows and Unix. */
  10557. #ifdef _WIN32
  10558. static unsigned __stdcall master_thread(void *thread_func_param)
  10559. {
  10560. master_thread_run(thread_func_param);
  10561. return 0;
  10562. }
  10563. #else
  10564. static void *
  10565. master_thread(void *thread_func_param)
  10566. {
  10567. master_thread_run(thread_func_param);
  10568. return NULL;
  10569. }
  10570. #endif /* _WIN32 */
  10571. static void
  10572. free_context(struct mg_context *ctx)
  10573. {
  10574. int i;
  10575. struct mg_handler_info *tmp_rh;
  10576. if (ctx == NULL) {
  10577. return;
  10578. }
  10579. if (ctx->callbacks.exit_context) {
  10580. ctx->callbacks.exit_context(ctx);
  10581. }
  10582. /* All threads exited, no sync is needed. Destroy thread mutex and
  10583. * condvars
  10584. */
  10585. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10586. (void)pthread_cond_destroy(&ctx->thread_cond);
  10587. (void)pthread_cond_destroy(&ctx->sq_empty);
  10588. (void)pthread_cond_destroy(&ctx->sq_full);
  10589. /* Destroy other context global data structures mutex */
  10590. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10591. #if defined(USE_TIMERS)
  10592. timers_exit(ctx);
  10593. #endif
  10594. /* Deallocate config parameters */
  10595. for (i = 0; i < NUM_OPTIONS; i++) {
  10596. if (ctx->config[i] != NULL) {
  10597. #if defined(_MSC_VER)
  10598. #pragma warning(suppress : 6001)
  10599. #endif
  10600. mg_free(ctx->config[i]);
  10601. }
  10602. }
  10603. /* Deallocate request handlers */
  10604. while (ctx->handlers) {
  10605. tmp_rh = ctx->handlers;
  10606. ctx->handlers = tmp_rh->next;
  10607. mg_free(tmp_rh->uri);
  10608. mg_free(tmp_rh);
  10609. }
  10610. #ifndef NO_SSL
  10611. /* Deallocate SSL context */
  10612. if (ctx->ssl_ctx != NULL) {
  10613. SSL_CTX_free(ctx->ssl_ctx);
  10614. }
  10615. if (ssl_mutexes != NULL) {
  10616. mg_free(ssl_mutexes);
  10617. ssl_mutexes = NULL;
  10618. }
  10619. #endif /* !NO_SSL */
  10620. /* Deallocate worker thread ID array */
  10621. if (ctx->workerthreadids != NULL) {
  10622. mg_free(ctx->workerthreadids);
  10623. }
  10624. /* Deallocate the tls variable */
  10625. if (mg_atomic_dec(&sTlsInit) == 0) {
  10626. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10627. DeleteCriticalSection(&global_log_file_lock);
  10628. #endif /* _WIN32 && !__SYMBIAN32__ */
  10629. #if !defined(_WIN32)
  10630. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10631. #endif
  10632. pthread_key_delete(sTlsKey);
  10633. }
  10634. /* deallocate system name string */
  10635. mg_free(ctx->systemName);
  10636. /* Deallocate context itself */
  10637. mg_free(ctx);
  10638. }
  10639. void
  10640. mg_stop(struct mg_context *ctx)
  10641. {
  10642. pthread_t mt;
  10643. if (!ctx) {
  10644. return;
  10645. }
  10646. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10647. * two threads is not allowed. */
  10648. mt = ctx->masterthreadid;
  10649. if (mt == 0) {
  10650. return;
  10651. }
  10652. ctx->masterthreadid = 0;
  10653. ctx->stop_flag = 1;
  10654. /* Wait until mg_fini() stops */
  10655. while (ctx->stop_flag != 2) {
  10656. (void)mg_sleep(10);
  10657. }
  10658. mg_join_thread(mt);
  10659. free_context(ctx);
  10660. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10661. (void)WSACleanup();
  10662. #endif /* _WIN32 && !__SYMBIAN32__ */
  10663. }
  10664. static void
  10665. get_system_name(char **sysName)
  10666. {
  10667. #if defined(_WIN32)
  10668. #if !defined(__SYMBIAN32__)
  10669. char name[128];
  10670. DWORD dwVersion = 0;
  10671. DWORD dwMajorVersion = 0;
  10672. DWORD dwMinorVersion = 0;
  10673. DWORD dwBuild = 0;
  10674. #ifdef _MSC_VER
  10675. #pragma warning(push)
  10676. // GetVersion was declared deprecated
  10677. #pragma warning(disable : 4996)
  10678. #endif
  10679. dwVersion = GetVersion();
  10680. #ifdef _MSC_VER
  10681. #pragma warning(pop)
  10682. #endif
  10683. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10684. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10685. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10686. (void)dwBuild;
  10687. sprintf(name,
  10688. "Windows %u.%u",
  10689. (unsigned)dwMajorVersion,
  10690. (unsigned)dwMinorVersion);
  10691. *sysName = mg_strdup(name);
  10692. #else
  10693. *sysName = mg_strdup("Symbian");
  10694. #endif
  10695. #else
  10696. struct utsname name;
  10697. memset(&name, 0, sizeof(name));
  10698. uname(&name);
  10699. *sysName = mg_strdup(name.sysname);
  10700. #endif
  10701. }
  10702. struct mg_context *
  10703. mg_start(const struct mg_callbacks *callbacks,
  10704. void *user_data,
  10705. const char **options)
  10706. {
  10707. struct mg_context *ctx;
  10708. const char *name, *value, *default_value;
  10709. int idx, ok, workerthreadcount;
  10710. unsigned int i;
  10711. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10712. struct mg_workerTLS tls;
  10713. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10714. WSADATA data;
  10715. WSAStartup(MAKEWORD(2, 2), &data);
  10716. #endif /* _WIN32 && !__SYMBIAN32__ */
  10717. /* Allocate context and initialize reasonable general case defaults. */
  10718. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10719. return NULL;
  10720. }
  10721. /* Random number generator will initialize at the first call */
  10722. ctx->auth_nonce_mask =
  10723. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10724. if (mg_atomic_inc(&sTlsInit) == 1) {
  10725. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10726. InitializeCriticalSection(&global_log_file_lock);
  10727. #endif /* _WIN32 && !__SYMBIAN32__ */
  10728. #if !defined(_WIN32)
  10729. pthread_mutexattr_init(&pthread_mutex_attr);
  10730. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10731. #endif
  10732. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10733. /* Fatal error - abort start. However, this situation should
  10734. * never
  10735. * occur in practice. */
  10736. mg_atomic_dec(&sTlsInit);
  10737. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10738. mg_free(ctx);
  10739. return NULL;
  10740. }
  10741. } else {
  10742. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10743. * initialized. */
  10744. mg_sleep(1);
  10745. }
  10746. tls.is_master = -1;
  10747. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10748. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10749. tls.pthread_cond_helper_mutex = NULL;
  10750. #endif
  10751. pthread_setspecific(sTlsKey, &tls);
  10752. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10753. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10754. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10755. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10756. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10757. if (!ok) {
  10758. /* Fatal error - abort start. However, this situation should never
  10759. * occur in practice. */
  10760. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10761. mg_free(ctx);
  10762. pthread_setspecific(sTlsKey, NULL);
  10763. return NULL;
  10764. }
  10765. if (callbacks) {
  10766. ctx->callbacks = *callbacks;
  10767. exit_callback = callbacks->exit_context;
  10768. ctx->callbacks.exit_context = 0;
  10769. }
  10770. ctx->user_data = user_data;
  10771. ctx->handlers = NULL;
  10772. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10773. ctx->shared_lua_websockets = 0;
  10774. #endif
  10775. while (options && (name = *options++) != NULL) {
  10776. if ((idx = get_option_index(name)) == -1) {
  10777. mg_cry(fc(ctx), "Invalid option: %s", name);
  10778. free_context(ctx);
  10779. pthread_setspecific(sTlsKey, NULL);
  10780. return NULL;
  10781. } else if ((value = *options++) == NULL) {
  10782. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10783. free_context(ctx);
  10784. pthread_setspecific(sTlsKey, NULL);
  10785. return NULL;
  10786. }
  10787. if (ctx->config[idx] != NULL) {
  10788. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10789. mg_free(ctx->config[idx]);
  10790. }
  10791. ctx->config[idx] = mg_strdup(value);
  10792. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10793. }
  10794. /* Set default value if needed */
  10795. for (i = 0; config_options[i].name != NULL; i++) {
  10796. default_value = config_options[i].default_value;
  10797. if (ctx->config[i] == NULL && default_value != NULL) {
  10798. ctx->config[i] = mg_strdup(default_value);
  10799. }
  10800. }
  10801. #if defined(NO_FILES)
  10802. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  10803. mg_cry(fc(ctx), "%s", "Document root must not be set");
  10804. free_context(ctx);
  10805. pthread_setspecific(sTlsKey, NULL);
  10806. return NULL;
  10807. }
  10808. #endif
  10809. get_system_name(&ctx->systemName);
  10810. /* NOTE(lsm): order is important here. SSL certificates must
  10811. * be initialized before listening ports. UID must be set last. */
  10812. if (!set_gpass_option(ctx) ||
  10813. #if !defined(NO_SSL)
  10814. !set_ssl_option(ctx) ||
  10815. #endif
  10816. !set_ports_option(ctx) ||
  10817. #if !defined(_WIN32)
  10818. !set_uid_option(ctx) ||
  10819. #endif
  10820. !set_acl_option(ctx)) {
  10821. free_context(ctx);
  10822. pthread_setspecific(sTlsKey, NULL);
  10823. return NULL;
  10824. }
  10825. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  10826. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  10827. * won't kill the whole process. */
  10828. (void)signal(SIGPIPE, SIG_IGN);
  10829. #endif /* !_WIN32 && !__SYMBIAN32__ */
  10830. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  10831. if (workerthreadcount > MAX_WORKER_THREADS) {
  10832. mg_cry(fc(ctx), "Too many worker threads");
  10833. free_context(ctx);
  10834. pthread_setspecific(sTlsKey, NULL);
  10835. return NULL;
  10836. }
  10837. if (workerthreadcount > 0) {
  10838. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  10839. ctx->workerthreadids =
  10840. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  10841. if (ctx->workerthreadids == NULL) {
  10842. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  10843. free_context(ctx);
  10844. pthread_setspecific(sTlsKey, NULL);
  10845. return NULL;
  10846. }
  10847. }
  10848. #if defined(USE_TIMERS)
  10849. if (timers_init(ctx) != 0) {
  10850. mg_cry(fc(ctx), "Error creating timers");
  10851. free_context(ctx);
  10852. pthread_setspecific(sTlsKey, NULL);
  10853. return NULL;
  10854. }
  10855. #endif
  10856. /* Context has been created - init user libraries */
  10857. if (ctx->callbacks.init_context) {
  10858. ctx->callbacks.init_context(ctx);
  10859. }
  10860. ctx->callbacks.exit_context = exit_callback;
  10861. ctx->context_type = 1; /* server context */
  10862. /* Start master (listening) thread */
  10863. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  10864. /* Start worker threads */
  10865. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10866. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10867. ctx->running_worker_threads++;
  10868. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10869. if (mg_start_thread_with_id(worker_thread,
  10870. ctx,
  10871. &ctx->workerthreadids[i]) != 0) {
  10872. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10873. ctx->running_worker_threads--;
  10874. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10875. if (i > 0) {
  10876. mg_cry(fc(ctx),
  10877. "Cannot start worker thread %i: error %ld",
  10878. i + 1,
  10879. (long)ERRNO);
  10880. } else {
  10881. mg_cry(fc(ctx),
  10882. "Cannot create threads: error %ld",
  10883. (long)ERRNO);
  10884. free_context(ctx);
  10885. pthread_setspecific(sTlsKey, NULL);
  10886. return NULL;
  10887. }
  10888. break;
  10889. }
  10890. }
  10891. pthread_setspecific(sTlsKey, NULL);
  10892. return ctx;
  10893. }
  10894. /* Feature check API function */
  10895. unsigned
  10896. mg_check_feature(unsigned feature)
  10897. {
  10898. static const unsigned feature_set = 0
  10899. /* Set bits for available features according to API documentation.
  10900. * This bit mask is created at compile time, according to the active
  10901. * preprocessor defines. It is a single const value at runtime. */
  10902. #if !defined(NO_FILES)
  10903. | 1
  10904. #endif
  10905. #if !defined(NO_SSL)
  10906. | 2
  10907. #endif
  10908. #if !defined(NO_CGI)
  10909. | 4
  10910. #endif
  10911. #if defined(USE_IPV6)
  10912. | 8
  10913. #endif
  10914. #if defined(USE_WEBSOCKET)
  10915. | 16
  10916. #endif
  10917. #if defined(USE_LUA)
  10918. | 32
  10919. #endif
  10920. #if defined(USE_DUKTAPE)
  10921. | 64
  10922. #endif
  10923. /* Set some extra bits not defined in the API documentation.
  10924. * These bits may change without further notice. */
  10925. #if defined(MG_LEGACY_INTERFACE)
  10926. | 128
  10927. #endif
  10928. #if defined(MEMORY_DEBUGGING)
  10929. | 256
  10930. #endif
  10931. #if defined(USE_TIMERS)
  10932. | 512
  10933. #endif
  10934. #if !defined(NO_NONCE_CHECK)
  10935. | 1024
  10936. #endif
  10937. #if !defined(NO_POPEN)
  10938. | 2048
  10939. #endif
  10940. ;
  10941. return (feature & feature_set);
  10942. }