civetweb.c 261 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038
  1. /* Copyright (c) 2013-2015 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. #else
  27. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  28. #define _GNU_SOURCE /* for setgroups() */
  29. #endif
  30. #ifdef __linux__
  31. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  32. #endif
  33. #ifndef _LARGEFILE_SOURCE
  34. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  35. #endif
  36. #ifndef _FILE_OFFSET_BITS
  37. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  38. #endif
  39. #ifndef __STDC_FORMAT_MACROS
  40. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  41. #endif
  42. #ifndef __STDC_LIMIT_MACROS
  43. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  44. #endif
  45. #ifdef __sun
  46. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  47. #define __inline inline /* not recognized on older compiler versions */
  48. #endif
  49. #endif
  50. #if defined(_MSC_VER)
  51. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  52. #pragma warning(disable : 4306)
  53. /* conditional expression is constant: introduced by FD_SET(..) */
  54. #pragma warning(disable : 4127)
  55. /* non-constant aggregate initializer: issued due to missing C99 support */
  56. #pragma warning(disable : 4204)
  57. #endif
  58. /* This code uses static_assert to check some conditions.
  59. * Unfortunately some compilers still do not support it, so we have a
  60. * replacement function here. */
  61. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  62. #define mg_static_assert static_assert
  63. #else
  64. char static_assert_replacement[1];
  65. #define mg_static_assert(cond, txt) \
  66. { extern char static_assert_replacement[(cond) ? 1 : -1]; }
  67. #endif
  68. mg_static_assert(1, "static assert has to be available");
  69. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  70. "int data type size check");
  71. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  72. "pointer data type size check");
  73. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  74. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  75. * type size check"); */
  76. /* DTL -- including winsock2.h works better if lean and mean */
  77. #ifndef WIN32_LEAN_AND_MEAN
  78. #define WIN32_LEAN_AND_MEAN
  79. #endif
  80. #if defined(_WIN32)
  81. #include <ws2tcpip.h>
  82. #endif
  83. #if defined(__SYMBIAN32__)
  84. #define NO_SSL /* SSL is not supported */
  85. #define NO_CGI /* CGI is not supported */
  86. #define PATH_MAX FILENAME_MAX
  87. #endif /* __SYMBIAN32__ */
  88. #ifndef IGNORE_UNUSED_RESULT
  89. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  90. #endif
  91. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  92. #include <sys/types.h>
  93. #include <sys/stat.h>
  94. #include <errno.h>
  95. #include <signal.h>
  96. #include <fcntl.h>
  97. #endif /* !_WIN32_WCE */
  98. #ifdef __MACH__
  99. #define CLOCK_MONOTONIC (1)
  100. #define CLOCK_REALTIME (2)
  101. #include <sys/time.h>
  102. #include <mach/clock.h>
  103. #include <mach/mach.h>
  104. #include <mach/mach_time.h>
  105. #include <assert.h>
  106. /* clock_gettime is not implemented on OSX */
  107. int clock_gettime(int clk_id, struct timespec *t) {
  108. if (clk_id == CLOCK_REALTIME) {
  109. struct timeval now;
  110. int rv = gettimeofday(&now, NULL);
  111. if (rv)
  112. return rv;
  113. t->tv_sec = now.tv_sec;
  114. t->tv_nsec = now.tv_usec * 1000;
  115. return 0;
  116. } else if (clk_id == CLOCK_MONOTONIC) {
  117. static uint64_t start_time = 0;
  118. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  119. uint64_t now = mach_absolute_time();
  120. if (start_time == 0) {
  121. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  122. #if defined(DEBUG)
  123. assert(mach_status == KERN_SUCCESS);
  124. #else
  125. /* appease "unused variable" warning for release builds */
  126. (void)mach_status;
  127. #endif
  128. start_time = now;
  129. }
  130. now =
  131. (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer /
  132. (double)timebase_ifo.denom);
  133. t->tv_sec = now / 1000000000;
  134. t->tv_nsec = now % 1000000000;
  135. return 0;
  136. }
  137. return -1; /* EINVAL - Clock ID is unknown */
  138. }
  139. #endif
  140. #include <time.h>
  141. #include <stdlib.h>
  142. #include <stdarg.h>
  143. #include <assert.h>
  144. #include <string.h>
  145. #include <ctype.h>
  146. #include <limits.h>
  147. #include <stddef.h>
  148. #include <stdio.h>
  149. #ifndef MAX_WORKER_THREADS
  150. #define MAX_WORKER_THREADS (1024 * 64)
  151. #endif
  152. mg_static_assert(MAX_WORKER_THREADS >= 1,
  153. "worker threads must be a positive number");
  154. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  155. #include <windows.h>
  156. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  157. typedef const char *SOCK_OPT_TYPE;
  158. #if !defined(PATH_MAX)
  159. #define PATH_MAX (MAX_PATH)
  160. #endif
  161. #if !defined(PATH_MAX)
  162. #define PATH_MAX (4096)
  163. #endif
  164. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  165. #ifndef _IN_PORT_T
  166. #ifndef in_port_t
  167. #define in_port_t u_short
  168. #endif
  169. #endif
  170. #ifndef _WIN32_WCE
  171. #include <process.h>
  172. #include <direct.h>
  173. #include <io.h>
  174. #else /* _WIN32_WCE */
  175. #define NO_CGI /* WinCE has no pipes */
  176. typedef long off_t;
  177. #define errno (GetLastError())
  178. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  179. #endif /* _WIN32_WCE */
  180. #define MAKEUQUAD(lo, hi) \
  181. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  182. #define RATE_DIFF (10000000) /* 100 nsecs */
  183. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  184. #define SYS2UNIX_TIME(lo, hi) \
  185. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  186. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  187. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  188. * Also use _strtoui64 on modern M$ compilers */
  189. #if defined(_MSC_VER) && (_MSC_VER < 1300)
  190. #define STRX(x) #x
  191. #define STR(x) STRX(x)
  192. #define __func__ __FILE__ ":" STR(__LINE__)
  193. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  194. #define strtoll(x, y, z) (_atoi64(x))
  195. #else
  196. #define __func__ __FUNCTION__
  197. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  198. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  199. #endif /* _MSC_VER */
  200. #define ERRNO (GetLastError())
  201. #define NO_SOCKLEN_T
  202. #define SSL_LIB "ssleay32.dll"
  203. #define CRYPTO_LIB "libeay32.dll"
  204. #define O_NONBLOCK (0)
  205. #ifndef W_OK
  206. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  207. #endif
  208. #if !defined(EWOULDBLOCK)
  209. #define EWOULDBLOCK WSAEWOULDBLOCK
  210. #endif /* !EWOULDBLOCK */
  211. #define _POSIX_
  212. #define INT64_FMT "I64d"
  213. #define WINCDECL __cdecl
  214. #define SHUT_RD (0)
  215. #define SHUT_WR (1)
  216. #define SHUT_BOTH (2)
  217. #define snprintf _snprintf
  218. #define vsnprintf _vsnprintf
  219. #define access _access
  220. #define mg_sleep(x) (Sleep(x))
  221. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  222. #ifndef popen
  223. #define popen(x, y) (_popen(x, y))
  224. #endif
  225. #ifndef pclose
  226. #define pclose(x) (_pclose(x))
  227. #endif
  228. #define close(x) (_close(x))
  229. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  230. #define RTLD_LAZY (0)
  231. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)))
  232. #define fdopen(x, y) (_fdopen((x), (y)))
  233. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  234. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  235. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  236. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  237. #define sleep(x) (Sleep((x)*1000))
  238. #define rmdir(x) (_rmdir(x))
  239. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  240. #define USE_TIMERS
  241. #endif
  242. #if !defined(fileno)
  243. #define fileno(x) (_fileno(x))
  244. #endif /* !fileno MINGW #defines fileno */
  245. typedef HANDLE pthread_mutex_t;
  246. typedef DWORD pthread_key_t;
  247. typedef HANDLE pthread_t;
  248. typedef struct {
  249. CRITICAL_SECTION threadIdSec;
  250. int waitingthreadcount; /* The number of threads queued. */
  251. pthread_t *waitingthreadhdls; /* The thread handles. */
  252. } pthread_cond_t;
  253. #ifndef __clockid_t_defined
  254. typedef DWORD clockid_t;
  255. #endif
  256. #ifndef CLOCK_MONOTONIC
  257. #define CLOCK_MONOTONIC (1)
  258. #endif
  259. #ifndef CLOCK_REALTIME
  260. #define CLOCK_REALTIME (2)
  261. #endif
  262. #ifndef _TIMESPEC_DEFINED
  263. struct timespec {
  264. time_t tv_sec; /* seconds */
  265. long tv_nsec; /* nanoseconds */
  266. };
  267. #endif
  268. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  269. static int pthread_mutex_lock(pthread_mutex_t *);
  270. static int pthread_mutex_unlock(pthread_mutex_t *);
  271. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  272. struct file;
  273. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  274. #if defined(HAVE_STDINT)
  275. #include <stdint.h>
  276. #else
  277. typedef unsigned int uint32_t;
  278. typedef unsigned short uint16_t;
  279. typedef unsigned __int64 uint64_t;
  280. typedef __int64 int64_t;
  281. #define INT64_MAX (9223372036854775807)
  282. #endif /* HAVE_STDINT */
  283. /* POSIX dirent interface */
  284. struct dirent {
  285. char d_name[PATH_MAX];
  286. };
  287. typedef struct DIR {
  288. HANDLE handle;
  289. WIN32_FIND_DATAW info;
  290. struct dirent result;
  291. } DIR;
  292. #if defined(_WIN32) && !defined(POLLIN)
  293. #ifndef HAVE_POLL
  294. struct pollfd {
  295. SOCKET fd;
  296. short events;
  297. short revents;
  298. };
  299. #define POLLIN (0x0300)
  300. #endif
  301. #endif
  302. /* Mark required libraries */
  303. #if defined(_MSC_VER)
  304. #pragma comment(lib, "Ws2_32.lib")
  305. #endif
  306. #else /* UNIX specific */
  307. #include <sys/wait.h>
  308. #include <sys/socket.h>
  309. #include <sys/poll.h>
  310. #include <netinet/in.h>
  311. #include <arpa/inet.h>
  312. #include <sys/time.h>
  313. #include <sys/utsname.h>
  314. #include <stdint.h>
  315. #include <inttypes.h>
  316. #include <netdb.h>
  317. typedef const void *SOCK_OPT_TYPE;
  318. #if defined(ANDROID)
  319. typedef unsigned short int in_port_t;
  320. #endif
  321. #include <pwd.h>
  322. #include <unistd.h>
  323. #include <grp.h>
  324. #include <dirent.h>
  325. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  326. #include <dlfcn.h>
  327. #endif
  328. #include <pthread.h>
  329. #if defined(__MACH__)
  330. #define SSL_LIB "libssl.dylib"
  331. #define CRYPTO_LIB "libcrypto.dylib"
  332. #else
  333. #if !defined(SSL_LIB)
  334. #define SSL_LIB "libssl.so"
  335. #endif
  336. #if !defined(CRYPTO_LIB)
  337. #define CRYPTO_LIB "libcrypto.so"
  338. #endif
  339. #endif
  340. #ifndef O_BINARY
  341. #define O_BINARY (0)
  342. #endif /* O_BINARY */
  343. #define closesocket(a) (close(a))
  344. #define mg_mkdir(x, y) (mkdir(x, y))
  345. #define mg_remove(x) (remove(x))
  346. #define mg_sleep(x) (usleep((x)*1000))
  347. #define ERRNO (errno)
  348. #define INVALID_SOCKET (-1)
  349. #define INT64_FMT PRId64
  350. typedef int SOCKET;
  351. #define WINCDECL
  352. #if defined(__hpux)
  353. /* HPUX 11 does not have monotonic, fall back to realtime */
  354. #ifndef CLOCK_MONOTONIC
  355. #define CLOCK_MONOTONIC CLOCK_REALTIME
  356. #endif
  357. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  358. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  359. * the prototypes use int* rather than socklen_t* which matches the
  360. * actual library expectation. When called with the wrong size arg
  361. * accept() returns a zero client inet addr and check_acl() always
  362. * fails. Since socklen_t is widely used below, just force replace
  363. * their typedef with int. - DTL
  364. */
  365. #define socklen_t int
  366. #endif /* hpux */
  367. #endif /* End of Windows and UNIX specific includes */
  368. /* va_copy should always be a macro, C99 and C++11 - DTL */
  369. #ifndef va_copy
  370. #define va_copy(x, y) ((x) = (y))
  371. #endif
  372. #ifdef _WIN32
  373. static CRITICAL_SECTION global_log_file_lock;
  374. static DWORD pthread_self(void) { return GetCurrentThreadId(); }
  375. int pthread_key_create(
  376. pthread_key_t *key,
  377. void (*_must_be_zero)(
  378. void *) /* destructor function not supported for windows */) {
  379. assert(_must_be_zero == NULL);
  380. if ((key != 0) && (_must_be_zero == NULL)) {
  381. *key = TlsAlloc();
  382. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  383. }
  384. return -2;
  385. }
  386. int pthread_key_delete(pthread_key_t key) { return TlsFree(key) ? 0 : 1; }
  387. int pthread_setspecific(pthread_key_t key, void *value) {
  388. return TlsSetValue(key, value) ? 0 : 1;
  389. }
  390. void *pthread_getspecific(pthread_key_t key) { return TlsGetValue(key); }
  391. #endif /* _WIN32 */
  392. #include "civetweb.h"
  393. #define PASSWORDS_FILE_NAME ".htpasswd"
  394. #define CGI_ENVIRONMENT_SIZE (4096)
  395. #define MAX_CGI_ENVIR_VARS (64)
  396. #define MG_BUF_LEN (8192)
  397. #ifndef MAX_REQUEST_SIZE
  398. #define MAX_REQUEST_SIZE (16384)
  399. #endif
  400. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  401. "request size length must be a positive number");
  402. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  403. #if !defined(DEBUG_TRACE)
  404. #if defined(DEBUG)
  405. static void DEBUG_TRACE_FUNC(const char *func, unsigned line,
  406. PRINTF_FORMAT_STRING(const char *fmt), ...)
  407. PRINTF_ARGS(3, 4);
  408. static void DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt,
  409. ...) {
  410. va_list args;
  411. flockfile(stdout);
  412. printf("*** %lu.%p.%s.%u: ", (unsigned long)time(NULL),
  413. (void *)pthread_self(), func, line);
  414. va_start(args, fmt);
  415. vprintf(fmt, args);
  416. va_end(args);
  417. putchar('\n');
  418. fflush(stdout);
  419. funlockfile(stdout);
  420. }
  421. #define DEBUG_TRACE(fmt, ...) \
  422. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  423. #else
  424. #define DEBUG_TRACE(fmt, ...)
  425. #endif /* DEBUG */
  426. #endif /* DEBUG_TRACE */
  427. #if defined(MEMORY_DEBUGGING)
  428. unsigned long mg_memory_debug_blockCount = 0;
  429. unsigned long mg_memory_debug_totalMemUsed = 0;
  430. static void *mg_malloc_ex(size_t size, const char *file, unsigned line) {
  431. void *data = malloc(size + sizeof(size_t));
  432. void *memory = 0;
  433. char mallocStr[256];
  434. if (data) {
  435. *(size_t *)data = size;
  436. mg_memory_debug_totalMemUsed += size;
  437. mg_memory_debug_blockCount++;
  438. memory = (void *)(((char *)data) + sizeof(size_t));
  439. }
  440. sprintf(mallocStr, "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n", memory,
  441. (unsigned long)size, mg_memory_debug_totalMemUsed,
  442. mg_memory_debug_blockCount, file, line);
  443. #if defined(_WIN32)
  444. OutputDebugStringA(mallocStr);
  445. #else
  446. DEBUG_TRACE("%s", mallocStr);
  447. #endif
  448. return memory;
  449. }
  450. static void *mg_calloc_ex(size_t count, size_t size, const char *file,
  451. unsigned line) {
  452. void *data = mg_malloc_ex(size * count, file, line);
  453. if (data)
  454. memset(data, 0, size);
  455. return data;
  456. }
  457. static void mg_free_ex(void *memory, const char *file, unsigned line) {
  458. char mallocStr[256];
  459. void *data = (void *)(((char *)memory) - sizeof(size_t));
  460. size_t size;
  461. if (memory) {
  462. size = *(size_t *)data;
  463. mg_memory_debug_totalMemUsed -= size;
  464. mg_memory_debug_blockCount--;
  465. sprintf(mallocStr, "MEM: %p %5lu free %7lu %4lu --- %s:%u\n", memory,
  466. (unsigned long)size, mg_memory_debug_totalMemUsed,
  467. mg_memory_debug_blockCount, file, line);
  468. #if defined(_WIN32)
  469. OutputDebugStringA(mallocStr);
  470. #else
  471. DEBUG_TRACE("%s", mallocStr);
  472. #endif
  473. free(data);
  474. }
  475. }
  476. static void *mg_realloc_ex(void *memory, size_t newsize, const char *file,
  477. unsigned line) {
  478. char mallocStr[256];
  479. void *data;
  480. void *_realloc;
  481. size_t oldsize;
  482. if (newsize) {
  483. if (memory) {
  484. data = (void *)(((char *)memory) - sizeof(size_t));
  485. oldsize = *(size_t *)data;
  486. _realloc = realloc(data, newsize + sizeof(size_t));
  487. if (_realloc) {
  488. data = _realloc;
  489. mg_memory_debug_totalMemUsed -= oldsize;
  490. sprintf(mallocStr, "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  491. memory, (unsigned long)oldsize,
  492. mg_memory_debug_totalMemUsed,
  493. mg_memory_debug_blockCount, file, line);
  494. #if defined(_WIN32)
  495. OutputDebugStringA(mallocStr);
  496. #else
  497. DEBUG_TRACE("%s", mallocStr);
  498. #endif
  499. mg_memory_debug_totalMemUsed += newsize;
  500. sprintf(mallocStr, "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  501. memory, (unsigned long)newsize,
  502. mg_memory_debug_totalMemUsed,
  503. mg_memory_debug_blockCount, file, line);
  504. #if defined(_WIN32)
  505. OutputDebugStringA(mallocStr);
  506. #else
  507. DEBUG_TRACE("%s", mallocStr);
  508. #endif
  509. *(size_t *)data = newsize;
  510. data = (void *)(((char *)data) + sizeof(size_t));
  511. } else {
  512. #if defined(_WIN32)
  513. OutputDebugStringA("MEM: realloc failed\n");
  514. #else
  515. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  516. #endif
  517. return _realloc;
  518. }
  519. } else {
  520. data = mg_malloc_ex(newsize, file, line);
  521. }
  522. } else {
  523. data = 0;
  524. mg_free_ex(memory, file, line);
  525. }
  526. return data;
  527. }
  528. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  529. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  530. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  531. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  532. #else
  533. static __inline void *mg_malloc(size_t a) { return malloc(a); }
  534. static __inline void *mg_calloc(size_t a, size_t b) { return calloc(a, b); }
  535. static __inline void *mg_realloc(void *a, size_t b) { return realloc(a, b); }
  536. static __inline void mg_free(void *a) { free(a); }
  537. #endif
  538. /* This following lines are just meant as a reminder to use the mg-functions
  539. * for memory management */
  540. #ifdef malloc
  541. #undef malloc
  542. #endif
  543. #ifdef calloc
  544. #undef calloc
  545. #endif
  546. #ifdef realloc
  547. #undef realloc
  548. #endif
  549. #ifdef free
  550. #undef free
  551. #endif
  552. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  553. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  554. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  555. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  556. #define MD5_STATIC static
  557. #include "md5.inl"
  558. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  559. #ifdef NO_SOCKLEN_T
  560. typedef int socklen_t;
  561. #endif /* NO_SOCKLEN_T */
  562. #define _DARWIN_UNLIMITED_SELECT
  563. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  564. #if !defined(MSG_NOSIGNAL)
  565. #define MSG_NOSIGNAL (0)
  566. #endif
  567. #if !defined(SOMAXCONN)
  568. #define SOMAXCONN (100)
  569. #endif
  570. /* Size of the accepted socket queue */
  571. #if !defined(MGSQLEN)
  572. #define MGSQLEN (20)
  573. #endif
  574. #if defined(NO_SSL_DL)
  575. #include <openssl/ssl.h>
  576. #include <openssl/err.h>
  577. #else
  578. /* SSL loaded dynamically from DLL.
  579. * I put the prototypes here to be independent from OpenSSL source
  580. * installation. */
  581. typedef struct ssl_st SSL;
  582. typedef struct ssl_method_st SSL_METHOD;
  583. typedef struct ssl_ctx_st SSL_CTX;
  584. struct ssl_func {
  585. const char *name; /* SSL function name */
  586. void (*ptr)(void); /* Function pointer */
  587. };
  588. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  589. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  590. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  591. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  592. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  593. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  594. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  595. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  596. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  597. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  598. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  599. #define SSL_CTX_use_PrivateKey_file \
  600. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  601. #define SSL_CTX_use_certificate_file \
  602. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  603. #define SSL_CTX_set_default_passwd_cb \
  604. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  605. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  606. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  607. #define SSL_CTX_use_certificate_chain_file \
  608. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  609. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  610. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  611. #define SSL_CTX_set_verify (*(void (*)(SSL_CTX *, int, int))ssl_sw[19].ptr)
  612. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  613. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  614. #define CRYPTO_set_locking_callback \
  615. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  616. #define CRYPTO_set_id_callback \
  617. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  618. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  619. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  620. /* set_ssl_option() function updates this array.
  621. * It loads SSL library dynamically and changes NULLs to the actual addresses
  622. * of respective functions. The macros above (like SSL_connect()) are really
  623. * just calling these functions indirectly via the pointer. */
  624. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  625. {"SSL_accept", NULL},
  626. {"SSL_connect", NULL},
  627. {"SSL_read", NULL},
  628. {"SSL_write", NULL},
  629. {"SSL_get_error", NULL},
  630. {"SSL_set_fd", NULL},
  631. {"SSL_new", NULL},
  632. {"SSL_CTX_new", NULL},
  633. {"SSLv23_server_method", NULL},
  634. {"SSL_library_init", NULL},
  635. {"SSL_CTX_use_PrivateKey_file", NULL},
  636. {"SSL_CTX_use_certificate_file", NULL},
  637. {"SSL_CTX_set_default_passwd_cb", NULL},
  638. {"SSL_CTX_free", NULL},
  639. {"SSL_load_error_strings", NULL},
  640. {"SSL_CTX_use_certificate_chain_file", NULL},
  641. {"SSLv23_client_method", NULL},
  642. {"SSL_pending", NULL},
  643. {"SSL_CTX_set_verify", NULL},
  644. {"SSL_shutdown", NULL},
  645. {NULL, NULL}};
  646. /* Similar array as ssl_sw. These functions could be located in different
  647. * lib. */
  648. #if !defined(NO_SSL)
  649. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  650. {"CRYPTO_set_locking_callback", NULL},
  651. {"CRYPTO_set_id_callback", NULL},
  652. {"ERR_get_error", NULL},
  653. {"ERR_error_string", NULL},
  654. {NULL, NULL}};
  655. #endif /* NO_SSL */
  656. #endif /* NO_SSL_DL */
  657. static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  658. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  659. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  660. * union u. */
  661. union usa {
  662. struct sockaddr sa;
  663. struct sockaddr_in sin;
  664. #if defined(USE_IPV6)
  665. struct sockaddr_in6 sin6;
  666. #endif
  667. };
  668. /* Describes a string (chunk of memory). */
  669. struct vec {
  670. const char *ptr;
  671. size_t len;
  672. };
  673. struct file {
  674. int is_directory;
  675. time_t modification_time;
  676. int64_t size;
  677. FILE *fp;
  678. const char *membuf; /* Non-NULL if file data is in memory */
  679. /* set to 1 if the content is gzipped
  680. in which case we need a content-encoding: gzip header */
  681. int gzipped;
  682. };
  683. #define STRUCT_FILE_INITIALIZER \
  684. { 0, 0, 0, NULL, NULL, 0 }
  685. /* Describes listening socket, or socket which was accept()-ed by the master
  686. thread and queued for future handling by the worker thread. */
  687. struct socket {
  688. SOCKET sock; /* Listening socket */
  689. union usa lsa; /* Local socket address */
  690. union usa rsa; /* Remote socket address */
  691. unsigned char is_ssl; /* Is port SSL-ed */
  692. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  693. port */
  694. };
  695. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  696. enum {
  697. CGI_EXTENSIONS,
  698. CGI_ENVIRONMENT,
  699. PUT_DELETE_PASSWORDS_FILE,
  700. CGI_INTERPRETER,
  701. PROTECT_URI,
  702. AUTHENTICATION_DOMAIN,
  703. SSI_EXTENSIONS,
  704. THROTTLE,
  705. ACCESS_LOG_FILE,
  706. ENABLE_DIRECTORY_LISTING,
  707. ERROR_LOG_FILE,
  708. GLOBAL_PASSWORDS_FILE,
  709. INDEX_FILES,
  710. ENABLE_KEEP_ALIVE,
  711. ACCESS_CONTROL_LIST,
  712. EXTRA_MIME_TYPES,
  713. LISTENING_PORTS,
  714. DOCUMENT_ROOT,
  715. SSL_CERTIFICATE,
  716. NUM_THREADS,
  717. RUN_AS_USER,
  718. REWRITE,
  719. HIDE_FILES,
  720. REQUEST_TIMEOUT,
  721. DECODE_URL,
  722. #if defined(USE_LUA)
  723. LUA_PRELOAD_FILE,
  724. LUA_SCRIPT_EXTENSIONS,
  725. LUA_SERVER_PAGE_EXTENSIONS,
  726. #endif
  727. #if defined(USE_WEBSOCKET)
  728. WEBSOCKET_ROOT,
  729. #endif
  730. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  731. LUA_WEBSOCKET_EXTENSIONS,
  732. #endif
  733. ACCESS_CONTROL_ALLOW_ORIGIN,
  734. ERROR_PAGES,
  735. NUM_OPTIONS
  736. };
  737. /* Config option name, config types, default value */
  738. static struct mg_option config_options[] = {
  739. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  740. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  741. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  742. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  743. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  744. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  745. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  746. {"throttle", CONFIG_TYPE_STRING, NULL},
  747. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  748. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  749. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  750. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  751. {"index_files", CONFIG_TYPE_STRING,
  752. #ifdef USE_LUA
  753. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  754. "index.shtml,index.php"},
  755. #else
  756. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  757. #endif
  758. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  759. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  760. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  761. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  762. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  763. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  764. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  765. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  766. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  767. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  768. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  769. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  770. #if defined(USE_LUA)
  771. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  772. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  773. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  774. #endif
  775. #if defined(USE_WEBSOCKET)
  776. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  777. #endif
  778. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  779. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  780. #endif
  781. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  782. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  783. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  784. /* Check if the config_options and the corresponding enum have compatible
  785. * sizes. */
  786. mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) ==
  787. (NUM_OPTIONS + 1),
  788. "config_options and enum not sync");
  789. struct mg_request_handler_info {
  790. /* Name/Pattern of the URI. */
  791. char *uri;
  792. size_t uri_len;
  793. /* URI type: ws/wss (websocket) or http/https (web page). */
  794. int is_websocket_handler;
  795. /* Handler for http/https requests. */
  796. mg_request_handler handler;
  797. /* Handler for ws/wss (websocket) requests. */
  798. mg_websocket_connect_handler connect_handler;
  799. mg_websocket_ready_handler ready_handler;
  800. mg_websocket_data_handler data_handler;
  801. mg_websocket_close_handler close_handler;
  802. /* User supplied argument for the handler function. */
  803. void *cbdata;
  804. /* next request handler in a linked list */
  805. struct mg_request_handler_info *next;
  806. };
  807. struct mg_context {
  808. volatile int stop_flag; /* Should we stop event loop */
  809. SSL_CTX *ssl_ctx; /* SSL context */
  810. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  811. struct mg_callbacks callbacks; /* User-defined callback function */
  812. void *user_data; /* User-defined data */
  813. int context_type; /* 1 = server context, 2 = client context */
  814. struct socket *listening_sockets;
  815. in_port_t *listening_ports;
  816. int num_listening_sockets;
  817. volatile int num_threads; /* Number of threads */
  818. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  819. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  820. struct socket queue[MGSQLEN]; /* Accepted sockets */
  821. volatile int sq_head; /* Head of the socket queue */
  822. volatile int sq_tail; /* Tail of the socket queue */
  823. pthread_cond_t sq_full; /* Signaled when socket is produced */
  824. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  825. pthread_t masterthreadid; /* The master thread ID */
  826. int workerthreadcount; /* The amount of worker threads. */
  827. pthread_t *workerthreadids; /* The worker thread IDs */
  828. unsigned long start_time; /* Server start time, used for authentication */
  829. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  830. unsigned long nonce_count; /* Used nonces, used for authentication */
  831. char *systemName; /* What operating system is running */
  832. /* linked list of uri handlers */
  833. struct mg_request_handler_info *request_handlers;
  834. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  835. /* linked list of shared lua websockets */
  836. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  837. #endif
  838. #ifdef USE_TIMERS
  839. struct ttimers *timers;
  840. #endif
  841. };
  842. struct mg_connection {
  843. struct mg_request_info request_info;
  844. struct mg_context *ctx;
  845. SSL *ssl; /* SSL descriptor */
  846. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  847. struct socket client; /* Connected client */
  848. time_t conn_birth_time; /* Time (wall clock) when connection was
  849. established */
  850. struct timespec
  851. req_time; /* Time (since system start) when the request was received */
  852. int64_t num_bytes_sent; /* Total bytes sent to client */
  853. int64_t content_len; /* Content-Length header value */
  854. int64_t consumed_content; /* How many bytes of content have been read */
  855. int is_chunked; /* Transfer-encoding is chunked: 0=no, 1=yes: data
  856. available,
  857. 2: all data read */
  858. size_t chunk_remainder; /* Unread data from the last chunk */
  859. char *buf; /* Buffer for received data */
  860. char *path_info; /* PATH_INFO part of the URL */
  861. int must_close; /* 1 if connection must be closed */
  862. int in_error_handler; /* 1 if in handler for user defined error pages */
  863. int buf_size; /* Buffer size */
  864. int request_len; /* Size of the request + headers in a buffer */
  865. int data_len; /* Total size of data in a buffer */
  866. int status_code; /* HTTP reply status code, e.g. 200 */
  867. int throttle; /* Throttling, bytes/sec. <= 0 means no throttle */
  868. time_t last_throttle_time; /* Last time throttled data was sent */
  869. int64_t last_throttle_bytes; /* Bytes sent this second */
  870. pthread_mutex_t mutex; /* Used by mg_lock_connection/mg_unlock_connection to
  871. ensure atomic transmissions for websockets */
  872. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  873. void *lua_websocket_state; /* Lua_State for a websocket connection */
  874. #endif
  875. };
  876. static pthread_key_t sTlsKey; /* Thread local storage index */
  877. static int sTlsInit = 0;
  878. struct mg_workerTLS {
  879. int is_master;
  880. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  881. HANDLE pthread_cond_helper_mutex;
  882. #endif
  883. };
  884. /* Directory entry */
  885. struct de {
  886. struct mg_connection *conn;
  887. char *file_name;
  888. struct file file;
  889. };
  890. #if defined(USE_WEBSOCKET)
  891. static int is_websocket_protocol(const struct mg_connection *conn);
  892. #else
  893. #define is_websocket_protocol(conn) (0)
  894. #endif
  895. int mg_atomic_inc(volatile int *addr) {
  896. int ret;
  897. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  898. /* Depending on the SDK, this function uses either
  899. * (volatile unsigned int *) or (volatile LONG *),
  900. * so whatever you use, the other SDK is likely to raise a warning. */
  901. ret = InterlockedIncrement((volatile unsigned int *)addr);
  902. #elif defined(__GNUC__)
  903. ret = __sync_add_and_fetch(addr, 1);
  904. #else
  905. ret = (++(*addr));
  906. #endif
  907. return ret;
  908. }
  909. int mg_atomic_dec(volatile int *addr) {
  910. int ret;
  911. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  912. /* Depending on the SDK, this function uses either
  913. * (volatile unsigned int *) or (volatile LONG *),
  914. * so whatever you use, the other SDK is likely to raise a warning. */
  915. ret = InterlockedDecrement((volatile unsigned int *)addr);
  916. #elif defined(__GNUC__)
  917. ret = __sync_sub_and_fetch(addr, 1);
  918. #else
  919. ret = (--(*addr));
  920. #endif
  921. return ret;
  922. }
  923. #if !defined(NO_THREAD_NAME)
  924. #if defined(_WIN32) && defined(_MSC_VER)
  925. /* Set the thread name for debugging purposes in Visual Studio
  926. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  927. */
  928. #pragma pack(push, 8)
  929. typedef struct tagTHREADNAME_INFO {
  930. DWORD dwType; /* Must be 0x1000. */
  931. LPCSTR szName; /* Pointer to name (in user addr space). */
  932. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  933. DWORD dwFlags; /* Reserved for future use, must be zero. */
  934. } THREADNAME_INFO;
  935. #pragma pack(pop)
  936. #elif defined(__linux__)
  937. #include <sys/prctl.h>
  938. #endif
  939. void mg_set_thread_name(const char *name) {
  940. char threadName[16]; /* Max. thread length in Linux/OSX/.. */
  941. /* TODO: use strcpy and strcat instad of snprintf, use server name, don't return */
  942. if (snprintf(threadName, sizeof(threadName), "civetweb-%s", name) < 0)
  943. return;
  944. threadName[sizeof(threadName) - 1] = 0;
  945. #if defined(_WIN32)
  946. #if defined(_MSC_VER)
  947. /* Windows and Visual Studio Compiler */
  948. __try {
  949. THREADNAME_INFO info;
  950. info.dwType = 0x1000;
  951. info.szName = threadName;
  952. info.dwThreadID = -1;
  953. info.dwFlags = 0;
  954. RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR),
  955. (ULONG_PTR *)&info);
  956. }
  957. __except(EXCEPTION_EXECUTE_HANDLER) {}
  958. #elif defined(__MINGW32__)
  959. /* No option known to set thread name for MinGW */
  960. ;
  961. #endif
  962. #elif defined(__linux__)
  963. /* Linux */
  964. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  965. #elif defined(__APPLE__) || defined(__MACH__)
  966. /* OS X (TODO: test) */
  967. (void)pthread_setname_np(threadName);
  968. #elif defined(BSD) || defined(__FreeBSD__) || defined(__OpenBSD__)
  969. /* BSD (TODO: test) */
  970. pthread_set_name_np(pthread_self(), threadName);
  971. #elif defined(__AIX__) || defined(_AIX) || defined(__hpux) || defined(__sun)
  972. /* pthread_set_name_np seems to be missing on AIX, hpux, sun, ... */
  973. #else
  974. /* POSIX */
  975. (void)pthread_setname_np(pthread_self(), threadName);
  976. #endif
  977. }
  978. #else /* !defined(NO_THREAD_NAME) */
  979. void mg_set_thread_name(const char *threadName) {}
  980. #endif
  981. #if defined(MG_LEGACY_INTERFACE)
  982. const char **mg_get_valid_option_names(void) {
  983. static const char *
  984. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  985. int i;
  986. for (i = 0; config_options[i].name != NULL; i++) {
  987. data[i * 2] = config_options[i].name;
  988. data[i * 2 + 1] = config_options[i].default_value;
  989. }
  990. return data;
  991. }
  992. #endif
  993. const struct mg_option *mg_get_valid_options(void) { return config_options; }
  994. static int is_file_in_memory(struct mg_connection *conn, const char *path,
  995. struct file *filep) {
  996. size_t size = 0;
  997. if (!conn || !filep)
  998. return 0;
  999. if ((filep->membuf =
  1000. conn->ctx->callbacks.open_file == NULL
  1001. ? NULL
  1002. : conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  1003. /* NOTE: override filep->size only on success. Otherwise, it might
  1004. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1005. filep->size = size;
  1006. }
  1007. return filep->membuf != NULL;
  1008. }
  1009. static int is_file_opened(const struct file *filep) {
  1010. if (!filep) {
  1011. return 0;
  1012. }
  1013. return filep->membuf != NULL || filep->fp != NULL;
  1014. }
  1015. static int mg_fopen(struct mg_connection *conn, const char *path,
  1016. const char *mode, struct file *filep) {
  1017. if (!filep) {
  1018. return 0;
  1019. }
  1020. if (!is_file_in_memory(conn, path, filep)) {
  1021. #ifdef _WIN32
  1022. wchar_t wbuf[PATH_MAX], wmode[20];
  1023. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1024. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1025. filep->fp = _wfopen(wbuf, wmode);
  1026. #else
  1027. filep->fp = fopen(path, mode);
  1028. #endif
  1029. }
  1030. return is_file_opened(filep);
  1031. }
  1032. static void mg_fclose(struct file *filep) {
  1033. if (filep != NULL && filep->fp != NULL) {
  1034. fclose(filep->fp);
  1035. }
  1036. }
  1037. static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
  1038. for (; *src != '\0' && n > 1; n--) {
  1039. *dst++ = *src++;
  1040. }
  1041. *dst = '\0';
  1042. }
  1043. static int lowercase(const char *s) {
  1044. return tolower(*(const unsigned char *)s);
  1045. }
  1046. int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  1047. int diff = 0;
  1048. if (len > 0)
  1049. do {
  1050. diff = lowercase(s1++) - lowercase(s2++);
  1051. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1052. return diff;
  1053. }
  1054. static int mg_strcasecmp(const char *s1, const char *s2) {
  1055. int diff;
  1056. do {
  1057. diff = lowercase(s1++) - lowercase(s2++);
  1058. } while (diff == 0 && s1[-1] != '\0');
  1059. return diff;
  1060. }
  1061. static char *mg_strndup(const char *ptr, size_t len) {
  1062. char *p;
  1063. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1064. mg_strlcpy(p, ptr, len + 1);
  1065. }
  1066. return p;
  1067. }
  1068. static char *mg_strdup(const char *str) { return mg_strndup(str, strlen(str)); }
  1069. static const char *mg_strcasestr(const char *big_str, const char *small_str) {
  1070. int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
  1071. for (i = 0; i <= big_len - small_len; i++) {
  1072. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1073. return big_str + i;
  1074. }
  1075. }
  1076. return NULL;
  1077. }
  1078. /* Like snprintf(), but never returns negative value, or a value
  1079. * that is larger than a supplied buffer.
  1080. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  1081. * in his audit report. */
  1082. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  1083. const char *fmt, va_list ap) {
  1084. int n;
  1085. if (buflen == 0)
  1086. return 0;
  1087. #ifdef __clang__
  1088. #pragma clang diagnostic push
  1089. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1090. /* Using fmt as a non-literal is intended here, since it is mostly called
  1091. * indirectly by mg_snprintf */
  1092. #endif
  1093. n = vsnprintf(buf, buflen, fmt, ap);
  1094. #ifdef __clang__
  1095. #pragma clang diagnostic pop
  1096. #endif
  1097. if (n < 0) {
  1098. mg_cry(conn, "vsnprintf error");
  1099. n = 0;
  1100. } else if (n >= (int)buflen) {
  1101. mg_cry(conn, "truncating vsnprintf buffer: [%.*s]", n > 200 ? 200 : n,
  1102. buf);
  1103. n = (int)buflen - 1;
  1104. }
  1105. buf[n] = '\0';
  1106. return n;
  1107. }
  1108. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  1109. PRINTF_FORMAT_STRING(const char *fmt), ...)
  1110. PRINTF_ARGS(4, 5);
  1111. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  1112. const char *fmt, ...) {
  1113. va_list ap;
  1114. int n;
  1115. va_start(ap, fmt);
  1116. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  1117. va_end(ap);
  1118. return n;
  1119. }
  1120. static int get_option_index(const char *name) {
  1121. int i;
  1122. for (i = 0; config_options[i].name != NULL; i++) {
  1123. if (strcmp(config_options[i].name, name) == 0) {
  1124. return i;
  1125. }
  1126. }
  1127. return -1;
  1128. }
  1129. const char *mg_get_option(const struct mg_context *ctx, const char *name) {
  1130. int i;
  1131. if ((i = get_option_index(name)) == -1) {
  1132. return NULL;
  1133. } else if (!ctx || ctx->config[i] == NULL) {
  1134. return "";
  1135. } else {
  1136. return ctx->config[i];
  1137. }
  1138. }
  1139. struct mg_context *mg_get_context(const struct mg_connection *conn) {
  1140. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1141. }
  1142. void *mg_get_user_data(const struct mg_context *ctx) {
  1143. return (ctx == NULL) ? NULL : ctx->user_data;
  1144. }
  1145. void mg_set_user_connection_data(const struct mg_connection *conn, void *data) {
  1146. if (conn != NULL) {
  1147. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1148. }
  1149. }
  1150. void *mg_get_user_connection_data(const struct mg_connection *conn) {
  1151. if (conn != NULL) {
  1152. return conn->request_info.conn_data;
  1153. }
  1154. return NULL;
  1155. }
  1156. size_t mg_get_ports(const struct mg_context *ctx, size_t size, int *ports,
  1157. int *ssl) {
  1158. size_t i;
  1159. if (!ctx) {
  1160. return 0;
  1161. }
  1162. for (i = 0; i < size && i < (size_t)ctx->num_listening_sockets; i++) {
  1163. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1164. ports[i] = ctx->listening_ports[i];
  1165. }
  1166. return i;
  1167. }
  1168. static void sockaddr_to_string(char *buf, size_t len, const union usa *usa) {
  1169. buf[0] = '\0';
  1170. if (usa->sa.sa_family == AF_INET) {
  1171. getnameinfo(&usa->sa, sizeof(usa->sin), buf, len, NULL, 0,
  1172. NI_NUMERICHOST);
  1173. }
  1174. #if defined(USE_IPV6)
  1175. else if (usa->sa.sa_family == AF_INET6) {
  1176. getnameinfo(&usa->sa, sizeof(usa->sin6), buf, len, NULL, 0,
  1177. NI_NUMERICHOST);
  1178. }
  1179. #endif
  1180. #if 0
  1181. // TODO: test alternative code, remove old code
  1182. #if defined(USE_IPV6)
  1183. mg_inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  1184. (void *) &usa->sin.sin_addr :
  1185. (void *) &usa->sin6.sin6_addr, buf, len);
  1186. #elif defined(_WIN32)
  1187. /* Only Windows Vista (and newer) have inet_ntop() */
  1188. mg_strlcpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  1189. #else
  1190. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, (socklen_t)len);
  1191. #endif
  1192. #endif
  1193. }
  1194. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1195. * included in all responses other than 100, 101, 5xx. */
  1196. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  1197. struct tm *tm;
  1198. tm = gmtime(t);
  1199. if (tm != NULL) {
  1200. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1201. } else {
  1202. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1203. buf[buf_len - 1] = '\0';
  1204. }
  1205. }
  1206. /* difftime for struct timespec. Return value is in seconds. */
  1207. static double mg_difftimespec(const struct timespec *ts_now,
  1208. const struct timespec *ts_before) {
  1209. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 +
  1210. (double)(ts_now->tv_sec - ts_before->tv_sec);
  1211. }
  1212. /* Print error message to the opened error log stream. */
  1213. void mg_cry(const struct mg_connection *conn, const char *fmt, ...) {
  1214. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1215. va_list ap;
  1216. FILE *fp;
  1217. time_t timestamp;
  1218. va_start(ap, fmt);
  1219. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  1220. va_end(ap);
  1221. /* Do not lock when getting the callback value, here and below.
  1222. * I suppose this is fine, since function cannot disappear in the
  1223. * same way string option can. */
  1224. if (conn && (conn->ctx->callbacks.log_message == NULL ||
  1225. conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1226. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1227. ? NULL
  1228. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1229. if (fp != NULL) {
  1230. flockfile(fp);
  1231. timestamp = time(NULL);
  1232. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1233. fprintf(fp, "[%010lu] [error] [client %s] ",
  1234. (unsigned long)timestamp, src_addr);
  1235. if (conn->request_info.request_method != NULL) {
  1236. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  1237. conn->request_info.uri);
  1238. }
  1239. fprintf(fp, "%s", buf);
  1240. fputc('\n', fp);
  1241. funlockfile(fp);
  1242. fclose(fp);
  1243. }
  1244. }
  1245. }
  1246. /* Return fake connection structure. Used for logging, if connection
  1247. * is not applicable at the moment of logging. */
  1248. static struct mg_connection *fc(struct mg_context *ctx) {
  1249. static struct mg_connection fake_connection;
  1250. fake_connection.ctx = ctx;
  1251. return &fake_connection;
  1252. }
  1253. const char *mg_version(void) { return CIVETWEB_VERSION; }
  1254. const struct mg_request_info *
  1255. mg_get_request_info(const struct mg_connection *conn) {
  1256. if (!conn) {
  1257. return NULL;
  1258. }
  1259. return &conn->request_info;
  1260. }
  1261. /* Skip the characters until one of the delimiters characters found.
  1262. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1263. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1264. * Delimiters can be quoted with quotechar. */
  1265. static char *skip_quoted(char **buf, const char *delimiters,
  1266. const char *whitespace, char quotechar) {
  1267. char *p, *begin_word, *end_word, *end_whitespace;
  1268. begin_word = *buf;
  1269. end_word = begin_word + strcspn(begin_word, delimiters);
  1270. /* Check for quotechar */
  1271. if (end_word > begin_word) {
  1272. p = end_word - 1;
  1273. while (*p == quotechar) {
  1274. /* TODO (bel): it seems this code is never reached, so quotechar is
  1275. * actually not needed - check if this code may be droped */
  1276. /* If there is anything beyond end_word, copy it */
  1277. if (*end_word == '\0') {
  1278. *p = '\0';
  1279. break;
  1280. } else {
  1281. size_t end_off = strcspn(end_word + 1, delimiters);
  1282. memmove(p, end_word, end_off + 1);
  1283. p += end_off; /* p must correspond to end_word - 1 */
  1284. end_word += end_off + 1;
  1285. }
  1286. }
  1287. for (p++; p < end_word; p++) {
  1288. *p = '\0';
  1289. }
  1290. }
  1291. if (*end_word == '\0') {
  1292. *buf = end_word;
  1293. } else {
  1294. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1295. for (p = end_word; p < end_whitespace; p++) {
  1296. *p = '\0';
  1297. }
  1298. *buf = end_whitespace;
  1299. }
  1300. return begin_word;
  1301. }
  1302. /* Simplified version of skip_quoted without quote char
  1303. * and whitespace == delimiters */
  1304. static char *skip(char **buf, const char *delimiters) {
  1305. return skip_quoted(buf, delimiters, delimiters, 0);
  1306. }
  1307. /* Return HTTP header value, or NULL if not found. */
  1308. static const char *get_header(const struct mg_request_info *ri,
  1309. const char *name) {
  1310. int i;
  1311. if (ri) {
  1312. for (i = 0; i < ri->num_headers; i++) {
  1313. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1314. return ri->http_headers[i].value;
  1315. }
  1316. }
  1317. }
  1318. return NULL;
  1319. }
  1320. const char *mg_get_header(const struct mg_connection *conn, const char *name) {
  1321. if (!conn) {
  1322. return NULL;
  1323. }
  1324. return get_header(&conn->request_info, name);
  1325. }
  1326. /* A helper function for traversing a comma separated list of values.
  1327. * It returns a list pointer shifted to the next value, or NULL if the end
  1328. * of the list found.
  1329. * Value is stored in val vector. If value has form "x=y", then eq_val
  1330. * vector is initialized to point to the "y" part, and val vector length
  1331. * is adjusted to point only to "x". */
  1332. static const char *next_option(const char *list, struct vec *val,
  1333. struct vec *eq_val) {
  1334. if (val == NULL || list == NULL || *list == '\0') {
  1335. /* End of the list */
  1336. list = NULL;
  1337. } else {
  1338. val->ptr = list;
  1339. if ((list = strchr(val->ptr, ',')) != NULL) {
  1340. /* Comma found. Store length and shift the list ptr */
  1341. val->len = list - val->ptr;
  1342. list++;
  1343. } else {
  1344. /* This value is the last one */
  1345. list = val->ptr + strlen(val->ptr);
  1346. val->len = list - val->ptr;
  1347. }
  1348. if (eq_val != NULL) {
  1349. /* Value has form "x=y", adjust pointers and lengths
  1350. * so that val points to "x", and eq_val points to "y". */
  1351. eq_val->len = 0;
  1352. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1353. if (eq_val->ptr != NULL) {
  1354. eq_val->ptr++; /* Skip over '=' character */
  1355. eq_val->len = val->ptr + val->len - eq_val->ptr;
  1356. val->len = (eq_val->ptr - val->ptr) - 1;
  1357. }
  1358. }
  1359. }
  1360. return list;
  1361. }
  1362. /* Perform case-insensitive match of string against pattern */
  1363. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  1364. const char *or_str;
  1365. int i, j, len, res;
  1366. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1367. res = match_prefix(pattern, (int)(or_str - pattern), str);
  1368. return res > 0
  1369. ? res
  1370. : match_prefix(or_str + 1,
  1371. (int)((pattern + pattern_len) - (or_str + 1)),
  1372. str);
  1373. }
  1374. i = j = 0;
  1375. for (; i < pattern_len; i++, j++) {
  1376. if (pattern[i] == '?' && str[j] != '\0') {
  1377. continue;
  1378. } else if (pattern[i] == '$') {
  1379. return str[j] == '\0' ? j : -1;
  1380. } else if (pattern[i] == '*') {
  1381. i++;
  1382. if (pattern[i] == '*') {
  1383. i++;
  1384. len = (int)strlen(str + j);
  1385. } else {
  1386. len = (int)strcspn(str + j, "/");
  1387. }
  1388. if (i == pattern_len) {
  1389. return j + len;
  1390. }
  1391. do {
  1392. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1393. } while (res == -1 && len-- > 0);
  1394. return res == -1 ? -1 : j + res + len;
  1395. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1396. return -1;
  1397. }
  1398. }
  1399. return j;
  1400. }
  1401. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1402. * This function must tolerate situations when connection info is not
  1403. * set up, for example if request parsing failed. */
  1404. static int should_keep_alive(const struct mg_connection *conn) {
  1405. if (conn != NULL) {
  1406. const char *http_version = conn->request_info.http_version;
  1407. const char *header = mg_get_header(conn, "Connection");
  1408. if (conn->must_close || conn->status_code == 401 ||
  1409. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1410. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1411. (header == NULL && http_version &&
  1412. 0 != strcmp(http_version, "1.1"))) {
  1413. return 0;
  1414. }
  1415. return 1;
  1416. }
  1417. return 0;
  1418. }
  1419. static int should_decode_url(const struct mg_connection *conn) {
  1420. if (!conn || !conn->ctx) {
  1421. return 0;
  1422. }
  1423. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1424. }
  1425. static const char *suggest_connection_header(const struct mg_connection *conn) {
  1426. return should_keep_alive(conn) ? "keep-alive" : "close";
  1427. }
  1428. static void handle_file_based_request(struct mg_connection *conn,
  1429. const char *path, struct file *filep);
  1430. static int mg_stat(struct mg_connection *conn, const char *path,
  1431. struct file *filep);
  1432. static const char *mg_get_response_code_text(int response_code,
  1433. struct mg_connection *conn) {
  1434. switch (response_code) {
  1435. /* RFC2616 Section 10.1 - Informational 1xx */
  1436. case 100:
  1437. return "Continue"; /* RFC2616 Section 10.1.1 */
  1438. case 101:
  1439. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1440. case 102:
  1441. return "Processing"; /* RFC2518 Section 10.1 */
  1442. /* RFC2616 Section 10.2 - Successful 2xx */
  1443. case 200:
  1444. return "OK"; /* RFC2616 Section 10.2.1 */
  1445. case 201:
  1446. return "Created"; /* RFC2616 Section 10.2.2 */
  1447. case 202:
  1448. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1449. case 203:
  1450. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1451. case 204:
  1452. return "No Content"; /* RFC2616 Section 10.2.5 */
  1453. case 205:
  1454. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1455. case 206:
  1456. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1457. case 207:
  1458. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1459. /* RFC2616 Section 10.3 - Redirection 3xx */
  1460. case 300:
  1461. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1462. case 301:
  1463. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1464. case 302:
  1465. return "Found"; /* RFC2616 Section 10.3.3 */
  1466. case 303:
  1467. return "See Other"; /* RFC2616 Section 10.3.4 */
  1468. case 304:
  1469. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1470. case 305:
  1471. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1472. case 307:
  1473. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1474. /* RFC2616 Section 10.4 - Client Error 4xx */
  1475. case 400:
  1476. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1477. case 401:
  1478. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1479. case 402:
  1480. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1481. case 403:
  1482. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1483. case 404:
  1484. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1485. case 405:
  1486. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1487. case 406:
  1488. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1489. case 407:
  1490. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1491. case 408:
  1492. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1493. case 409:
  1494. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1495. case 410:
  1496. return "Gone"; /* RFC2616 Section 10.4.11 */
  1497. case 411:
  1498. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1499. case 412:
  1500. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1501. case 413:
  1502. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1503. case 414:
  1504. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1505. case 415:
  1506. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1507. case 416:
  1508. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1509. case 417:
  1510. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1511. case 422:
  1512. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1513. Section
  1514. 11.2 */
  1515. case 423:
  1516. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1517. case 424:
  1518. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918 Section
  1519. * 11.4 */
  1520. case 428:
  1521. return "Precondition Required"; /* RFC 6585, Section 3 */
  1522. case 429:
  1523. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1524. case 431:
  1525. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1526. /* RFC2616 Section 10.5 - Server Error 5xx */
  1527. case 500:
  1528. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1529. case 501:
  1530. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1531. case 502:
  1532. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1533. case 503:
  1534. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1535. case 504:
  1536. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1537. case 505:
  1538. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1539. case 507:
  1540. return "Insufficient Storage"; /* RFC2518 Section 10.6, , RFC4918
  1541. Section
  1542. 11.5 */
  1543. case 511:
  1544. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1545. /* Other RFCs */
  1546. case 426:
  1547. return "Upgrade Required"; /* RFC 2817 */
  1548. /* Return codes from non normative RFCs: */
  1549. /* Informative and experimental RFCs, "de facto" standards due to common
  1550. * use, ... */
  1551. case 208:
  1552. return "Already Reported"; /* RFC5842 Section 7.1 */
  1553. case 226:
  1554. return "IM used"; /* RFC3229 Section 10.4.1 */
  1555. case 308:
  1556. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1557. case 418:
  1558. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1559. case 419:
  1560. return "Authentication Timeout"; /* common use */
  1561. case 451:
  1562. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1563. Section 3 */
  1564. case 506:
  1565. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1566. case 508:
  1567. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1568. case 510:
  1569. return "Not Extended"; /* RFC 2774, Section 7 */
  1570. default:
  1571. /* This error code is unknown. This should not happen. */
  1572. if (conn) {
  1573. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1574. }
  1575. /* Return at least a category according to RFC 2616 Section 10. */
  1576. if (response_code >= 100 && response_code < 200) {
  1577. /* Unknown informational status code */
  1578. return "Information";
  1579. }
  1580. if (response_code >= 200 && response_code < 300) {
  1581. /* Unknown success code */
  1582. return "Success";
  1583. }
  1584. if (response_code >= 300 && response_code < 400) {
  1585. /* Unknown redirection code */
  1586. return "Redirection";
  1587. }
  1588. if (response_code >= 400 && response_code < 500) {
  1589. /* Unknown request error code */
  1590. return "Client Error";
  1591. }
  1592. if (response_code >= 500 && response_code < 600) {
  1593. /* Unknown server error code */
  1594. return "Server Error";
  1595. }
  1596. /* Response code not even within reasonable range */
  1597. return "";
  1598. }
  1599. }
  1600. static void send_http_error(struct mg_connection *, int,
  1601. PRINTF_FORMAT_STRING(const char *fmt), ...)
  1602. PRINTF_ARGS(3, 4);
  1603. static void send_http_error(struct mg_connection *conn, int status,
  1604. const char *fmt, ...) {
  1605. char buf[MG_BUF_LEN];
  1606. va_list ap;
  1607. int len = 0, i, page_handler_found, scope;
  1608. char date[64];
  1609. time_t curtime = time(NULL);
  1610. const char *error_handler = NULL;
  1611. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1612. const char *error_page_file_ext, *tstr;
  1613. const char *status_text = mg_get_response_code_text(status, conn);
  1614. if (conn == NULL) {
  1615. return;
  1616. }
  1617. conn->status_code = status;
  1618. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL ||
  1619. conn->ctx->callbacks.http_error(conn, status)) {
  1620. if (!conn->in_error_handler) {
  1621. /* Send user defined error pages, if defined */
  1622. error_handler = conn->ctx->config[ERROR_PAGES];
  1623. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1624. page_handler_found = 0;
  1625. if (error_handler != NULL) {
  1626. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1627. switch (scope) {
  1628. case 1:
  1629. len =
  1630. mg_snprintf(conn, buf, sizeof(buf) - 32,
  1631. "%serror%03u.", error_handler, status);
  1632. break;
  1633. case 2:
  1634. len = mg_snprintf(conn, buf, sizeof(buf) - 32,
  1635. "%serror%01uxx.", error_handler,
  1636. status / 100);
  1637. break;
  1638. default:
  1639. len = mg_snprintf(conn, buf, sizeof(buf) - 32,
  1640. "%serror.", error_handler);
  1641. break;
  1642. }
  1643. tstr = strchr(error_page_file_ext, '.');
  1644. while (tstr) {
  1645. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  1646. i++)
  1647. buf[len + i - 1] = tstr[i];
  1648. buf[len + i - 1] = 0;
  1649. if (mg_stat(conn, buf, &error_page_file)) {
  1650. page_handler_found = 1;
  1651. break;
  1652. }
  1653. tstr = strchr(tstr + i, '.');
  1654. }
  1655. }
  1656. }
  1657. if (page_handler_found) {
  1658. conn->in_error_handler = 1;
  1659. handle_file_based_request(conn, buf, &error_page_file);
  1660. conn->in_error_handler = 0;
  1661. return;
  1662. }
  1663. }
  1664. buf[0] = '\0';
  1665. gmt_time_string(date, sizeof(date), &curtime);
  1666. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1667. if (status > 199 && status != 204 && status != 304) {
  1668. len = mg_snprintf(conn, buf, sizeof(buf) - 1, "Error %d: %s",
  1669. status, status_text);
  1670. buf[len] = '\n';
  1671. len++;
  1672. buf[len] = 0;
  1673. va_start(ap, fmt);
  1674. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  1675. va_end(ap);
  1676. }
  1677. DEBUG_TRACE("[%s]", buf);
  1678. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  1679. if (len > 0) {
  1680. mg_printf(conn, "Content-Type: text/plain\r\n");
  1681. }
  1682. mg_printf(conn, "Content-Length: %d\r\n"
  1683. "Date: %s\r\n"
  1684. "Connection: %s\r\n\r\n",
  1685. len, date, suggest_connection_header(conn));
  1686. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  1687. }
  1688. }
  1689. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1690. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
  1691. (void)unused;
  1692. *mutex = CreateMutex(NULL, FALSE, NULL);
  1693. return *mutex == NULL ? -1 : 0;
  1694. }
  1695. static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
  1696. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1697. }
  1698. static int pthread_mutex_lock(pthread_mutex_t *mutex) {
  1699. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  1700. }
  1701. static int pthread_mutex_trylock(pthread_mutex_t *mutex) {
  1702. switch (WaitForSingleObject(*mutex, 0)) {
  1703. case WAIT_OBJECT_0:
  1704. return 0;
  1705. case WAIT_TIMEOUT:
  1706. return -2; /* EBUSY */
  1707. }
  1708. return -1;
  1709. }
  1710. static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
  1711. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1712. }
  1713. #ifndef WIN_PTHREADS_TIME_H
  1714. static int clock_gettime(clockid_t clk_id, struct timespec *tp) {
  1715. FILETIME ft;
  1716. ULARGE_INTEGER li;
  1717. BOOL ok = FALSE;
  1718. double d;
  1719. static double perfcnt_per_sec = 0.0;
  1720. if (tp) {
  1721. if (clk_id == CLOCK_REALTIME) {
  1722. GetSystemTimeAsFileTime(&ft);
  1723. li.LowPart = ft.dwLowDateTime;
  1724. li.HighPart = ft.dwHighDateTime;
  1725. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1726. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1727. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1728. ok = TRUE;
  1729. } else if (clk_id == CLOCK_MONOTONIC) {
  1730. if (perfcnt_per_sec == 0.0) {
  1731. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  1732. perfcnt_per_sec = 1.0 / li.QuadPart;
  1733. }
  1734. if (perfcnt_per_sec != 0.0) {
  1735. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  1736. d = li.QuadPart * perfcnt_per_sec;
  1737. tp->tv_sec = (time_t)d;
  1738. d -= tp->tv_sec;
  1739. tp->tv_nsec = (long)(d * 1.0E9);
  1740. ok = TRUE;
  1741. }
  1742. }
  1743. }
  1744. return ok ? 0 : -1;
  1745. }
  1746. #endif
  1747. static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
  1748. (void)unused;
  1749. InitializeCriticalSection(&cv->threadIdSec);
  1750. cv->waitingthreadcount = 0;
  1751. cv->waitingthreadhdls =
  1752. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1753. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  1754. }
  1755. static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex,
  1756. const struct timespec *abstime) {
  1757. struct mg_workerTLS *tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1758. int ok;
  1759. struct timespec tsnow;
  1760. int64_t nsnow, nswaitabs, nswaitrel;
  1761. DWORD mswaitrel;
  1762. EnterCriticalSection(&cv->threadIdSec);
  1763. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1764. cv->waitingthreadhdls[cv->waitingthreadcount] =
  1765. tls->pthread_cond_helper_mutex;
  1766. cv->waitingthreadcount++;
  1767. LeaveCriticalSection(&cv->threadIdSec);
  1768. if (abstime) {
  1769. clock_gettime(CLOCK_REALTIME, &tsnow);
  1770. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  1771. nswaitabs =
  1772. (((uint64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  1773. nswaitrel = nswaitabs - nsnow;
  1774. if (nswaitrel < 0)
  1775. nswaitrel = 0;
  1776. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1777. } else {
  1778. mswaitrel = INFINITE;
  1779. }
  1780. pthread_mutex_unlock(mutex);
  1781. ok = (WAIT_OBJECT_0 ==
  1782. WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1783. pthread_mutex_lock(mutex);
  1784. return ok ? 0 : -1;
  1785. }
  1786. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
  1787. return pthread_cond_timedwait(cv, mutex, NULL);
  1788. }
  1789. static int pthread_cond_signal(pthread_cond_t *cv) {
  1790. int i;
  1791. HANDLE wkup = NULL;
  1792. BOOL ok = FALSE;
  1793. EnterCriticalSection(&cv->threadIdSec);
  1794. if (cv->waitingthreadcount) {
  1795. wkup = cv->waitingthreadhdls[0];
  1796. ok = SetEvent(wkup);
  1797. for (i = 1; i < cv->waitingthreadcount; i++) {
  1798. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  1799. }
  1800. cv->waitingthreadcount--;
  1801. assert(ok);
  1802. }
  1803. LeaveCriticalSection(&cv->threadIdSec);
  1804. return ok ? 0 : 1;
  1805. }
  1806. static int pthread_cond_broadcast(pthread_cond_t *cv) {
  1807. EnterCriticalSection(&cv->threadIdSec);
  1808. while (cv->waitingthreadcount) {
  1809. pthread_cond_signal(cv);
  1810. }
  1811. LeaveCriticalSection(&cv->threadIdSec);
  1812. return 0;
  1813. }
  1814. static int pthread_cond_destroy(pthread_cond_t *cv) {
  1815. EnterCriticalSection(&cv->threadIdSec);
  1816. assert(cv->waitingthreadcount == 0);
  1817. mg_free(cv->waitingthreadhdls);
  1818. cv->waitingthreadhdls = 0;
  1819. LeaveCriticalSection(&cv->threadIdSec);
  1820. DeleteCriticalSection(&cv->threadIdSec);
  1821. return 0;
  1822. }
  1823. /* For Windows, change all slashes to backslashes in path names. */
  1824. static void change_slashes_to_backslashes(char *path) {
  1825. int i;
  1826. for (i = 0; path[i] != '\0'; i++) {
  1827. if (path[i] == '/') {
  1828. path[i] = '\\';
  1829. }
  1830. /* remove double backslash (check i > 0 to preserve UNC paths,
  1831. * like \\server\file.txt) */
  1832. if ((path[i] == '\\') && (i > 0)) {
  1833. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  1834. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  1835. }
  1836. }
  1837. }
  1838. }
  1839. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1840. * wbuf and wbuf_len is a target buffer and its length. */
  1841. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1842. char buf[PATH_MAX], buf2[PATH_MAX];
  1843. mg_strlcpy(buf, path, sizeof(buf));
  1844. change_slashes_to_backslashes(buf);
  1845. /* Convert to Unicode and back. If doubly-converted string does not
  1846. * match the original, something is fishy, reject. */
  1847. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1848. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  1849. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2),
  1850. NULL, NULL);
  1851. if (strcmp(buf, buf2) != 0) {
  1852. wbuf[0] = L'\0';
  1853. }
  1854. }
  1855. #if defined(_WIN32_WCE)
  1856. static time_t time(time_t *ptime) {
  1857. time_t t;
  1858. SYSTEMTIME st;
  1859. FILETIME ft;
  1860. GetSystemTime(&st);
  1861. SystemTimeToFileTime(&st, &ft);
  1862. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1863. if (ptime != NULL) {
  1864. *ptime = t;
  1865. }
  1866. return t;
  1867. }
  1868. static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
  1869. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  1870. FILETIME ft, lft;
  1871. SYSTEMTIME st;
  1872. TIME_ZONE_INFORMATION tzinfo;
  1873. if (ptm == NULL) {
  1874. return NULL;
  1875. }
  1876. *(int64_t *)&ft = t;
  1877. FileTimeToLocalFileTime(&ft, &lft);
  1878. FileTimeToSystemTime(&lft, &st);
  1879. ptm->tm_year = st.wYear - 1900;
  1880. ptm->tm_mon = st.wMonth - 1;
  1881. ptm->tm_wday = st.wDayOfWeek;
  1882. ptm->tm_mday = st.wDay;
  1883. ptm->tm_hour = st.wHour;
  1884. ptm->tm_min = st.wMinute;
  1885. ptm->tm_sec = st.wSecond;
  1886. ptm->tm_yday = 0; /* hope nobody uses this */
  1887. ptm->tm_isdst =
  1888. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1889. return ptm;
  1890. }
  1891. static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
  1892. /* FIXME(lsm): fix this. */
  1893. return localtime(ptime, ptm);
  1894. }
  1895. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1896. const struct tm *tm) {
  1897. (void)snprintf(dst, dst_size, "implement strftime() for WinCE");
  1898. return 0;
  1899. }
  1900. #endif
  1901. /* Windows happily opens files with some garbage at the end of file name.
  1902. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  1903. * "a.cgi", despite one would expect an error back.
  1904. * This function returns non-0 if path ends with some garbage. */
  1905. static int path_cannot_disclose_cgi(const char *path) {
  1906. static const char *allowed_last_characters = "_-";
  1907. int last = path[strlen(path) - 1];
  1908. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  1909. }
  1910. static int mg_stat(struct mg_connection *conn, const char *path,
  1911. struct file *filep) {
  1912. wchar_t wbuf[PATH_MAX];
  1913. WIN32_FILE_ATTRIBUTE_DATA info;
  1914. if (!is_file_in_memory(conn, path, filep)) {
  1915. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1916. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1917. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1918. filep->modification_time =
  1919. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  1920. info.ftLastWriteTime.dwHighDateTime);
  1921. filep->is_directory =
  1922. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1923. /* If file name is fishy, reset the file structure and return
  1924. * error.
  1925. * Note it is important to reset, not just return the error, cause
  1926. * functions like is_file_opened() check the struct. */
  1927. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  1928. memset(filep, 0, sizeof(*filep));
  1929. }
  1930. }
  1931. }
  1932. return filep->membuf != NULL || filep->modification_time != 0;
  1933. }
  1934. static int mg_remove(const char *path) {
  1935. wchar_t wbuf[PATH_MAX];
  1936. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1937. return DeleteFileW(wbuf) ? 0 : -1;
  1938. }
  1939. static int mg_mkdir(const char *path, int mode) {
  1940. char buf[PATH_MAX];
  1941. wchar_t wbuf[PATH_MAX];
  1942. (void)mode;
  1943. mg_strlcpy(buf, path, sizeof(buf));
  1944. change_slashes_to_backslashes(buf);
  1945. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  1946. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1947. }
  1948. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  1949. static DIR *opendir(const char *name) {
  1950. DIR *dir = NULL;
  1951. wchar_t wpath[PATH_MAX];
  1952. DWORD attrs;
  1953. if (name == NULL) {
  1954. SetLastError(ERROR_BAD_ARGUMENTS);
  1955. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  1956. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1957. } else {
  1958. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1959. attrs = GetFileAttributesW(wpath);
  1960. if (attrs != 0xFFFFFFFF &&
  1961. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1962. (void)wcscat(wpath, L"\\*");
  1963. dir->handle = FindFirstFileW(wpath, &dir->info);
  1964. dir->result.d_name[0] = '\0';
  1965. } else {
  1966. mg_free(dir);
  1967. dir = NULL;
  1968. }
  1969. }
  1970. return dir;
  1971. }
  1972. static int closedir(DIR *dir) {
  1973. int result = 0;
  1974. if (dir != NULL) {
  1975. if (dir->handle != INVALID_HANDLE_VALUE)
  1976. result = FindClose(dir->handle) ? 0 : -1;
  1977. mg_free(dir);
  1978. } else {
  1979. result = -1;
  1980. SetLastError(ERROR_BAD_ARGUMENTS);
  1981. }
  1982. return result;
  1983. }
  1984. static struct dirent *readdir(DIR *dir) {
  1985. struct dirent *result = 0;
  1986. if (dir) {
  1987. if (dir->handle != INVALID_HANDLE_VALUE) {
  1988. result = &dir->result;
  1989. (void)WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
  1990. result->d_name, sizeof(result->d_name),
  1991. NULL, NULL);
  1992. if (!FindNextFileW(dir->handle, &dir->info)) {
  1993. (void)FindClose(dir->handle);
  1994. dir->handle = INVALID_HANDLE_VALUE;
  1995. }
  1996. } else {
  1997. SetLastError(ERROR_FILE_NOT_FOUND);
  1998. }
  1999. } else {
  2000. SetLastError(ERROR_BAD_ARGUMENTS);
  2001. }
  2002. return result;
  2003. }
  2004. #ifndef HAVE_POLL
  2005. static int poll(struct pollfd *pfd, int n, int milliseconds) {
  2006. struct timeval tv;
  2007. fd_set set;
  2008. int i, result;
  2009. SOCKET maxfd = 0;
  2010. tv.tv_sec = milliseconds / 1000;
  2011. tv.tv_usec = (milliseconds % 1000) * 1000;
  2012. FD_ZERO(&set);
  2013. for (i = 0; i < n; i++) {
  2014. FD_SET((SOCKET)pfd[i].fd, &set);
  2015. pfd[i].revents = 0;
  2016. if (pfd[i].fd > maxfd) {
  2017. maxfd = pfd[i].fd;
  2018. }
  2019. }
  2020. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2021. for (i = 0; i < n; i++) {
  2022. if (FD_ISSET(pfd[i].fd, &set)) {
  2023. pfd[i].revents = POLLIN;
  2024. }
  2025. }
  2026. }
  2027. return result;
  2028. }
  2029. #endif /* HAVE_POLL */
  2030. static void set_close_on_exec(SOCKET sock,
  2031. struct mg_connection *conn /* may be null */) {
  2032. (void)conn; /* Unused. */
  2033. (void)SetHandleInformation((HANDLE)sock, HANDLE_FLAG_INHERIT, 0);
  2034. }
  2035. int mg_start_thread(mg_thread_func_t f, void *p) {
  2036. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2037. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2038. */
  2039. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2040. ((uintptr_t)(-1L)))
  2041. ? -1
  2042. : 0);
  2043. #else
  2044. return (
  2045. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2046. ? -1
  2047. : 0);
  2048. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2049. }
  2050. /* Start a thread storing the thread context. */
  2051. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *), void *p,
  2052. pthread_t *threadidptr) {
  2053. uintptr_t uip;
  2054. HANDLE threadhandle;
  2055. int result = -1;
  2056. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2057. threadhandle = (HANDLE)uip;
  2058. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2059. *threadidptr = threadhandle;
  2060. result = 0;
  2061. }
  2062. return result;
  2063. }
  2064. /* Wait for a thread to finish. */
  2065. static int mg_join_thread(pthread_t threadid) {
  2066. int result;
  2067. DWORD dwevent;
  2068. result = -1;
  2069. dwevent = WaitForSingleObject(threadid, INFINITE);
  2070. if (dwevent == WAIT_FAILED) {
  2071. int err = GetLastError();
  2072. (void)err;
  2073. DEBUG_TRACE("WaitForSingleObject() failed, error %d", err);
  2074. } else {
  2075. if (dwevent == WAIT_OBJECT_0) {
  2076. CloseHandle(threadid);
  2077. result = 0;
  2078. }
  2079. }
  2080. return result;
  2081. }
  2082. static HANDLE dlopen(const char *dll_name, int flags) {
  2083. wchar_t wbuf[PATH_MAX];
  2084. (void)flags;
  2085. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2086. return LoadLibraryW(wbuf);
  2087. }
  2088. static int dlclose(void *handle) {
  2089. int result;
  2090. if (FreeLibrary((HMODULE)handle) != 0) {
  2091. result = 0;
  2092. } else {
  2093. result = -1;
  2094. }
  2095. return result;
  2096. }
  2097. #if !defined(NO_CGI)
  2098. #define SIGKILL (0)
  2099. static int kill(pid_t pid, int sig_num) {
  2100. (void)TerminateProcess(pid, sig_num);
  2101. (void)CloseHandle(pid);
  2102. return 0;
  2103. }
  2104. static void trim_trailing_whitespaces(char *s) {
  2105. char *e = s + strlen(s) - 1;
  2106. while (e > s && isspace(*(unsigned char *)e)) {
  2107. *e-- = '\0';
  2108. }
  2109. }
  2110. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  2111. char *envblk, char *envp[], int fdin, int fdout,
  2112. const char *dir) {
  2113. HANDLE me;
  2114. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2115. cmdline[PATH_MAX], buf[PATH_MAX];
  2116. struct file file = STRUCT_FILE_INITIALIZER;
  2117. STARTUPINFOA si;
  2118. PROCESS_INFORMATION pi = {0};
  2119. (void)envp;
  2120. memset(&si, 0, sizeof(si));
  2121. si.cb = sizeof(si);
  2122. /* TODO(lsm): redirect CGI errors to the error log file */
  2123. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2124. si.wShowWindow = SW_HIDE;
  2125. me = GetCurrentProcess();
  2126. DuplicateHandle(me, (HANDLE)_get_osfhandle(fdin), me, &si.hStdInput, 0,
  2127. TRUE, DUPLICATE_SAME_ACCESS);
  2128. DuplicateHandle(me, (HANDLE)_get_osfhandle(fdout), me, &si.hStdOutput, 0,
  2129. TRUE, DUPLICATE_SAME_ACCESS);
  2130. /* If CGI file is a script, try to read the interpreter line */
  2131. interp = conn->ctx->config[CGI_INTERPRETER];
  2132. if (interp == NULL) {
  2133. buf[0] = buf[1] = '\0';
  2134. /* Read the first line of the script into the buffer */
  2135. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  2136. if (mg_fopen(conn, cmdline, "r", &file)) {
  2137. p = (char *)file.membuf;
  2138. mg_fgets(buf, sizeof(buf), &file, &p);
  2139. mg_fclose(&file);
  2140. buf[sizeof(buf) - 1] = '\0';
  2141. }
  2142. if (buf[0] == '#' && buf[1] == '!') {
  2143. trim_trailing_whitespaces(buf + 2);
  2144. } else {
  2145. buf[2] = '\0';
  2146. }
  2147. interp = buf + 2;
  2148. }
  2149. if (interp[0] != '\0') {
  2150. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2151. interp = full_interp;
  2152. }
  2153. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2154. if (interp[0] != '\0')
  2155. mg_snprintf(conn, cmdline, sizeof(cmdline), "\"%s\" \"%s\\%s\"", interp,
  2156. full_dir, prog);
  2157. else
  2158. mg_snprintf(conn, cmdline, sizeof(cmdline), "\"%s\\%s\"", full_dir,
  2159. prog);
  2160. DEBUG_TRACE("Running [%s]", cmdline);
  2161. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  2162. CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
  2163. mg_cry(conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, ERRNO);
  2164. pi.hProcess = (pid_t)-1;
  2165. }
  2166. (void)CloseHandle(si.hStdOutput);
  2167. (void)CloseHandle(si.hStdInput);
  2168. if (pi.hThread != NULL)
  2169. (void)CloseHandle(pi.hThread);
  2170. return (pid_t)pi.hProcess;
  2171. }
  2172. #endif /* !NO_CGI */
  2173. static int set_non_blocking_mode(SOCKET sock) {
  2174. unsigned long on = 1;
  2175. return ioctlsocket(sock, FIONBIO, &on);
  2176. }
  2177. #else
  2178. static int mg_stat(struct mg_connection *conn, const char *path,
  2179. struct file *filep) {
  2180. struct stat st;
  2181. if (!filep) {
  2182. return 0;
  2183. }
  2184. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  2185. filep->size = st.st_size;
  2186. filep->modification_time = st.st_mtime;
  2187. filep->is_directory = S_ISDIR(st.st_mode);
  2188. } else {
  2189. filep->modification_time = (time_t)0;
  2190. }
  2191. return filep->membuf != NULL || filep->modification_time != (time_t)0;
  2192. }
  2193. static void set_close_on_exec(int fd,
  2194. struct mg_connection *conn /* may be null */) {
  2195. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2196. if (conn) {
  2197. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__,
  2198. strerror(ERRNO));
  2199. }
  2200. }
  2201. }
  2202. int mg_start_thread(mg_thread_func_t func, void *param) {
  2203. pthread_t thread_id;
  2204. pthread_attr_t attr;
  2205. int result;
  2206. (void)pthread_attr_init(&attr);
  2207. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2208. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2209. /* Compile-time option to control stack size,
  2210. * e.g. -DUSE_STACK_SIZE=16384 */
  2211. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2212. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2213. result = pthread_create(&thread_id, &attr, func, param);
  2214. pthread_attr_destroy(&attr);
  2215. return result;
  2216. }
  2217. /* Start a thread storing the thread context. */
  2218. static int mg_start_thread_with_id(mg_thread_func_t func, void *param,
  2219. pthread_t *threadidptr) {
  2220. pthread_t thread_id;
  2221. pthread_attr_t attr;
  2222. int result;
  2223. (void)pthread_attr_init(&attr);
  2224. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2225. /* Compile-time option to control stack size,
  2226. * e.g. -DUSE_STACK_SIZE=16384 */
  2227. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2228. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2229. result = pthread_create(&thread_id, &attr, func, param);
  2230. pthread_attr_destroy(&attr);
  2231. if ((result == 0) && (threadidptr != NULL)) {
  2232. *threadidptr = thread_id;
  2233. }
  2234. return result;
  2235. }
  2236. /* Wait for a thread to finish. */
  2237. static int mg_join_thread(pthread_t threadid) {
  2238. int result;
  2239. result = pthread_join(threadid, NULL);
  2240. return result;
  2241. }
  2242. #ifndef NO_CGI
  2243. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  2244. char *envblk, char *envp[], int fdin, int fdout,
  2245. const char *dir) {
  2246. pid_t pid;
  2247. const char *interp;
  2248. (void)envblk;
  2249. if (conn == NULL) {
  2250. return 0;
  2251. }
  2252. if ((pid = fork()) == -1) {
  2253. /* Parent */
  2254. send_http_error(conn, 500, "Error: Creating CGI process\nfork(): %s",
  2255. strerror(ERRNO));
  2256. } else if (pid == 0) {
  2257. /* Child */
  2258. if (chdir(dir) != 0) {
  2259. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2260. } else if (dup2(fdin, 0) == -1) {
  2261. mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin,
  2262. strerror(ERRNO));
  2263. } else if (dup2(fdout, 1) == -1) {
  2264. mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout,
  2265. strerror(ERRNO));
  2266. } else {
  2267. /* Not redirecting stderr to stdout, to avoid output being littered
  2268. * with the error messages. */
  2269. (void)close(fdin);
  2270. (void)close(fdout);
  2271. /* After exec, all signal handlers are restored to their default
  2272. * values, with one exception of SIGCHLD. According to
  2273. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2274. * leave unchanged after exec if it was set to be ignored. Restore
  2275. * it to default action. */
  2276. signal(SIGCHLD, SIG_DFL);
  2277. interp = conn->ctx->config[CGI_INTERPRETER];
  2278. if (interp == NULL) {
  2279. (void)execle(prog, prog, NULL, envp);
  2280. mg_cry(conn, "%s: execle(%s): %s", __func__, prog,
  2281. strerror(ERRNO));
  2282. } else {
  2283. (void)execle(interp, interp, prog, NULL, envp);
  2284. mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  2285. strerror(ERRNO));
  2286. }
  2287. }
  2288. exit(EXIT_FAILURE);
  2289. }
  2290. return pid;
  2291. }
  2292. #endif /* !NO_CGI */
  2293. static int set_non_blocking_mode(SOCKET sock) {
  2294. int flags;
  2295. flags = fcntl(sock, F_GETFL, 0);
  2296. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2297. return 0;
  2298. }
  2299. #endif /* _WIN32 */
  2300. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2301. * descriptor. Return number of bytes written. */
  2302. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  2303. int64_t len) {
  2304. int64_t sent;
  2305. int n, k;
  2306. (void)ssl; /* Get rid of warning */
  2307. sent = 0;
  2308. while (sent < len) {
  2309. /* How many bytes we send in this iteration */
  2310. k = len - sent > INT_MAX ? INT_MAX : (int)(len - sent);
  2311. #ifndef NO_SSL
  2312. if (ssl != NULL) {
  2313. n = SSL_write(ssl, buf + sent, k);
  2314. } else
  2315. #endif
  2316. if (fp != NULL) {
  2317. n = (int)fwrite(buf + sent, 1, (size_t)k, fp);
  2318. if (ferror(fp))
  2319. n = -1;
  2320. } else {
  2321. n = (int)send(sock, buf + sent, (size_t)k, MSG_NOSIGNAL);
  2322. }
  2323. if (n <= 0)
  2324. break;
  2325. sent += n;
  2326. }
  2327. return sent;
  2328. }
  2329. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2330. * Return negative value on error, or number of bytes read on success. */
  2331. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  2332. int nread;
  2333. double timeout = -1;
  2334. struct timespec start, now;
  2335. memset(&start, 0, sizeof(start));
  2336. memset(&now, 0, sizeof(now));
  2337. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2338. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2339. }
  2340. if (timeout > 0) {
  2341. clock_gettime(CLOCK_MONOTONIC, &start);
  2342. }
  2343. do {
  2344. if (fp != NULL) {
  2345. /* Use read() instead of fread(), because if we're reading from the
  2346. * CGI pipe, fread() may block until IO buffer is filled up. We
  2347. * cannot afford to block and must pass all read bytes immediately
  2348. * to the client. */
  2349. nread = (int)read(fileno(fp), buf, (size_t)len);
  2350. #ifndef NO_SSL
  2351. } else if (conn->ssl != NULL) {
  2352. nread = SSL_read(conn->ssl, buf, len);
  2353. #endif
  2354. } else {
  2355. nread = (int)recv(conn->client.sock, buf, (size_t)len, 0);
  2356. }
  2357. if (conn->ctx->stop_flag) {
  2358. return -1;
  2359. }
  2360. if (nread >= 0) {
  2361. return nread;
  2362. }
  2363. if (timeout > 0) {
  2364. clock_gettime(CLOCK_MONOTONIC, &now);
  2365. }
  2366. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2367. /* Timeout occured, but no data available. */
  2368. return -1;
  2369. }
  2370. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  2371. int n, nread = 0;
  2372. while (len > 0 && conn->ctx->stop_flag == 0) {
  2373. n = pull(fp, conn, buf + nread, len);
  2374. if (n < 0) {
  2375. nread = n; /* Propagate the error */
  2376. break;
  2377. } else if (n == 0) {
  2378. break; /* No more data to read */
  2379. } else {
  2380. conn->consumed_content += n;
  2381. nread += n;
  2382. len -= n;
  2383. }
  2384. }
  2385. return nread;
  2386. }
  2387. static void discard_unread_request_data(struct mg_connection *conn) {
  2388. char buf[MG_BUF_LEN];
  2389. int to_read, nread;
  2390. if (conn == NULL) {
  2391. return;
  2392. }
  2393. to_read = sizeof(buf);
  2394. if (conn->is_chunked) {
  2395. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2396. * completely */
  2397. while (conn->is_chunked == 1) {
  2398. nread = mg_read(conn, buf, to_read);
  2399. if (nread <= 0) {
  2400. break;
  2401. }
  2402. }
  2403. } else {
  2404. /* Not chunked: content length is known */
  2405. while (conn->consumed_content < conn->content_len) {
  2406. if ((int64_t)to_read >
  2407. (conn->content_len - conn->consumed_content)) {
  2408. to_read = (int)(conn->content_len - conn->consumed_content);
  2409. }
  2410. nread = mg_read(conn, buf, to_read);
  2411. if (nread <= 0) {
  2412. break;
  2413. }
  2414. }
  2415. }
  2416. }
  2417. int mg_read_inner(struct mg_connection *conn, void *buf, size_t len) {
  2418. int64_t n, buffered_len, nread;
  2419. int64_t len64 =
  2420. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2421. * int, we may not read more
  2422. * bytes */
  2423. const char *body;
  2424. if (conn == NULL)
  2425. return 0;
  2426. /* If Content-Length is not set for a PUT or POST request, read until
  2427. * socket is closed */
  2428. if (conn->consumed_content == 0 && conn->content_len == -1) {
  2429. conn->content_len = INT64_MAX;
  2430. conn->must_close = 1;
  2431. }
  2432. nread = 0;
  2433. if (conn->consumed_content < conn->content_len) {
  2434. /* Adjust number of bytes to read. */
  2435. int64_t left_to_read = conn->content_len - conn->consumed_content;
  2436. if (left_to_read < len64) {
  2437. /* Do not reade more than the total content length of the request.
  2438. */
  2439. len64 = left_to_read;
  2440. }
  2441. /* Return buffered data */
  2442. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  2443. conn->consumed_content;
  2444. if (buffered_len > 0) {
  2445. if (len64 < buffered_len) {
  2446. buffered_len = len64;
  2447. }
  2448. body = conn->buf + conn->request_len + conn->consumed_content;
  2449. memcpy(buf, body, (size_t)buffered_len);
  2450. len64 -= buffered_len;
  2451. conn->consumed_content += buffered_len;
  2452. nread += buffered_len;
  2453. buf = (char *)buf + buffered_len;
  2454. }
  2455. /* We have returned all buffered data. Read new data from the remote
  2456. * socket.
  2457. */
  2458. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  2459. nread += n;
  2460. } else {
  2461. nread = (nread > 0 ? nread : n);
  2462. }
  2463. }
  2464. return (int)nread;
  2465. }
  2466. static char mg_getc(struct mg_connection *conn) {
  2467. char c;
  2468. if (conn == NULL) {
  2469. return 0;
  2470. }
  2471. conn->content_len++;
  2472. if (mg_read_inner(conn, &c, 1) <= 0) {
  2473. return (char)0;
  2474. }
  2475. return c;
  2476. }
  2477. int mg_read(struct mg_connection *conn, void *buf, size_t len) {
  2478. if (len > INT_MAX)
  2479. len = INT_MAX;
  2480. if (conn == NULL)
  2481. return 0;
  2482. if (conn->is_chunked) {
  2483. size_t all_read = 0;
  2484. while (len > 0) {
  2485. if (conn->chunk_remainder) {
  2486. /* copy from the remainder of the last received chunk */
  2487. long read_ret;
  2488. int read_now = (int)((conn->chunk_remainder > len)
  2489. ? (len)
  2490. : (conn->chunk_remainder));
  2491. conn->content_len += read_now;
  2492. read_ret =
  2493. mg_read_inner(conn, (char *)buf + all_read, read_now);
  2494. all_read += read_ret;
  2495. conn->chunk_remainder -= read_now;
  2496. len -= read_now;
  2497. if (conn->chunk_remainder == 0) {
  2498. /* the rest of the data in the current chunk has been read
  2499. */
  2500. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  2501. /* Protocol violation */
  2502. return -1;
  2503. }
  2504. }
  2505. } else {
  2506. /* fetch a new chunk */
  2507. int i = 0;
  2508. char lenbuf[64];
  2509. char *end = 0;
  2510. unsigned long chunkSize = 0;
  2511. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  2512. lenbuf[i] = mg_getc(conn);
  2513. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r')
  2514. continue;
  2515. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  2516. lenbuf[i + 1] = 0;
  2517. chunkSize = strtoul(lenbuf, &end, 16);
  2518. break;
  2519. }
  2520. if (!isalnum(lenbuf[i])) {
  2521. /* illegal character for chunk length */
  2522. return -1;
  2523. }
  2524. }
  2525. if ((end == NULL) || (*end != '\r')) {
  2526. /* chunksize not set correctly */
  2527. return -1;
  2528. }
  2529. conn->chunk_remainder = chunkSize;
  2530. if (chunkSize == 0) {
  2531. /* regular end of content */
  2532. conn->is_chunked = 2;
  2533. break;
  2534. }
  2535. }
  2536. }
  2537. return (int)all_read;
  2538. }
  2539. return mg_read_inner(conn, buf, len);
  2540. }
  2541. int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
  2542. time_t now;
  2543. int64_t n, total, allowed;
  2544. if (conn == NULL) {
  2545. return 0;
  2546. }
  2547. if (conn->throttle > 0) {
  2548. if ((now = time(NULL)) != conn->last_throttle_time) {
  2549. conn->last_throttle_time = now;
  2550. conn->last_throttle_bytes = 0;
  2551. }
  2552. allowed = conn->throttle - conn->last_throttle_bytes;
  2553. if (allowed > (int64_t)len) {
  2554. allowed = len;
  2555. }
  2556. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *)buf,
  2557. (int64_t)allowed)) == allowed) {
  2558. buf = (char *)buf + total;
  2559. conn->last_throttle_bytes += total;
  2560. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  2561. allowed = conn->throttle > (int64_t)len - total
  2562. ? (int64_t)len - total
  2563. : conn->throttle;
  2564. if ((n = push(NULL, conn->client.sock, conn->ssl,
  2565. (const char *)buf, (int64_t)allowed)) !=
  2566. allowed) {
  2567. break;
  2568. }
  2569. sleep(1);
  2570. conn->last_throttle_bytes = allowed;
  2571. conn->last_throttle_time = time(NULL);
  2572. buf = (char *)buf + n;
  2573. total += n;
  2574. }
  2575. }
  2576. } else {
  2577. total = push(NULL, conn->client.sock, conn->ssl, (const char *)buf,
  2578. (int64_t)len);
  2579. }
  2580. return (int)total;
  2581. }
  2582. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  2583. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap) {
  2584. va_list ap_copy;
  2585. int size = MG_BUF_LEN;
  2586. int len = -1;
  2587. *buf = NULL;
  2588. while (len == -1) {
  2589. if (*buf)
  2590. mg_free(*buf);
  2591. *buf = (char *)mg_malloc(size *= 4);
  2592. if (!*buf)
  2593. break;
  2594. va_copy(ap_copy, ap);
  2595. len = vsnprintf(*buf, size, fmt, ap_copy);
  2596. va_end(ap_copy);
  2597. }
  2598. return len;
  2599. }
  2600. /* Print message to buffer. If buffer is large enough to hold the message,
  2601. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  2602. * and return allocated buffer. */
  2603. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  2604. va_list ap_copy;
  2605. int len;
  2606. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  2607. * buffer is too small. Also, older versions of msvcrt.dll do not have
  2608. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  2609. * Therefore, we make two passes: on first pass, get required message
  2610. * length.
  2611. * On second pass, actually print the message. */
  2612. va_copy(ap_copy, ap);
  2613. len = vsnprintf(NULL, 0, fmt, ap_copy);
  2614. va_end(ap_copy);
  2615. if (len < 0) {
  2616. /* C runtime is not standard compliant, vsnprintf() returned -1.
  2617. * Switch to alternative code path that uses incremental allocations.
  2618. */
  2619. va_copy(ap_copy, ap);
  2620. len = alloc_vprintf2(buf, fmt, ap);
  2621. va_end(ap_copy);
  2622. } else if (len > (int)size && (size = len + 1) > 0 &&
  2623. (*buf = (char *)mg_malloc(size)) == NULL) {
  2624. len = -1; /* Allocation failed, mark failure */
  2625. } else {
  2626. va_copy(ap_copy, ap);
  2627. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  2628. va_end(ap_copy);
  2629. }
  2630. return len;
  2631. }
  2632. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
  2633. char mem[MG_BUF_LEN], *buf = mem;
  2634. int len;
  2635. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  2636. len = mg_write(conn, buf, (size_t)len);
  2637. }
  2638. if (buf != mem && buf != NULL) {
  2639. mg_free(buf);
  2640. }
  2641. return len;
  2642. }
  2643. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  2644. va_list ap;
  2645. int result;
  2646. va_start(ap, fmt);
  2647. result = mg_vprintf(conn, fmt, ap);
  2648. va_end(ap);
  2649. return result;
  2650. }
  2651. int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
  2652. int is_form_url_encoded) {
  2653. int i, j, a, b;
  2654. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  2655. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  2656. if (i < src_len - 2 && src[i] == '%' &&
  2657. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  2658. isxdigit(*(const unsigned char *)(src + i + 2))) {
  2659. a = tolower(*(const unsigned char *)(src + i + 1));
  2660. b = tolower(*(const unsigned char *)(src + i + 2));
  2661. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  2662. i += 2;
  2663. } else if (is_form_url_encoded && src[i] == '+') {
  2664. dst[j] = ' ';
  2665. } else {
  2666. dst[j] = src[i];
  2667. }
  2668. }
  2669. dst[j] = '\0'; /* Null-terminate the destination */
  2670. return i >= src_len ? j : -1;
  2671. }
  2672. int mg_get_var(const char *data, size_t data_len, const char *name, char *dst,
  2673. size_t dst_len) {
  2674. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  2675. }
  2676. int mg_get_var2(const char *data, size_t data_len, const char *name, char *dst,
  2677. size_t dst_len, size_t occurrence) {
  2678. const char *p, *e, *s;
  2679. size_t name_len;
  2680. int len;
  2681. if (dst == NULL || dst_len == 0) {
  2682. len = -2;
  2683. } else if (data == NULL || name == NULL || data_len == 0) {
  2684. len = -1;
  2685. dst[0] = '\0';
  2686. } else {
  2687. name_len = strlen(name);
  2688. e = data + data_len;
  2689. len = -1;
  2690. dst[0] = '\0';
  2691. /* data is "var1=val1&var2=val2...". Find variable first */
  2692. for (p = data; p + name_len < e; p++) {
  2693. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  2694. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  2695. /* Point p to variable value */
  2696. p += name_len + 1;
  2697. /* Point s to the end of the value */
  2698. s = (const char *)memchr(p, '&', (size_t)(e - p));
  2699. if (s == NULL) {
  2700. s = e;
  2701. }
  2702. /* assert(s >= p); */
  2703. if (s < p) {
  2704. return -3;
  2705. }
  2706. /* Decode variable into destination buffer */
  2707. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  2708. /* Redirect error code from -1 to -2 (destination buffer too
  2709. * small). */
  2710. if (len == -1) {
  2711. len = -2;
  2712. }
  2713. break;
  2714. }
  2715. }
  2716. }
  2717. return len;
  2718. }
  2719. int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst,
  2720. size_t dst_size) {
  2721. const char *s, *p, *end;
  2722. int name_len, len = -1;
  2723. if (dst == NULL || dst_size == 0) {
  2724. len = -2;
  2725. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  2726. len = -1;
  2727. dst[0] = '\0';
  2728. } else {
  2729. name_len = (int)strlen(var_name);
  2730. end = s + strlen(s);
  2731. dst[0] = '\0';
  2732. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  2733. if (s[name_len] == '=') {
  2734. s += name_len + 1;
  2735. if ((p = strchr(s, ' ')) == NULL)
  2736. p = end;
  2737. if (p[-1] == ';')
  2738. p--;
  2739. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  2740. s++;
  2741. p--;
  2742. }
  2743. if ((size_t)(p - s) < dst_size) {
  2744. len = (int)(p - s);
  2745. mg_strlcpy(dst, s, (size_t)len + 1);
  2746. } else {
  2747. len = -3;
  2748. }
  2749. break;
  2750. }
  2751. }
  2752. }
  2753. return len;
  2754. }
  2755. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  2756. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  2757. static const char *b64 =
  2758. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2759. int i, j, a, b, c;
  2760. for (i = j = 0; i < src_len; i += 3) {
  2761. a = src[i];
  2762. b = i + 1 >= src_len ? 0 : src[i + 1];
  2763. c = i + 2 >= src_len ? 0 : src[i + 2];
  2764. dst[j++] = b64[a >> 2];
  2765. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  2766. if (i + 1 < src_len) {
  2767. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  2768. }
  2769. if (i + 2 < src_len) {
  2770. dst[j++] = b64[c & 63];
  2771. }
  2772. }
  2773. while (j % 4 != 0) {
  2774. dst[j++] = '=';
  2775. }
  2776. dst[j++] = '\0';
  2777. }
  2778. #endif
  2779. #if defined(USE_LUA)
  2780. static unsigned char b64reverse(char letter) {
  2781. if (letter >= 'A' && letter <= 'Z')
  2782. return letter - 'A';
  2783. if (letter >= 'a' && letter <= 'z')
  2784. return letter - 'a' + 26;
  2785. if (letter >= '0' && letter <= '9')
  2786. return letter - '0' + 52;
  2787. if (letter == '+')
  2788. return 62;
  2789. if (letter == '/')
  2790. return 63;
  2791. if (letter == '=')
  2792. return 255; /* normal end */
  2793. return 254; /* error */
  2794. }
  2795. static int base64_decode(const unsigned char *src, int src_len, char *dst,
  2796. size_t *dst_len) {
  2797. int i;
  2798. unsigned char a, b, c, d;
  2799. *dst_len = 0;
  2800. for (i = 0; i < src_len; i += 4) {
  2801. a = b64reverse(src[i]);
  2802. if (a >= 254)
  2803. return i;
  2804. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  2805. if (b >= 254)
  2806. return i + 1;
  2807. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  2808. if (c == 254)
  2809. return i + 2;
  2810. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  2811. if (c == 254)
  2812. return i + 3;
  2813. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  2814. if (c != 255) {
  2815. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  2816. if (d != 255) {
  2817. dst[(*dst_len)++] = (c << 6) + d;
  2818. }
  2819. }
  2820. }
  2821. return -1;
  2822. }
  2823. #endif
  2824. static int is_put_or_delete_method(const struct mg_connection *conn) {
  2825. if (conn) {
  2826. const char *s = conn->request_info.request_method;
  2827. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  2828. !strcmp(s, "MKCOL"));
  2829. }
  2830. return 0;
  2831. }
  2832. static void
  2833. interpret_uri(struct mg_connection *conn, /* in: request */
  2834. char *filename, /* out: filename */
  2835. size_t filename_buf_len, /* in: size of filename buffer */
  2836. struct file *filep, /* out: file structure */
  2837. int *is_script_ressource, /* out: handled by a script? */
  2838. int *is_websocket_request, /* out: websocket connetion? */
  2839. int *is_put_or_delete_request /* out: put/delete a file? */
  2840. ) {
  2841. if (conn && conn->ctx) {
  2842. const char *uri = conn->request_info.uri;
  2843. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  2844. #if !defined(NO_FILES)
  2845. const char *rewrite;
  2846. struct vec a, b;
  2847. char *p;
  2848. int match_len;
  2849. char gz_path[PATH_MAX];
  2850. char const *accept_encoding;
  2851. #endif
  2852. memset(filep, 0, sizeof(*filep));
  2853. *filename = 0;
  2854. *is_script_ressource = 0;
  2855. *is_put_or_delete_request = is_put_or_delete_method(conn);
  2856. #if defined(USE_WEBSOCKET)
  2857. *is_websocket_request = is_websocket_protocol(conn);
  2858. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  2859. root = conn->ctx->config[WEBSOCKET_ROOT];
  2860. }
  2861. #else
  2862. *is_websocket_request = 0;
  2863. #endif
  2864. #if !defined(NO_FILES)
  2865. /* Note that root == NULL is a regular use case here. This occurs,
  2866. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  2867. * config is not required. */
  2868. if (root == NULL) {
  2869. /* all file related outputs have already been set to 0, just return
  2870. */
  2871. return;
  2872. }
  2873. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  2874. * of the path one byte on the right.
  2875. * If document_root is NULL, leave the file empty. */
  2876. mg_snprintf(conn, filename, filename_buf_len - 1, "%s%s", root, uri);
  2877. rewrite = conn->ctx->config[REWRITE];
  2878. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  2879. if ((match_len = match_prefix(a.ptr, (int)a.len, uri)) > 0) {
  2880. mg_snprintf(conn, filename, filename_buf_len - 1, "%.*s%s",
  2881. (int)b.len, b.ptr, uri + match_len);
  2882. break;
  2883. }
  2884. }
  2885. /* Local file path and name, corresponding to requested URI
  2886. * is now stored in "filename" variable. */
  2887. if (mg_stat(conn, filename, filep)) {
  2888. /* File exists. Check if it is a script type. */
  2889. if (0
  2890. #if !defined(NO_CGI)
  2891. ||
  2892. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  2893. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  2894. filename) > 0
  2895. #endif
  2896. #if defined(USE_LUA)
  2897. ||
  2898. match_prefix(
  2899. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  2900. (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  2901. filename) > 0
  2902. #endif
  2903. ) {
  2904. /* The request addresses a CGI script or a Lua script. The URI
  2905. * corresponds to the script itself (like /path/script.cgi),
  2906. * and there is no additional resource path
  2907. * (like /path/script.cgi/something).
  2908. * Requests that modify (replace or delete) a resource, like
  2909. * PUT and DELETE requests, should replace/delete the script
  2910. * file.
  2911. * Requests that read or write from/to a resource, like GET and
  2912. * POST requests, should call the script and return the
  2913. * generated response. */
  2914. *is_script_ressource = !*is_put_or_delete_request;
  2915. }
  2916. return;
  2917. }
  2918. /* If we can't find the actual file, look for the file
  2919. * with the same name but a .gz extension. If we find it,
  2920. * use that and set the gzipped flag in the file struct
  2921. * to indicate that the response need to have the content-
  2922. * encoding: gzip header.
  2923. * We can only do this if the browser declares support. */
  2924. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  2925. NULL) {
  2926. if (strstr(accept_encoding, "gzip") != NULL) {
  2927. snprintf(gz_path, sizeof(gz_path), "%s.gz", filename);
  2928. if (mg_stat(conn, gz_path, filep)) {
  2929. if (filep)
  2930. filep->gzipped = 1;
  2931. /* Currently gz files can not be scripts. */
  2932. return;
  2933. }
  2934. }
  2935. }
  2936. /* Support PATH_INFO for CGI scripts. */
  2937. for (p = filename + strlen(filename); p > filename + 1; p--) {
  2938. if (*p == '/') {
  2939. *p = '\0';
  2940. if ((0
  2941. #if !defined(NO_CGI)
  2942. ||
  2943. match_prefix(
  2944. conn->ctx->config[CGI_EXTENSIONS],
  2945. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  2946. filename) > 0
  2947. #endif
  2948. #if defined(USE_LUA)
  2949. ||
  2950. match_prefix(
  2951. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  2952. (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  2953. filename) > 0
  2954. #endif
  2955. ) &&
  2956. mg_stat(conn, filename, filep)) {
  2957. /* Shift PATH_INFO block one character right, e.g.
  2958. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  2959. * conn->path_info is pointing to the local variable "path"
  2960. * declared in handle_request(), so PATH_INFO is not valid
  2961. * after handle_request returns. */
  2962. conn->path_info = p + 1;
  2963. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  2964. * trailing \0 */
  2965. p[1] = '/';
  2966. *is_script_ressource = 1;
  2967. break;
  2968. } else {
  2969. *p = '/';
  2970. }
  2971. }
  2972. }
  2973. #endif
  2974. }
  2975. }
  2976. /* Check whether full request is buffered. Return:
  2977. * -1 if request is malformed
  2978. * 0 if request is not yet fully buffered
  2979. * >0 actual request length, including last \r\n\r\n */
  2980. static int get_request_len(const char *buf, int buflen) {
  2981. const char *s, *e;
  2982. int len = 0;
  2983. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  2984. /* Control characters are not allowed but >=128 is. */
  2985. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  2986. *(const unsigned char *)s < 128) {
  2987. len = -1;
  2988. break; /* [i_a] abort scan as soon as one malformed character is
  2989. * found; */
  2990. /* don't let subsequent \r\n\r\n win us over anyhow */
  2991. } else if (s[0] == '\n' && s[1] == '\n') {
  2992. len = (int)(s - buf) + 2;
  2993. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  2994. len = (int)(s - buf) + 3;
  2995. }
  2996. return len;
  2997. }
  2998. /* Convert month to the month number. Return -1 on error, or month number */
  2999. static int get_month_index(const char *s) {
  3000. size_t i;
  3001. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  3002. if (!strcmp(s, month_names[i]))
  3003. return (int)i;
  3004. return -1;
  3005. }
  3006. static int num_leap_years(int year) {
  3007. return year / 4 - year / 100 + year / 400;
  3008. }
  3009. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3010. static time_t parse_date_string(const char *datetime) {
  3011. static const unsigned short days_before_month[] = {
  3012. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3013. char month_str[32] = {0};
  3014. int second, minute, hour, day, month, year, leap_days, days;
  3015. time_t result = (time_t)0;
  3016. if ((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
  3017. &minute, &second) == 6) ||
  3018. (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
  3019. &minute, &second) == 6) ||
  3020. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
  3021. &hour, &minute, &second) == 6) ||
  3022. (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
  3023. &minute, &second) == 6)) {
  3024. month = get_month_index(month_str);
  3025. if ((month >= 0) && (year > 1970)) {
  3026. leap_days = num_leap_years(year) - num_leap_years(1970);
  3027. year -= 1970;
  3028. days =
  3029. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3030. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3031. minute * 60 + second;
  3032. }
  3033. }
  3034. return result;
  3035. }
  3036. /* Protect against directory disclosure attack by removing '..',
  3037. * excessive '/' and '\' characters */
  3038. static void remove_double_dots_and_double_slashes(char *s) {
  3039. char *p = s;
  3040. while (*s != '\0') {
  3041. *p++ = *s++;
  3042. if (s[-1] == '/' || s[-1] == '\\') {
  3043. /* Skip all following slashes, backslashes and double-dots */
  3044. while (s[0] != '\0') {
  3045. if (s[0] == '/' || s[0] == '\\') {
  3046. s++;
  3047. } else if (s[0] == '.' && s[1] == '.') {
  3048. s += 2;
  3049. } else {
  3050. break;
  3051. }
  3052. }
  3053. }
  3054. }
  3055. *p = '\0';
  3056. }
  3057. static const struct {
  3058. const char *extension;
  3059. size_t ext_len;
  3060. const char *mime_type;
  3061. } builtin_mime_types[] = {
  3062. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3063. * application types */
  3064. {".doc", 4, "application/msword"},
  3065. {".eps", 4, "application/postscript"},
  3066. {".exe", 4, "application/octet-stream"},
  3067. {".js", 3, "application/javascript"},
  3068. {".json", 5, "application/json"},
  3069. {".pdf", 4, "application/pdf"},
  3070. {".ps", 3, "application/postscript"},
  3071. {".rtf", 4, "application/rtf"},
  3072. {".xhtml", 6, "application/xhtml+xml"},
  3073. {".xsl", 4, "application/xml"},
  3074. {".xslt", 5, "application/xml"},
  3075. /* audio */
  3076. {".mp3", 4, "audio/mpeg"},
  3077. {".oga", 4, "audio/ogg"},
  3078. {".ogg", 4, "audio/ogg"},
  3079. /* image */
  3080. {".gif", 4, "image/gif"},
  3081. {".ief", 4, "image/ief"},
  3082. {".jpeg", 5, "image/jpeg"},
  3083. {".jpg", 4, "image/jpeg"},
  3084. {".jpm", 4, "image/jpm"},
  3085. {".jpx", 4, "image/jpx"},
  3086. {".png", 4, "image/png"},
  3087. {".svg", 4, "image/svg+xml"},
  3088. {".tif", 4, "image/tiff"},
  3089. {".tiff", 5, "image/tiff"},
  3090. /* model */
  3091. {".wrl", 4, "model/vrml"},
  3092. /* text */
  3093. {".css", 4, "text/css"},
  3094. {".csv", 4, "text/csv"},
  3095. {".htm", 4, "text/html"},
  3096. {".html", 5, "text/html"},
  3097. {".sgm", 4, "text/sgml"},
  3098. {".shtm", 5, "text/html"},
  3099. {".shtml", 6, "text/html"},
  3100. {".txt", 4, "text/plain"},
  3101. {".xml", 4, "text/xml"},
  3102. /* video */
  3103. {".mov", 4, "video/quicktime"},
  3104. {".mp4", 4, "video/mp4"},
  3105. {".mpeg", 5, "video/mpeg"},
  3106. {".mpg", 4, "video/mpeg"},
  3107. {".ogv", 4, "video/ogg"},
  3108. {".qt", 3, "video/quicktime"},
  3109. /* not registered types
  3110. * (http://reference.sitepoint.com/html/mime-types-full,
  3111. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3112. {".arj", 4, "application/x-arj-compressed"},
  3113. {".gz", 3, "application/x-gunzip"},
  3114. {".rar", 4, "application/x-arj-compressed"},
  3115. {".swf", 4, "application/x-shockwave-flash"},
  3116. {".tar", 4, "application/x-tar"},
  3117. {".tgz", 4, "application/x-tar-gz"},
  3118. {".torrent", 8, "application/x-bittorrent"},
  3119. {".ppt", 4, "application/x-mspowerpoint"},
  3120. {".xls", 4, "application/x-msexcel"},
  3121. {".zip", 4, "application/x-zip-compressed"},
  3122. {".aac", 4,
  3123. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3124. {".aif", 4, "audio/x-aif"},
  3125. {".m3u", 4, "audio/x-mpegurl"},
  3126. {".mid", 4, "audio/x-midi"},
  3127. {".ra", 3, "audio/x-pn-realaudio"},
  3128. {".ram", 4, "audio/x-pn-realaudio"},
  3129. {".wav", 4, "audio/x-wav"},
  3130. {".bmp", 4, "image/bmp"},
  3131. {".ico", 4, "image/x-icon"},
  3132. {".pct", 4, "image/x-pct"},
  3133. {".pict", 5, "image/pict"},
  3134. {".rgb", 4, "image/x-rgb"},
  3135. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3136. {".asf", 4, "video/x-ms-asf"},
  3137. {".avi", 4, "video/x-msvideo"},
  3138. {".m4v", 4, "video/x-m4v"},
  3139. {NULL, 0, NULL}};
  3140. const char *mg_get_builtin_mime_type(const char *path) {
  3141. const char *ext;
  3142. size_t i, path_len;
  3143. path_len = strlen(path);
  3144. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3145. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3146. if (path_len > builtin_mime_types[i].ext_len &&
  3147. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3148. return builtin_mime_types[i].mime_type;
  3149. }
  3150. }
  3151. return "text/plain";
  3152. }
  3153. /* Look at the "path" extension and figure what mime type it has.
  3154. * Store mime type in the vector. */
  3155. static void get_mime_type(struct mg_context *ctx, const char *path,
  3156. struct vec *vec) {
  3157. struct vec ext_vec, mime_vec;
  3158. const char *list, *ext;
  3159. size_t path_len;
  3160. path_len = strlen(path);
  3161. if (ctx == NULL || vec == NULL) {
  3162. return;
  3163. }
  3164. /* Scan user-defined mime types first, in case user wants to
  3165. * override default mime types. */
  3166. list = ctx->config[EXTRA_MIME_TYPES];
  3167. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3168. /* ext now points to the path suffix */
  3169. ext = path + path_len - ext_vec.len;
  3170. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3171. *vec = mime_vec;
  3172. return;
  3173. }
  3174. }
  3175. vec->ptr = mg_get_builtin_mime_type(path);
  3176. vec->len = strlen(vec->ptr);
  3177. }
  3178. /* Stringify binary data. Output buffer must be twice as big as input,
  3179. * because each byte takes 2 bytes in string representation */
  3180. static void bin2str(char *to, const unsigned char *p, size_t len) {
  3181. static const char *hex = "0123456789abcdef";
  3182. for (; len--; p++) {
  3183. *to++ = hex[p[0] >> 4];
  3184. *to++ = hex[p[0] & 0x0f];
  3185. }
  3186. *to = '\0';
  3187. }
  3188. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3189. char *mg_md5(char buf[33], ...) {
  3190. md5_byte_t hash[16];
  3191. const char *p;
  3192. va_list ap;
  3193. md5_state_t ctx;
  3194. md5_init(&ctx);
  3195. va_start(ap, buf);
  3196. while ((p = va_arg(ap, const char *)) != NULL) {
  3197. md5_append(&ctx, (const md5_byte_t *)p, (int)strlen(p));
  3198. }
  3199. va_end(ap);
  3200. md5_finish(&ctx, hash);
  3201. bin2str(buf, hash, sizeof(hash));
  3202. return buf;
  3203. }
  3204. /* Check the user's password, return 1 if OK */
  3205. static int check_password(const char *method, const char *ha1, const char *uri,
  3206. const char *nonce, const char *nc, const char *cnonce,
  3207. const char *qop, const char *response) {
  3208. char ha2[32 + 1], expected_response[32 + 1];
  3209. /* Some of the parameters may be NULL */
  3210. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3211. qop == NULL || response == NULL) {
  3212. return 0;
  3213. }
  3214. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3215. /* TODO(lsm): check for authentication timeout */
  3216. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3217. strlen(response) != 32
  3218. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3219. ) {
  3220. return 0;
  3221. }
  3222. mg_md5(ha2, method, ":", uri, NULL);
  3223. mg_md5(expected_response, ha1, ":", nonce, ":", nc, ":", cnonce, ":", qop,
  3224. ":", ha2, NULL);
  3225. return mg_strcasecmp(response, expected_response) == 0;
  3226. }
  3227. /* Use the global passwords file, if specified by auth_gpass option,
  3228. * or search for .htpasswd in the requested directory. */
  3229. static void open_auth_file(struct mg_connection *conn, const char *path,
  3230. struct file *filep) {
  3231. if (conn != NULL && conn->ctx != NULL) {
  3232. char name[PATH_MAX];
  3233. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3234. struct file file = STRUCT_FILE_INITIALIZER;
  3235. if (gpass != NULL) {
  3236. /* Use global passwords file */
  3237. if (!mg_fopen(conn, gpass, "r", filep)) {
  3238. #ifdef DEBUG
  3239. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3240. #endif
  3241. }
  3242. /* Important: using local struct file to test path for is_directory
  3243. * flag.
  3244. * If filep is used, mg_stat() makes it appear as if auth file was
  3245. * opened. */
  3246. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3247. mg_snprintf(conn, name, sizeof(name), "%s%c%s", path, '/',
  3248. PASSWORDS_FILE_NAME);
  3249. if (!mg_fopen(conn, name, "r", filep)) {
  3250. #ifdef DEBUG
  3251. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3252. #endif
  3253. }
  3254. } else {
  3255. /* Try to find .htpasswd in requested directory. */
  3256. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  3257. if (e[0] == '/') {
  3258. break;
  3259. }
  3260. }
  3261. mg_snprintf(conn, name, sizeof(name), "%.*s%c%s", (int)(e - p), p,
  3262. '/', PASSWORDS_FILE_NAME);
  3263. if (!mg_fopen(conn, name, "r", filep)) {
  3264. #ifdef DEBUG
  3265. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3266. #endif
  3267. }
  3268. }
  3269. }
  3270. }
  3271. /* Parsed Authorization header */
  3272. struct ah {
  3273. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  3274. };
  3275. /* Return 1 on success. Always initializes the ah structure. */
  3276. static int parse_auth_header(struct mg_connection *conn, char *buf,
  3277. size_t buf_size, struct ah *ah) {
  3278. char *name, *value, *s;
  3279. const char *auth_header;
  3280. unsigned long nonce;
  3281. if (!ah || !conn)
  3282. return 0;
  3283. (void)memset(ah, 0, sizeof(*ah));
  3284. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  3285. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  3286. return 0;
  3287. }
  3288. /* Make modifiable copy of the auth header */
  3289. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  3290. s = buf;
  3291. /* Parse authorization header */
  3292. for (;;) {
  3293. /* Gobble initial spaces */
  3294. while (isspace(*(unsigned char *)s)) {
  3295. s++;
  3296. }
  3297. name = skip_quoted(&s, "=", " ", 0);
  3298. /* Value is either quote-delimited, or ends at first comma or space. */
  3299. if (s[0] == '\"') {
  3300. s++;
  3301. value = skip_quoted(&s, "\"", " ", '\\');
  3302. if (s[0] == ',') {
  3303. s++;
  3304. }
  3305. } else {
  3306. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  3307. * spaces */
  3308. }
  3309. if (*name == '\0') {
  3310. break;
  3311. }
  3312. if (!strcmp(name, "username")) {
  3313. ah->user = value;
  3314. } else if (!strcmp(name, "cnonce")) {
  3315. ah->cnonce = value;
  3316. } else if (!strcmp(name, "response")) {
  3317. ah->response = value;
  3318. } else if (!strcmp(name, "uri")) {
  3319. ah->uri = value;
  3320. } else if (!strcmp(name, "qop")) {
  3321. ah->qop = value;
  3322. } else if (!strcmp(name, "nc")) {
  3323. ah->nc = value;
  3324. } else if (!strcmp(name, "nonce")) {
  3325. ah->nonce = value;
  3326. }
  3327. }
  3328. #ifndef NO_NONCE_CHECK
  3329. /* Convert the nonce from the client to a number and check it. */
  3330. /* Server side nonce check is valuable in all situations but one: if the
  3331. * server restarts frequently,
  3332. * but the client should not see that, so the server should accept nonces
  3333. * from
  3334. * previous starts. */
  3335. if (ah->nonce == NULL) {
  3336. return 0;
  3337. }
  3338. nonce = strtoul(ah->nonce, &s, 10);
  3339. if ((s == NULL) || (*s != 0)) {
  3340. return 0;
  3341. }
  3342. nonce ^= (unsigned long)(conn->ctx);
  3343. if (nonce < conn->ctx->start_time) {
  3344. /* nonce is from a previous start of the server and no longer valid
  3345. * (replay attack?) */
  3346. return 0;
  3347. }
  3348. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  3349. return 0;
  3350. }
  3351. #endif
  3352. /* CGI needs it as REMOTE_USER */
  3353. if (ah->user != NULL) {
  3354. conn->request_info.remote_user = mg_strdup(ah->user);
  3355. } else {
  3356. return 0;
  3357. }
  3358. return 1;
  3359. }
  3360. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {
  3361. char *eof;
  3362. size_t len;
  3363. char *memend;
  3364. if (!filep)
  3365. return NULL;
  3366. if (filep->membuf != NULL && *p != NULL) {
  3367. memend = (char *)&filep->membuf[filep->size];
  3368. eof = (char *)memchr(
  3369. *p, '\n',
  3370. memend - *p); /* Search for \n from p till the end of stream */
  3371. if (eof != NULL) {
  3372. eof += 1; /* Include \n */
  3373. } else {
  3374. eof = memend; /* Copy remaining data */
  3375. }
  3376. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  3377. memcpy(buf, *p, len);
  3378. buf[len] = '\0';
  3379. *p += len;
  3380. return len ? eof : NULL;
  3381. } else if (filep->fp != NULL) {
  3382. return fgets(buf, (int)size, filep->fp);
  3383. } else {
  3384. return NULL;
  3385. }
  3386. }
  3387. struct read_auth_file_struct {
  3388. struct mg_connection *conn;
  3389. struct ah ah;
  3390. char *domain;
  3391. char buf[256 + 256 + 40];
  3392. char *f_user;
  3393. char *f_domain;
  3394. char *f_ha1;
  3395. };
  3396. static int read_auth_file(struct file *filep,
  3397. struct read_auth_file_struct *workdata) {
  3398. char *p;
  3399. int is_authorized = 0;
  3400. struct file fp;
  3401. size_t l;
  3402. if (!filep || !workdata)
  3403. return 0;
  3404. /* Loop over passwords file */
  3405. p = (char *)filep->membuf;
  3406. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  3407. l = strlen(workdata->buf);
  3408. while (l > 0) {
  3409. if (isspace(workdata->buf[l - 1]) ||
  3410. iscntrl(workdata->buf[l - 1])) {
  3411. l--;
  3412. workdata->buf[l] = 0;
  3413. } else
  3414. break;
  3415. }
  3416. if (l < 1)
  3417. continue;
  3418. workdata->f_user = workdata->buf;
  3419. if (workdata->f_user[0] == ':') {
  3420. /* user names may not contain a ':' and may not be empty,
  3421. * so lines starting with ':' may be used for a special purpose */
  3422. if (workdata->f_user[1] == '#') {
  3423. /* :# is a comment */
  3424. continue;
  3425. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  3426. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  3427. is_authorized = read_auth_file(&fp, workdata);
  3428. mg_fclose(&fp);
  3429. } else {
  3430. mg_cry(workdata->conn,
  3431. "%s: cannot open authorization file: %s", __func__,
  3432. workdata->buf);
  3433. }
  3434. continue;
  3435. }
  3436. /* everything is invalid for the moment (might change in the
  3437. * future) */
  3438. mg_cry(workdata->conn, "%s: syntax error in authorization file: %s",
  3439. __func__, workdata->buf);
  3440. continue;
  3441. }
  3442. workdata->f_domain = strchr(workdata->f_user, ':');
  3443. if (workdata->f_domain == NULL) {
  3444. mg_cry(workdata->conn, "%s: syntax error in authorization file: %s",
  3445. __func__, workdata->buf);
  3446. continue;
  3447. }
  3448. *(workdata->f_domain) = 0;
  3449. (workdata->f_domain)++;
  3450. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  3451. if (workdata->f_ha1 == NULL) {
  3452. mg_cry(workdata->conn, "%s: syntax error in authorization file: %s",
  3453. __func__, workdata->buf);
  3454. continue;
  3455. }
  3456. *(workdata->f_ha1) = 0;
  3457. (workdata->f_ha1)++;
  3458. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  3459. !strcmp(workdata->domain, workdata->f_domain)) {
  3460. return check_password(
  3461. workdata->conn->request_info.request_method, workdata->f_ha1,
  3462. workdata->ah.uri, workdata->ah.nonce, workdata->ah.nc,
  3463. workdata->ah.cnonce, workdata->ah.qop, workdata->ah.response);
  3464. }
  3465. }
  3466. return is_authorized;
  3467. }
  3468. /* Authorize against the opened passwords file. Return 1 if authorized. */
  3469. static int authorize(struct mg_connection *conn, struct file *filep) {
  3470. struct read_auth_file_struct workdata;
  3471. char buf[MG_BUF_LEN];
  3472. if (!conn || !conn->ctx)
  3473. return 0;
  3474. memset(&workdata, 0, sizeof(workdata));
  3475. workdata.conn = conn;
  3476. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  3477. return 0;
  3478. }
  3479. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  3480. return read_auth_file(filep, &workdata);
  3481. }
  3482. /* Return 1 if request is authorised, 0 otherwise. */
  3483. static int check_authorization(struct mg_connection *conn, const char *path) {
  3484. char fname[PATH_MAX];
  3485. struct vec uri_vec, filename_vec;
  3486. const char *list;
  3487. struct file file = STRUCT_FILE_INITIALIZER;
  3488. int authorized = 1;
  3489. if (!conn || !conn->ctx)
  3490. return 0;
  3491. list = conn->ctx->config[PROTECT_URI];
  3492. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  3493. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  3494. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  3495. (int)filename_vec.len, filename_vec.ptr);
  3496. if (!mg_fopen(conn, fname, "r", &file)) {
  3497. mg_cry(conn, "%s: cannot open %s: %s", __func__, fname,
  3498. strerror(errno));
  3499. }
  3500. break;
  3501. }
  3502. }
  3503. if (!is_file_opened(&file)) {
  3504. open_auth_file(conn, path, &file);
  3505. }
  3506. if (is_file_opened(&file)) {
  3507. authorized = authorize(conn, &file);
  3508. mg_fclose(&file);
  3509. }
  3510. return authorized;
  3511. }
  3512. static void send_authorization_request(struct mg_connection *conn) {
  3513. char date[64];
  3514. time_t curtime = time(NULL);
  3515. if (conn && conn->ctx) {
  3516. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  3517. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  3518. nonce += conn->ctx->nonce_count;
  3519. ++conn->ctx->nonce_count;
  3520. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  3521. nonce ^= (unsigned long)(conn->ctx);
  3522. conn->status_code = 401;
  3523. conn->must_close = 1;
  3524. gmt_time_string(date, sizeof(date), &curtime);
  3525. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n"
  3526. "Date: %s\r\n"
  3527. "Connection: %s\r\n"
  3528. "Content-Length: 0\r\n"
  3529. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  3530. "nonce=\"%lu\"\r\n\r\n",
  3531. date, suggest_connection_header(conn),
  3532. conn->ctx->config[AUTHENTICATION_DOMAIN], nonce);
  3533. }
  3534. }
  3535. static int is_authorized_for_put(struct mg_connection *conn) {
  3536. if (conn) {
  3537. struct file file = STRUCT_FILE_INITIALIZER;
  3538. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  3539. int ret = 0;
  3540. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  3541. ret = authorize(conn, &file);
  3542. mg_fclose(&file);
  3543. }
  3544. return ret;
  3545. }
  3546. return 0;
  3547. }
  3548. int mg_modify_passwords_file(const char *fname, const char *domain,
  3549. const char *user, const char *pass) {
  3550. int found, i;
  3551. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  3552. FILE *fp, *fp2;
  3553. found = 0;
  3554. fp = fp2 = NULL;
  3555. /* Regard empty password as no password - remove user record. */
  3556. if (pass != NULL && pass[0] == '\0') {
  3557. pass = NULL;
  3558. }
  3559. /* Other arguments must not be empty */
  3560. if (fname == NULL || domain == NULL || user == NULL)
  3561. return 0;
  3562. /* Using the given file format, user name and domain must not contain ':'
  3563. */
  3564. if (strchr(user, ':') != NULL)
  3565. return 0;
  3566. if (strchr(domain, ':') != NULL)
  3567. return 0;
  3568. /* Do not allow control characters like newline in user name and domain.
  3569. * Do not allow excessively long names either. */
  3570. for (i = 0; i < 255 && user[i] != 0; i++) {
  3571. if (iscntrl(user[i]))
  3572. return 0;
  3573. }
  3574. if (user[i])
  3575. return 0;
  3576. for (i = 0; i < 255 && domain[i] != 0; i++) {
  3577. if (iscntrl(domain[i]))
  3578. return 0;
  3579. }
  3580. if (domain[i])
  3581. return 0;
  3582. /* Create a temporary file name */
  3583. (void)snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  3584. tmp[sizeof(tmp) - 1] = 0;
  3585. /* Create the file if does not exist */
  3586. if ((fp = fopen(fname, "a+")) != NULL) {
  3587. (void)fclose(fp);
  3588. }
  3589. /* Open the given file and temporary file */
  3590. if ((fp = fopen(fname, "r")) == NULL) {
  3591. return 0;
  3592. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  3593. fclose(fp);
  3594. return 0;
  3595. }
  3596. /* Copy the stuff to temporary file */
  3597. while (fgets(line, sizeof(line), fp) != NULL) {
  3598. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  3599. continue;
  3600. }
  3601. u[255] = 0;
  3602. d[255] = 0;
  3603. if (!strcmp(u, user) && !strcmp(d, domain)) {
  3604. found++;
  3605. if (pass != NULL) {
  3606. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  3607. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  3608. }
  3609. } else {
  3610. fprintf(fp2, "%s", line);
  3611. }
  3612. }
  3613. /* If new user, just add it */
  3614. if (!found && pass != NULL) {
  3615. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  3616. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  3617. }
  3618. /* Close files */
  3619. fclose(fp);
  3620. fclose(fp2);
  3621. /* Put the temp file in place of real file */
  3622. IGNORE_UNUSED_RESULT(remove(fname));
  3623. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  3624. return 1;
  3625. }
  3626. static SOCKET conn2(struct mg_context *ctx /* may be null */, const char *host,
  3627. int port, int use_ssl, char *ebuf, size_t ebuf_len) {
  3628. struct sockaddr_in sain;
  3629. struct hostent *he;
  3630. SOCKET sock = INVALID_SOCKET;
  3631. if (ebuf_len > 0) {
  3632. *ebuf = 0;
  3633. }
  3634. if (host == NULL) {
  3635. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  3636. } else if (use_ssl && SSLv23_client_method == NULL) {
  3637. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  3638. /* TODO(lsm): use something threadsafe instead of gethostbyname() */
  3639. } else if ((he = gethostbyname(host)) == NULL) {
  3640. snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host,
  3641. strerror(ERRNO));
  3642. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  3643. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  3644. } else {
  3645. set_close_on_exec(sock, fc(ctx));
  3646. memset(&sain, '\0', sizeof(sain));
  3647. sain.sin_family = AF_INET;
  3648. sain.sin_port = htons((uint16_t)port);
  3649. sain.sin_addr = *(struct in_addr *)he->h_addr_list[0];
  3650. if (connect(sock, (struct sockaddr *)&sain, sizeof(sain)) != 0) {
  3651. snprintf(ebuf, ebuf_len, "connect(%s:%d): %s", host, port,
  3652. strerror(ERRNO));
  3653. closesocket(sock);
  3654. sock = INVALID_SOCKET;
  3655. }
  3656. }
  3657. return sock;
  3658. }
  3659. int mg_url_encode(const char *src, char *dst, size_t dst_len) {
  3660. static const char *dont_escape = "._-$,;~()";
  3661. static const char *hex = "0123456789abcdef";
  3662. char *pos = dst;
  3663. const char *end = dst + dst_len - 1;
  3664. for (; *src != '\0' && pos < end; src++, pos++) {
  3665. if (isalnum(*(const unsigned char *)src) ||
  3666. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  3667. *pos = *src;
  3668. } else if (pos + 2 < end) {
  3669. pos[0] = '%';
  3670. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  3671. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  3672. pos += 2;
  3673. } else {
  3674. break;
  3675. }
  3676. }
  3677. *pos = '\0';
  3678. return (*src == '\0') ? (int)(pos - dst) : -1;
  3679. }
  3680. static void print_dir_entry(struct de *de) {
  3681. char size[64], mod[64], href[PATH_MAX];
  3682. struct tm *tm;
  3683. if (de->file.is_directory) {
  3684. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  3685. } else {
  3686. /* We use (signed) cast below because MSVC 6 compiler cannot
  3687. * convert unsigned __int64 to double. Sigh. */
  3688. if (de->file.size < 1024) {
  3689. mg_snprintf(de->conn, size, sizeof(size), "%d", (int)de->file.size);
  3690. } else if (de->file.size < 0x100000) {
  3691. mg_snprintf(de->conn, size, sizeof(size), "%.1fk",
  3692. (double)de->file.size / 1024.0);
  3693. } else if (de->file.size < 0x40000000) {
  3694. mg_snprintf(de->conn, size, sizeof(size), "%.1fM",
  3695. (double)de->file.size / 1048576);
  3696. } else {
  3697. mg_snprintf(de->conn, size, sizeof(size), "%.1fG",
  3698. (double)de->file.size / 1073741824);
  3699. }
  3700. }
  3701. tm = localtime(&de->file.modification_time);
  3702. if (tm != NULL) {
  3703. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  3704. } else {
  3705. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  3706. mod[sizeof(mod) - 1] = '\0';
  3707. }
  3708. mg_url_encode(de->file_name, href, sizeof(href));
  3709. de->conn->num_bytes_sent += mg_printf(
  3710. de->conn, "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  3711. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  3712. de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
  3713. de->file_name, de->file.is_directory ? "/" : "", mod, size);
  3714. }
  3715. /* This function is called from send_directory() and used for
  3716. * sorting directory entries by size, or name, or modification time.
  3717. * On windows, __cdecl specification is needed in case if project is built
  3718. * with __stdcall convention. qsort always requires __cdels callback. */
  3719. static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
  3720. if (p1 && p2) {
  3721. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  3722. const char *query_string = a->conn->request_info.query_string;
  3723. int cmp_result = 0;
  3724. if (query_string == NULL) {
  3725. query_string = "na";
  3726. }
  3727. if (a->file.is_directory && !b->file.is_directory) {
  3728. return -1; /* Always put directories on top */
  3729. } else if (!a->file.is_directory && b->file.is_directory) {
  3730. return 1; /* Always put directories on top */
  3731. } else if (*query_string == 'n') {
  3732. cmp_result = strcmp(a->file_name, b->file_name);
  3733. } else if (*query_string == 's') {
  3734. cmp_result = a->file.size == b->file.size
  3735. ? 0
  3736. : a->file.size > b->file.size ? 1 : -1;
  3737. } else if (*query_string == 'd') {
  3738. cmp_result =
  3739. a->file.modification_time == b->file.modification_time
  3740. ? 0
  3741. : a->file.modification_time > b->file.modification_time
  3742. ? 1
  3743. : -1;
  3744. }
  3745. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  3746. }
  3747. return 0;
  3748. }
  3749. static int must_hide_file(struct mg_connection *conn, const char *path) {
  3750. if (conn && conn->ctx) {
  3751. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  3752. const char *pattern = conn->ctx->config[HIDE_FILES];
  3753. return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
  3754. (pattern != NULL &&
  3755. match_prefix(pattern, (int)strlen(pattern), path) > 0);
  3756. }
  3757. return 0;
  3758. }
  3759. static int scan_directory(struct mg_connection *conn, const char *dir,
  3760. void *data, void (*cb)(struct de *, void *)) {
  3761. char path[PATH_MAX];
  3762. struct dirent *dp;
  3763. DIR *dirp;
  3764. struct de de;
  3765. if ((dirp = opendir(dir)) == NULL) {
  3766. return 0;
  3767. } else {
  3768. de.conn = conn;
  3769. while ((dp = readdir(dirp)) != NULL) {
  3770. /* Do not show current dir and hidden files */
  3771. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  3772. must_hide_file(conn, dp->d_name)) {
  3773. continue;
  3774. }
  3775. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/',
  3776. dp->d_name);
  3777. /* If we don't memset stat structure to zero, mtime will have
  3778. * garbage and strftime() will segfault later on in
  3779. * print_dir_entry(). memset is required only if mg_stat()
  3780. * fails. For more details, see
  3781. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  3782. memset(&de.file, 0, sizeof(de.file));
  3783. if (!mg_stat(conn, path, &de.file)) {
  3784. mg_cry(conn, "%s: mg_stat(%s) failed: %s", __func__, path,
  3785. strerror(ERRNO));
  3786. }
  3787. de.file_name = dp->d_name;
  3788. cb(&de, data);
  3789. }
  3790. (void)closedir(dirp);
  3791. }
  3792. return 1;
  3793. }
  3794. static int remove_directory(struct mg_connection *conn, const char *dir) {
  3795. char path[PATH_MAX];
  3796. struct dirent *dp;
  3797. DIR *dirp;
  3798. struct de de;
  3799. if ((dirp = opendir(dir)) == NULL) {
  3800. return 0;
  3801. } else {
  3802. de.conn = conn;
  3803. while ((dp = readdir(dirp)) != NULL) {
  3804. /* Do not show current dir (but show hidden files as they will
  3805. also be removed) */
  3806. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  3807. continue;
  3808. }
  3809. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/',
  3810. dp->d_name);
  3811. /* If we don't memset stat structure to zero, mtime will have
  3812. * garbage and strftime() will segfault later on in
  3813. * print_dir_entry(). memset is required only if mg_stat()
  3814. * fails. For more details, see
  3815. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  3816. memset(&de.file, 0, sizeof(de.file));
  3817. if (!mg_stat(conn, path, &de.file)) {
  3818. mg_cry(conn, "%s: mg_stat(%s) failed: %s", __func__, path,
  3819. strerror(ERRNO));
  3820. }
  3821. if (de.file.modification_time) {
  3822. if (de.file.is_directory) {
  3823. remove_directory(conn, path);
  3824. } else {
  3825. mg_remove(path);
  3826. }
  3827. }
  3828. }
  3829. (void)closedir(dirp);
  3830. IGNORE_UNUSED_RESULT(rmdir(dir));
  3831. }
  3832. return 1;
  3833. }
  3834. struct dir_scan_data {
  3835. struct de *entries;
  3836. int num_entries;
  3837. int arr_size;
  3838. };
  3839. /* Behaves like realloc(), but frees original pointer on failure */
  3840. static void *realloc2(void *ptr, size_t size) {
  3841. void *new_ptr = mg_realloc(ptr, size);
  3842. if (new_ptr == NULL) {
  3843. mg_free(ptr);
  3844. }
  3845. return new_ptr;
  3846. }
  3847. static void dir_scan_callback(struct de *de, void *data) {
  3848. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  3849. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  3850. dsd->arr_size *= 2;
  3851. dsd->entries = (struct de *)realloc2(
  3852. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  3853. }
  3854. if (dsd->entries == NULL) {
  3855. /* TODO(lsm): propagate an error to the caller */
  3856. dsd->num_entries = 0;
  3857. } else {
  3858. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  3859. dsd->entries[dsd->num_entries].file = de->file;
  3860. dsd->entries[dsd->num_entries].conn = de->conn;
  3861. dsd->num_entries++;
  3862. }
  3863. }
  3864. static void handle_directory_request(struct mg_connection *conn,
  3865. const char *dir) {
  3866. int i, sort_direction;
  3867. struct dir_scan_data data = {NULL, 0, 128};
  3868. char date[64];
  3869. time_t curtime = time(NULL);
  3870. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  3871. send_http_error(conn, 500,
  3872. "Error: Cannot open directory\nopendir(%s): %s", dir,
  3873. strerror(ERRNO));
  3874. return;
  3875. }
  3876. gmt_time_string(date, sizeof(date), &curtime);
  3877. if (!conn)
  3878. return;
  3879. sort_direction = conn->request_info.query_string != NULL &&
  3880. conn->request_info.query_string[1] == 'd'
  3881. ? 'a'
  3882. : 'd';
  3883. conn->must_close = 1;
  3884. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3885. "Date: %s\r\n"
  3886. "Connection: close\r\n"
  3887. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  3888. date);
  3889. conn->num_bytes_sent += mg_printf(
  3890. conn, "<html><head><title>Index of %s</title>"
  3891. "<style>th {text-align: left;}</style></head>"
  3892. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  3893. "<tr><th><a href=\"?n%c\">Name</a></th>"
  3894. "<th><a href=\"?d%c\">Modified</a></th>"
  3895. "<th><a href=\"?s%c\">Size</a></th></tr>"
  3896. "<tr><td colspan=\"3\"><hr></td></tr>",
  3897. conn->request_info.uri, conn->request_info.uri, sort_direction,
  3898. sort_direction, sort_direction);
  3899. /* Print first entry - link to a parent directory */
  3900. conn->num_bytes_sent +=
  3901. mg_printf(conn, "<tr><td><a href=\"%s%s\">%s</a></td>"
  3902. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  3903. conn->request_info.uri, "..", "Parent directory", "-", "-");
  3904. /* Sort and print directory entries */
  3905. if (data.entries != NULL) {
  3906. qsort(data.entries, (size_t)data.num_entries, sizeof(data.entries[0]),
  3907. compare_dir_entries);
  3908. for (i = 0; i < data.num_entries; i++) {
  3909. print_dir_entry(&data.entries[i]);
  3910. mg_free(data.entries[i].file_name);
  3911. }
  3912. mg_free(data.entries);
  3913. }
  3914. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  3915. conn->status_code = 200;
  3916. }
  3917. /* Send len bytes from the opened file to the client. */
  3918. static void send_file_data(struct mg_connection *conn, struct file *filep,
  3919. int64_t offset, int64_t len) {
  3920. char buf[MG_BUF_LEN];
  3921. int to_read, num_read, num_written;
  3922. /* Sanity check the offset */
  3923. if (!filep)
  3924. return;
  3925. offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
  3926. if (len > 0 && filep->membuf != NULL && filep->size > 0) {
  3927. if (len > filep->size - offset) {
  3928. len = filep->size - offset;
  3929. }
  3930. mg_write(conn, filep->membuf + offset, (size_t)len);
  3931. } else if (len > 0 && filep->fp != NULL) {
  3932. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  3933. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  3934. }
  3935. while (len > 0) {
  3936. /* Calculate how much to read from the file in the buffer */
  3937. to_read = sizeof(buf);
  3938. if ((int64_t)to_read > len) {
  3939. to_read = (int)len;
  3940. }
  3941. /* Read from file, exit the loop on error */
  3942. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp)) <=
  3943. 0) {
  3944. break;
  3945. }
  3946. /* Send read bytes to the client, exit the loop on error */
  3947. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  3948. num_read) {
  3949. break;
  3950. }
  3951. /* Both read and were successful, adjust counters */
  3952. if (!conn)
  3953. break;
  3954. conn->num_bytes_sent += num_written;
  3955. len -= num_written;
  3956. }
  3957. }
  3958. }
  3959. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  3960. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  3961. }
  3962. static void construct_etag(char *buf, size_t buf_len,
  3963. const struct file *filep) {
  3964. if (filep)
  3965. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  3966. (unsigned long)filep->modification_time, filep->size);
  3967. }
  3968. static void fclose_on_exec(struct file *filep, struct mg_connection *conn) {
  3969. if (filep != NULL && filep->fp != NULL) {
  3970. #ifdef _WIN32
  3971. (void)conn; /* Unused. */
  3972. #else
  3973. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  3974. mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__,
  3975. strerror(ERRNO));
  3976. }
  3977. #endif
  3978. }
  3979. }
  3980. static void handle_static_file_request(struct mg_connection *conn,
  3981. const char *path, struct file *filep) {
  3982. char date[64], lm[64], etag[64], range[64];
  3983. const char *msg = "OK", *hdr;
  3984. time_t curtime = time(NULL);
  3985. int64_t cl, r1, r2;
  3986. struct vec mime_vec;
  3987. int n;
  3988. char gz_path[PATH_MAX];
  3989. const char *encoding = "";
  3990. const char *cors1, *cors2, *cors3;
  3991. if (!conn || !conn->ctx || !filep)
  3992. return;
  3993. get_mime_type(conn->ctx, path, &mime_vec);
  3994. cl = filep->size;
  3995. conn->status_code = 200;
  3996. range[0] = '\0';
  3997. /* if this file is in fact a pre-gzipped file, rewrite its filename
  3998. * it's important to rewrite the filename after resolving
  3999. * the mime type from it, to preserve the actual file's type */
  4000. if (filep->gzipped) {
  4001. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  4002. path = gz_path;
  4003. encoding = "Content-Encoding: gzip\r\n";
  4004. }
  4005. if (!mg_fopen(conn, path, "rb", filep)) {
  4006. send_http_error(conn, 500, "Error: Cannot open file\nfopen(%s): %s",
  4007. path, strerror(ERRNO));
  4008. return;
  4009. }
  4010. fclose_on_exec(filep, conn);
  4011. /* If Range: header specified, act accordingly */
  4012. r1 = r2 = 0;
  4013. hdr = mg_get_header(conn, "Range");
  4014. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  4015. r2 >= 0) {
  4016. /* actually, range requests don't play well with a pre-gzipped
  4017. * file (since the range is specified in the uncompressed space) */
  4018. if (filep->gzipped) {
  4019. send_http_error(
  4020. conn, 501, "%s",
  4021. "Error: Range requests in gzipped files are not supported");
  4022. mg_fclose(filep);
  4023. return;
  4024. }
  4025. conn->status_code = 206;
  4026. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  4027. mg_snprintf(conn, range, sizeof(range),
  4028. "Content-Range: bytes "
  4029. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  4030. r1, r1 + cl - 1, filep->size);
  4031. msg = "Partial Content";
  4032. }
  4033. hdr = mg_get_header(conn, "Origin");
  4034. if (hdr) {
  4035. /* Cross-origin resource sharing (CORS), see
  4036. * http://www.html5rocks.com/en/tutorials/cors/,
  4037. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  4038. * preflight is not supported for files. */
  4039. cors1 = "Access-Control-Allow-Origin: ";
  4040. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4041. cors3 = "\r\n";
  4042. } else {
  4043. cors1 = cors2 = cors3 = "";
  4044. }
  4045. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  4046. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  4047. gmt_time_string(date, sizeof(date), &curtime);
  4048. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  4049. construct_etag(etag, sizeof(etag), filep);
  4050. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  4051. "%s%s%s"
  4052. "Date: %s\r\n"
  4053. "Last-Modified: %s\r\n"
  4054. "Etag: %s\r\n"
  4055. "Content-Type: %.*s\r\n"
  4056. "Content-Length: %" INT64_FMT "\r\n"
  4057. "Connection: %s\r\n"
  4058. "Accept-Ranges: bytes\r\n"
  4059. "%s%s\r\n",
  4060. conn->status_code, msg, cors1, cors2, cors3, date, lm, etag,
  4061. (int)mime_vec.len, mime_vec.ptr, cl,
  4062. suggest_connection_header(conn), range, encoding);
  4063. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  4064. send_file_data(conn, filep, r1, cl);
  4065. }
  4066. mg_fclose(filep);
  4067. }
  4068. void mg_send_file(struct mg_connection *conn, const char *path) {
  4069. struct file file = STRUCT_FILE_INITIALIZER;
  4070. if (mg_stat(conn, path, &file)) {
  4071. if (file.is_directory) {
  4072. if (!conn)
  4073. return;
  4074. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  4075. "yes")) {
  4076. handle_directory_request(conn, path);
  4077. } else {
  4078. send_http_error(conn, 403, "%s",
  4079. "Error: Directory listing denied");
  4080. }
  4081. } else {
  4082. handle_static_file_request(conn, path, &file);
  4083. }
  4084. } else {
  4085. send_http_error(conn, 404, "%s", "Error: File not found");
  4086. }
  4087. }
  4088. /* Parse HTTP headers from the given buffer, advance buffer to the point
  4089. * where parsing stopped. */
  4090. static void parse_http_headers(char **buf, struct mg_request_info *ri) {
  4091. int i;
  4092. if (!ri)
  4093. return;
  4094. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  4095. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  4096. ri->http_headers[i].value = skip(buf, "\r\n");
  4097. if (ri->http_headers[i].name[0] == '\0')
  4098. break;
  4099. ri->num_headers = i + 1;
  4100. }
  4101. }
  4102. static int is_valid_http_method(const char *method) {
  4103. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  4104. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  4105. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  4106. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  4107. !strcmp(method, "MKCOL");
  4108. }
  4109. /* Parse HTTP request, fill in mg_request_info structure.
  4110. * This function modifies the buffer by NUL-terminating
  4111. * HTTP request components, header names and header values. */
  4112. static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
  4113. int is_request, request_length = get_request_len(buf, len);
  4114. if (request_length > 0) {
  4115. if (!ri)
  4116. return 0;
  4117. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  4118. * remote_port */
  4119. ri->remote_user = ri->request_method = ri->uri = ri->http_version =
  4120. NULL;
  4121. ri->num_headers = 0;
  4122. buf[request_length - 1] = '\0';
  4123. /* RFC says that all initial whitespaces should be ingored */
  4124. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  4125. buf++;
  4126. }
  4127. ri->request_method = skip(&buf, " ");
  4128. ri->uri = skip(&buf, " ");
  4129. ri->http_version = skip(&buf, "\r\n");
  4130. /* HTTP message could be either HTTP request or HTTP response, e.g.
  4131. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  4132. is_request = is_valid_http_method(ri->request_method);
  4133. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  4134. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  4135. request_length = -1;
  4136. } else {
  4137. if (is_request) {
  4138. ri->http_version += 5;
  4139. }
  4140. parse_http_headers(&buf, ri);
  4141. }
  4142. }
  4143. return request_length;
  4144. }
  4145. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  4146. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  4147. * buffer (which marks the end of HTTP request). Buffer buf may already
  4148. * have some data. The length of the data is stored in nread.
  4149. * Upon every read operation, increase nread by the number of bytes read. */
  4150. static int read_request(FILE *fp, struct mg_connection *conn, char *buf,
  4151. int bufsiz, int *nread) {
  4152. int request_len, n = 0;
  4153. struct timespec last_action_time = {0, 0};
  4154. double request_timeout;
  4155. if (!conn)
  4156. return 0;
  4157. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4158. /* value of request_timeout is in seconds, config in milliseconds */
  4159. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4160. } else {
  4161. request_timeout = -1.0;
  4162. }
  4163. request_len = get_request_len(buf, *nread);
  4164. while ((conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  4165. (request_len == 0) &&
  4166. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  4167. request_timeout) ||
  4168. (request_timeout < 0)) &&
  4169. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0)) {
  4170. *nread += n;
  4171. /* assert(*nread <= bufsiz); */
  4172. if (*nread > bufsiz)
  4173. return -2;
  4174. request_len = get_request_len(buf, *nread);
  4175. if (request_timeout > 0.0) {
  4176. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  4177. }
  4178. }
  4179. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  4180. }
  4181. /* For given directory path, substitute it to valid index file.
  4182. * Return 1 if index file has been found, 0 if not found.
  4183. * If the file is found, it's stats is returned in stp. */
  4184. static int substitute_index_file(struct mg_connection *conn, char *path,
  4185. size_t path_len, struct file *filep) {
  4186. if (conn && conn->ctx) {
  4187. const char *list = conn->ctx->config[INDEX_FILES];
  4188. struct file file = STRUCT_FILE_INITIALIZER;
  4189. struct vec filename_vec;
  4190. size_t n = strlen(path);
  4191. int found = 0;
  4192. /* The 'path' given to us points to the directory. Remove all trailing
  4193. * directory separator characters from the end of the path, and
  4194. * then append single directory separator character. */
  4195. while (n > 0 && path[n - 1] == '/') {
  4196. n--;
  4197. }
  4198. path[n] = '/';
  4199. /* Traverse index files list. For each entry, append it to the given
  4200. * path and see if the file exists. If it exists, break the loop */
  4201. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  4202. /* Ignore too long entries that may overflow path buffer */
  4203. if (filename_vec.len > path_len - (n + 2))
  4204. continue;
  4205. /* Prepare full path to the index file */
  4206. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  4207. /* Does it exist? */
  4208. if (mg_stat(conn, path, &file)) {
  4209. /* Yes it does, break the loop */
  4210. *filep = file;
  4211. found = 1;
  4212. break;
  4213. }
  4214. }
  4215. /* If no index file exists, restore directory path */
  4216. if (!found) {
  4217. path[n] = '\0';
  4218. }
  4219. return found;
  4220. }
  4221. return 0;
  4222. }
  4223. /* Return True if we should reply 304 Not Modified. */
  4224. static int is_not_modified(const struct mg_connection *conn,
  4225. const struct file *filep) {
  4226. char etag[64];
  4227. const char *ims = mg_get_header(conn, "If-Modified-Since");
  4228. const char *inm = mg_get_header(conn, "If-None-Match");
  4229. construct_etag(etag, sizeof(etag), filep);
  4230. if (!filep)
  4231. return 0;
  4232. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  4233. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  4234. }
  4235. static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock,
  4236. SSL *ssl) {
  4237. const char *expect, *body;
  4238. char buf[MG_BUF_LEN];
  4239. int to_read, nread, success = 0;
  4240. int64_t buffered_len;
  4241. if (!conn)
  4242. return 0;
  4243. expect = mg_get_header(conn, "Expect");
  4244. /* assert(fp != NULL); */
  4245. if (!fp) {
  4246. send_http_error(conn, 500, "%s", "Error: NULL File");
  4247. return 0;
  4248. }
  4249. if (conn->content_len == -1 && !conn->is_chunked) {
  4250. /* Content length is not specified by the client. */
  4251. send_http_error(conn, 411, "%s",
  4252. "Error: Client did not specify content length");
  4253. } else if ((expect != NULL) &&
  4254. (mg_strcasecmp(expect, "100-continue") != 0)) {
  4255. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  4256. send_http_error(conn, 417, "Error: Can not fulfill expectation %s",
  4257. expect);
  4258. } else {
  4259. if (expect != NULL) {
  4260. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  4261. conn->status_code = 100;
  4262. } else {
  4263. conn->status_code = 200;
  4264. }
  4265. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  4266. conn->consumed_content;
  4267. /*
  4268. assert(buffered_len >= 0);
  4269. assert(conn->consumed_content == 0);
  4270. */
  4271. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  4272. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  4273. return 0;
  4274. }
  4275. if (buffered_len > 0) {
  4276. if ((int64_t)buffered_len > conn->content_len) {
  4277. buffered_len = (int)conn->content_len;
  4278. }
  4279. body = conn->buf + conn->request_len + conn->consumed_content;
  4280. push(fp, sock, ssl, body, (int64_t)buffered_len);
  4281. conn->consumed_content += buffered_len;
  4282. }
  4283. nread = 0;
  4284. while (conn->consumed_content < conn->content_len) {
  4285. to_read = sizeof(buf);
  4286. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  4287. to_read = (int)(conn->content_len - conn->consumed_content);
  4288. }
  4289. nread = pull(NULL, conn, buf, to_read);
  4290. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  4291. break;
  4292. }
  4293. conn->consumed_content += nread;
  4294. }
  4295. if (conn->consumed_content == conn->content_len) {
  4296. success = nread >= 0;
  4297. }
  4298. /* Each error code path in this function must send an error */
  4299. if (!success) {
  4300. /* TODO: Maybe some data has already been sent. */
  4301. send_http_error(conn, 500, "%s", "");
  4302. }
  4303. }
  4304. return success;
  4305. }
  4306. #if !defined(NO_CGI)
  4307. /* This structure helps to create an environment for the spawned CGI program.
  4308. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  4309. * last element must be NULL.
  4310. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  4311. * strings must reside in a contiguous buffer. The end of the buffer is
  4312. * marked by two '\0' characters.
  4313. * We satisfy both worlds: we create an envp array (which is vars), all
  4314. * entries are actually pointers inside buf. */
  4315. struct cgi_env_block {
  4316. struct mg_connection *conn;
  4317. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  4318. int len; /* Space taken */
  4319. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  4320. int nvars; /* Number of variables */
  4321. };
  4322. static char *addenv(struct cgi_env_block *block,
  4323. PRINTF_FORMAT_STRING(const char *fmt), ...)
  4324. PRINTF_ARGS(2, 3);
  4325. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  4326. * pointer into the vars array. */
  4327. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  4328. int n, space;
  4329. char *added;
  4330. va_list ap;
  4331. if (!block)
  4332. return NULL;
  4333. /* Calculate how much space is left in the buffer */
  4334. space = sizeof(block->buf) - block->len - 2;
  4335. /* assert(space >= 0); */
  4336. if (space < 0)
  4337. return NULL;
  4338. /* Make a pointer to the free space int the buffer */
  4339. added = block->buf + block->len;
  4340. /* Copy VARIABLE=VALUE\0 string into the free space */
  4341. va_start(ap, fmt);
  4342. n = mg_vsnprintf(block->conn, added, (size_t)space, fmt, ap);
  4343. va_end(ap);
  4344. /* Make sure we do not overflow buffer and the envp array */
  4345. if (n > 0 && n + 1 < space &&
  4346. block->nvars < (int)ARRAY_SIZE(block->vars) - 2) {
  4347. /* Append a pointer to the added string into the envp array */
  4348. block->vars[block->nvars++] = added;
  4349. /* Bump up used length counter. Include \0 terminator */
  4350. block->len += n + 1;
  4351. } else {
  4352. mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__,
  4353. fmt);
  4354. }
  4355. return added;
  4356. }
  4357. static void prepare_cgi_environment(struct mg_connection *conn,
  4358. const char *prog,
  4359. struct cgi_env_block *blk) {
  4360. const char *s;
  4361. struct vec var_vec;
  4362. char *p, src_addr[IP_ADDR_STR_LEN];
  4363. int i;
  4364. if (conn == NULL || blk == NULL)
  4365. return;
  4366. blk->len = blk->nvars = 0;
  4367. blk->conn = conn;
  4368. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  4369. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  4370. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  4371. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  4372. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  4373. /* Prepare the environment block */
  4374. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  4375. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  4376. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  4377. /* TODO(lsm): fix this for IPv6 case */
  4378. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  4379. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  4380. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  4381. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  4382. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  4383. /* SCRIPT_NAME */
  4384. addenv(blk, "SCRIPT_NAME=%.*s",
  4385. (int)strlen(conn->request_info.uri) -
  4386. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  4387. conn->request_info.uri);
  4388. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  4389. if (conn->path_info == NULL) {
  4390. addenv(blk, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  4391. } else {
  4392. addenv(blk, "PATH_TRANSLATED=%s%s", conn->ctx->config[DOCUMENT_ROOT],
  4393. conn->path_info);
  4394. }
  4395. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  4396. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  4397. addenv(blk, "CONTENT_TYPE=%s", s);
  4398. if (conn->request_info.query_string != NULL)
  4399. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  4400. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  4401. addenv(blk, "CONTENT_LENGTH=%s", s);
  4402. if ((s = getenv("PATH")) != NULL)
  4403. addenv(blk, "PATH=%s", s);
  4404. if (conn->path_info != NULL) {
  4405. addenv(blk, "PATH_INFO=%s", conn->path_info);
  4406. }
  4407. if (conn->status_code > 0) {
  4408. /* CGI error handler should show the status code */
  4409. addenv(blk, "STATUS=%d", conn->status_code);
  4410. }
  4411. #if defined(_WIN32)
  4412. if ((s = getenv("COMSPEC")) != NULL) {
  4413. addenv(blk, "COMSPEC=%s", s);
  4414. }
  4415. if ((s = getenv("SYSTEMROOT")) != NULL) {
  4416. addenv(blk, "SYSTEMROOT=%s", s);
  4417. }
  4418. if ((s = getenv("SystemDrive")) != NULL) {
  4419. addenv(blk, "SystemDrive=%s", s);
  4420. }
  4421. if ((s = getenv("ProgramFiles")) != NULL) {
  4422. addenv(blk, "ProgramFiles=%s", s);
  4423. }
  4424. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  4425. addenv(blk, "ProgramFiles(x86)=%s", s);
  4426. }
  4427. #else
  4428. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  4429. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  4430. #endif /* _WIN32 */
  4431. if ((s = getenv("PERLLIB")) != NULL)
  4432. addenv(blk, "PERLLIB=%s", s);
  4433. if (conn->request_info.remote_user != NULL) {
  4434. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  4435. addenv(blk, "%s", "AUTH_TYPE=Digest");
  4436. }
  4437. /* Add all headers as HTTP_* variables */
  4438. for (i = 0; i < conn->request_info.num_headers; i++) {
  4439. p = addenv(blk, "HTTP_%s=%s", conn->request_info.http_headers[i].name,
  4440. conn->request_info.http_headers[i].value);
  4441. /* Convert variable name into uppercase, and change - to _ */
  4442. for (; *p != '=' && *p != '\0'; p++) {
  4443. if (*p == '-')
  4444. *p = '_';
  4445. *p = (char)toupper(*(unsigned char *)p);
  4446. }
  4447. }
  4448. /* Add user-specified variables */
  4449. s = conn->ctx->config[CGI_ENVIRONMENT];
  4450. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  4451. addenv(blk, "%.*s", (int)var_vec.len, var_vec.ptr);
  4452. }
  4453. blk->vars[blk->nvars++] = NULL;
  4454. blk->buf[blk->len++] = '\0';
  4455. /*
  4456. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  4457. assert(blk->len > 0);
  4458. assert(blk->len < (int) sizeof(blk->buf));
  4459. */
  4460. if ((blk->nvars >= (int)ARRAY_SIZE(blk->vars)) || (blk->len <= 0) ||
  4461. (blk->len >= (int)sizeof(blk->buf)))
  4462. return;
  4463. }
  4464. static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
  4465. char *buf;
  4466. size_t buflen;
  4467. int headers_len, data_len, i, fdin[2] = {0, 0}, fdout[2] = {0, 0};
  4468. const char *status, *status_text, *connection_state;
  4469. char *pbuf, dir[PATH_MAX], *p;
  4470. struct mg_request_info ri;
  4471. struct cgi_env_block blk;
  4472. FILE *in = NULL, *out = NULL;
  4473. struct file fout = STRUCT_FILE_INITIALIZER;
  4474. pid_t pid = (pid_t)-1;
  4475. if (conn == NULL)
  4476. return;
  4477. buf = NULL;
  4478. buflen = 16384;
  4479. prepare_cgi_environment(conn, prog, &blk);
  4480. /* CGI must be executed in its own directory. 'dir' must point to the
  4481. * directory containing executable program, 'p' must point to the
  4482. * executable program name relative to 'dir'. */
  4483. (void)mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  4484. if ((p = strrchr(dir, '/')) != NULL) {
  4485. *p++ = '\0';
  4486. } else {
  4487. dir[0] = '.', dir[1] = '\0';
  4488. p = (char *)prog;
  4489. }
  4490. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  4491. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s",
  4492. strerror(ERRNO));
  4493. goto done;
  4494. }
  4495. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  4496. if (pid == (pid_t)-1) {
  4497. send_http_error(conn, 500, "Error: Cannot spawn CGI process [%s]: %s",
  4498. prog, strerror(ERRNO));
  4499. goto done;
  4500. }
  4501. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  4502. set_close_on_exec(fdin[0], conn);
  4503. set_close_on_exec(fdin[1], conn);
  4504. set_close_on_exec(fdout[0], conn);
  4505. set_close_on_exec(fdout[1], conn);
  4506. /* Parent closes only one side of the pipes.
  4507. * If we don't mark them as closed, close() attempt before
  4508. * return from this function throws an exception on Windows.
  4509. * Windows does not like when closed descriptor is closed again. */
  4510. (void)close(fdin[0]);
  4511. (void)close(fdout[1]);
  4512. fdin[0] = fdout[1] = -1;
  4513. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  4514. send_http_error(conn, 500, "Error: CGI can not open fdin\nfopen: %s",
  4515. strerror(ERRNO));
  4516. goto done;
  4517. }
  4518. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  4519. send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s",
  4520. strerror(ERRNO));
  4521. goto done;
  4522. }
  4523. setbuf(in, NULL);
  4524. setbuf(out, NULL);
  4525. fout.fp = out;
  4526. /* Send POST or PUT data to the CGI process if needed */
  4527. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  4528. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  4529. /* This is a POST/PUT request */
  4530. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  4531. /* Error sending the body data */
  4532. goto done;
  4533. }
  4534. }
  4535. /* Close so child gets an EOF. */
  4536. fclose(in);
  4537. in = NULL;
  4538. fdin[1] = -1;
  4539. /* Now read CGI reply into a buffer. We need to set correct
  4540. * status code, thus we need to see all HTTP headers first.
  4541. * Do not send anything back to client, until we buffer in all
  4542. * HTTP headers. */
  4543. data_len = 0;
  4544. buf = (char *)mg_malloc(buflen);
  4545. if (buf == NULL) {
  4546. send_http_error(conn, 500,
  4547. "Error: Not enough memory for CGI buffer (%u bytes)",
  4548. (unsigned int)buflen);
  4549. goto done;
  4550. }
  4551. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  4552. if (headers_len <= 0) {
  4553. send_http_error(conn, 500,
  4554. "Error: CGI program sent malformed or too big "
  4555. "(>%u bytes) HTTP headers: [%.*s]",
  4556. (unsigned)buflen, data_len, buf);
  4557. goto done;
  4558. }
  4559. pbuf = buf;
  4560. buf[headers_len - 1] = '\0';
  4561. parse_http_headers(&pbuf, &ri);
  4562. /* Make up and send the status line */
  4563. status_text = "OK";
  4564. if ((status = get_header(&ri, "Status")) != NULL) {
  4565. conn->status_code = atoi(status);
  4566. status_text = status;
  4567. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  4568. status_text++;
  4569. }
  4570. } else if (get_header(&ri, "Location") != NULL) {
  4571. conn->status_code = 302;
  4572. } else {
  4573. conn->status_code = 200;
  4574. }
  4575. connection_state = get_header(&ri, "Connection");
  4576. if (connection_state == NULL ||
  4577. mg_strcasecmp(connection_state, "keep-alive")) {
  4578. conn->must_close = 1;
  4579. }
  4580. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  4581. /* Send headers */
  4582. for (i = 0; i < ri.num_headers; i++) {
  4583. mg_printf(conn, "%s: %s\r\n", ri.http_headers[i].name,
  4584. ri.http_headers[i].value);
  4585. }
  4586. mg_write(conn, "\r\n", 2);
  4587. /* Send chunk of data that may have been read after the headers */
  4588. conn->num_bytes_sent +=
  4589. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  4590. /* Read the rest of CGI output and send to the client */
  4591. send_file_data(conn, &fout, 0, INT64_MAX);
  4592. done:
  4593. if (pid != (pid_t)-1) {
  4594. kill(pid, SIGKILL);
  4595. #if !defined(_WIN32)
  4596. {
  4597. int st;
  4598. while (waitpid(pid, &st, 0) != -1)
  4599. ; /* clean zombies */
  4600. }
  4601. #endif
  4602. }
  4603. if (fdin[0] != -1) {
  4604. close(fdin[0]);
  4605. }
  4606. if (fdout[1] != -1) {
  4607. close(fdout[1]);
  4608. }
  4609. if (in != NULL) {
  4610. fclose(in);
  4611. } else if (fdin[1] != -1) {
  4612. close(fdin[1]);
  4613. }
  4614. if (out != NULL) {
  4615. fclose(out);
  4616. } else if (fdout[0] != -1) {
  4617. close(fdout[0]);
  4618. }
  4619. if (buf != NULL) {
  4620. mg_free(buf);
  4621. }
  4622. }
  4623. #endif /* !NO_CGI */
  4624. /* For a given PUT path, create all intermediate subdirectories.
  4625. * Return 0 if the path itself is a directory.
  4626. * Return 1 if the path leads to a file.
  4627. * Return -1 for if the path is too long.
  4628. * Return -2 if path can not be created.
  4629. */
  4630. static int put_dir(struct mg_connection *conn, const char *path) {
  4631. char buf[PATH_MAX];
  4632. const char *s, *p;
  4633. struct file file = STRUCT_FILE_INITIALIZER;
  4634. int len, res = 1;
  4635. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  4636. len = (int)(p - path);
  4637. if (len >= (int)sizeof(buf)) {
  4638. /* path too long */
  4639. res = -1;
  4640. break;
  4641. }
  4642. memcpy(buf, path, len);
  4643. buf[len] = '\0';
  4644. /* Try to create intermediate directory */
  4645. DEBUG_TRACE("mkdir(%s)", buf);
  4646. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  4647. /* path does not exixt and can not be created */
  4648. res = -2;
  4649. break;
  4650. }
  4651. /* Is path itself a directory? */
  4652. if (p[1] == '\0') {
  4653. res = 0;
  4654. }
  4655. }
  4656. return res;
  4657. }
  4658. static void mkcol(struct mg_connection *conn, const char *path) {
  4659. int rc, body_len;
  4660. struct de de;
  4661. char date[64];
  4662. time_t curtime = time(NULL);
  4663. if (conn == NULL)
  4664. return;
  4665. /* TODO: Check the send_http_error situations in this function */
  4666. memset(&de.file, 0, sizeof(de.file));
  4667. if (!mg_stat(conn, path, &de.file)) {
  4668. mg_cry(conn, "%s: mg_stat(%s) failed: %s", __func__, path,
  4669. strerror(ERRNO));
  4670. }
  4671. if (de.file.modification_time) {
  4672. send_http_error(conn, 405, "Error: mkcol(%s): %s", path,
  4673. strerror(ERRNO));
  4674. return;
  4675. }
  4676. body_len = conn->data_len - conn->request_len;
  4677. if (body_len > 0) {
  4678. send_http_error(conn, 415, "Error: mkcol(%s): %s", path,
  4679. strerror(ERRNO));
  4680. return;
  4681. }
  4682. rc = mg_mkdir(path, 0755);
  4683. if (rc == 0) {
  4684. conn->status_code = 201;
  4685. gmt_time_string(date, sizeof(date), &curtime);
  4686. mg_printf(conn, "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  4687. "0\r\nConnection: %s\r\n\r\n",
  4688. conn->status_code, date, suggest_connection_header(conn));
  4689. } else if (rc == -1) {
  4690. if (errno == EEXIST)
  4691. send_http_error(conn, 405, "Error:mkcol(%s): %s", path,
  4692. strerror(ERRNO));
  4693. else if (errno == EACCES)
  4694. send_http_error(conn, 403, "Error: mkcol(%s): %s", path,
  4695. strerror(ERRNO));
  4696. else if (errno == ENOENT)
  4697. send_http_error(conn, 409, "Error: mkcol(%s): %s", path,
  4698. strerror(ERRNO));
  4699. else
  4700. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  4701. }
  4702. }
  4703. static void put_file(struct mg_connection *conn, const char *path) {
  4704. struct file file = STRUCT_FILE_INITIALIZER;
  4705. const char *range;
  4706. int64_t r1, r2;
  4707. int rc;
  4708. char date[64];
  4709. time_t curtime = time(NULL);
  4710. if (conn == NULL)
  4711. return;
  4712. if (mg_stat(conn, path, &file)) {
  4713. /* File already exists */
  4714. conn->status_code = 200;
  4715. if (file.is_directory) {
  4716. /* This is an already existing directory,
  4717. so there is nothing to do for the server. */
  4718. rc = 0;
  4719. } else {
  4720. /* File exists and is not a directory. */
  4721. /* Can it be replaced? */
  4722. if (file.modification_time == 0) {
  4723. /* This is an "in-memory" file, that can not be replaced */
  4724. send_http_error(
  4725. conn, 405,
  4726. "Error: Put not possible\nReplacing %s is not supported",
  4727. path);
  4728. return;
  4729. }
  4730. /* Check if the server may write this file */
  4731. if (access(path, W_OK) == 0) {
  4732. /* Access granted */
  4733. conn->status_code = 200;
  4734. rc = 1;
  4735. } else {
  4736. send_http_error(
  4737. conn, 403,
  4738. "Error: Put not possible\nReplacing %s is not allowed",
  4739. path);
  4740. return;
  4741. }
  4742. }
  4743. } else {
  4744. /* File should be created */
  4745. conn->status_code = 201;
  4746. rc = put_dir(conn, path);
  4747. }
  4748. if (rc == 0) {
  4749. /* put_dir returns 0 if path is a directory */
  4750. gmt_time_string(date, sizeof(date), &curtime);
  4751. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  4752. "Date: %s\r\n"
  4753. "Content-Length: 0\r\n"
  4754. "Connection: %s\r\n\r\n",
  4755. conn->status_code,
  4756. mg_get_response_code_text(conn->status_code, NULL), date,
  4757. suggest_connection_header(conn));
  4758. /* Request to create a directory has been fulfilled successfully.
  4759. * No need to put a file. */
  4760. return;
  4761. }
  4762. if (rc == -1) {
  4763. /* put_dir returns -1 if the path is too long */
  4764. send_http_error(conn, 414, "Error: Path too long\nput_dir(%s): %s",
  4765. path, strerror(ERRNO));
  4766. return;
  4767. }
  4768. if (rc == -2) {
  4769. /* put_dir returns -2 if the directory can not be created */
  4770. send_http_error(conn, 500,
  4771. "Error: Can not create directory\nput_dir(%s): %s",
  4772. path, strerror(ERRNO));
  4773. return;
  4774. }
  4775. /* A file should be created or overwritten. */
  4776. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  4777. mg_fclose(&file);
  4778. send_http_error(conn, 500, "Error: Can not create file\nfopen(%s): %s",
  4779. path, strerror(ERRNO));
  4780. return;
  4781. }
  4782. fclose_on_exec(&file, conn);
  4783. range = mg_get_header(conn, "Content-Range");
  4784. r1 = r2 = 0;
  4785. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  4786. conn->status_code = 206; /* Partial content */
  4787. fseeko(file.fp, r1, SEEK_SET);
  4788. }
  4789. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  4790. /* forward_body_data failed.
  4791. * The error code has already been sent to the client,
  4792. * and conn->status_code is already set. */
  4793. return;
  4794. }
  4795. gmt_time_string(date, sizeof(date), &curtime);
  4796. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  4797. "Date: %s\r\n"
  4798. "Content-Length: 0\r\n"
  4799. "Connection: %s\r\n\r\n",
  4800. conn->status_code,
  4801. mg_get_response_code_text(conn->status_code, NULL), date,
  4802. suggest_connection_header(conn));
  4803. mg_fclose(&file);
  4804. }
  4805. static void delete_file(struct mg_connection *conn, const char *path) {
  4806. struct de de;
  4807. memset(&de.file, 0, sizeof(de.file));
  4808. if (!mg_stat(conn, path, &de.file)) {
  4809. /* mg_stat returns 0 if the file does not exist */
  4810. send_http_error(conn, 404,
  4811. "Error: Cannot delete file\nFile %s not found", path);
  4812. return;
  4813. }
  4814. if (de.file.modification_time == 0) {
  4815. /* mg_stat returns != 0 and modification_time == 0
  4816. * if the file is cached in memory */
  4817. send_http_error(
  4818. conn, 405,
  4819. "Error: Delete not possible\nDeleting %s is not supported", path);
  4820. return;
  4821. }
  4822. if (de.file.is_directory) {
  4823. remove_directory(conn, path);
  4824. /* TODO: remove_dir does not return success of the operation */
  4825. /* Assume delete is successful: Return 204 without content. */
  4826. send_http_error(conn, 204, "%s", "");
  4827. return;
  4828. }
  4829. /* This is an existing file (not a directory).
  4830. * Check if write permission is granted. */
  4831. if (access(path, W_OK) != 0) {
  4832. /* File is read only */
  4833. send_http_error(
  4834. conn, 403, "Error: Delete not possible\nDeleting %s is not allowed",
  4835. path);
  4836. return;
  4837. }
  4838. /* Try to delete it. */
  4839. if (mg_remove(path) == 0) {
  4840. /* Delete was successful: Return 204 without content. */
  4841. send_http_error(conn, 204, "%s", "");
  4842. } else {
  4843. /* Delete not successful (file locked). */
  4844. send_http_error(conn, 423, "Error: Cannot delete file\nremove(%s): %s",
  4845. path, strerror(ERRNO));
  4846. }
  4847. }
  4848. static void send_ssi_file(struct mg_connection *, const char *, struct file *,
  4849. int);
  4850. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  4851. char *tag, int include_level) {
  4852. char file_name[MG_BUF_LEN], path[512], *p;
  4853. struct file file = STRUCT_FILE_INITIALIZER;
  4854. size_t len;
  4855. if (conn == NULL)
  4856. return;
  4857. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  4858. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  4859. * always < MG_BUF_LEN. */
  4860. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  4861. /* File name is relative to the webserver root */
  4862. file_name[511] = 0;
  4863. (void)mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  4864. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  4865. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  4866. /* File name is relative to the webserver working directory
  4867. * or it is absolute system path */
  4868. file_name[511] = 0;
  4869. (void)mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  4870. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  4871. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  4872. /* File name is relative to the currect document */
  4873. file_name[511] = 0;
  4874. (void)mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  4875. if ((p = strrchr(path, '/')) != NULL) {
  4876. p[1] = '\0';
  4877. }
  4878. len = strlen(path);
  4879. (void)mg_snprintf(conn, path + len, sizeof(path) - len, "%s",
  4880. file_name);
  4881. } else {
  4882. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  4883. return;
  4884. }
  4885. if (!mg_fopen(conn, path, "rb", &file)) {
  4886. mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s", tag, path,
  4887. strerror(ERRNO));
  4888. } else {
  4889. fclose_on_exec(&file, conn);
  4890. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  4891. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  4892. path) > 0) {
  4893. send_ssi_file(conn, path, &file, include_level + 1);
  4894. } else {
  4895. send_file_data(conn, &file, 0, INT64_MAX);
  4896. }
  4897. mg_fclose(&file);
  4898. }
  4899. }
  4900. #if !defined(NO_POPEN)
  4901. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  4902. char cmd[1024] = "";
  4903. struct file file = STRUCT_FILE_INITIALIZER;
  4904. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  4905. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  4906. } else {
  4907. cmd[1023] = 0;
  4908. if ((file.fp = popen(cmd, "r")) == NULL) {
  4909. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  4910. } else {
  4911. send_file_data(conn, &file, 0, INT64_MAX);
  4912. pclose(file.fp);
  4913. }
  4914. }
  4915. }
  4916. #endif /* !NO_POPEN */
  4917. static int mg_fgetc(struct file *filep, int offset) {
  4918. if (filep == NULL)
  4919. return EOF;
  4920. if (filep->membuf != NULL && offset >= 0 && offset < filep->size) {
  4921. return ((unsigned char *)filep->membuf)[offset];
  4922. } else if (filep->fp != NULL) {
  4923. return fgetc(filep->fp);
  4924. } else {
  4925. return EOF;
  4926. }
  4927. }
  4928. static void send_ssi_file(struct mg_connection *conn, const char *path,
  4929. struct file *filep, int include_level) {
  4930. char buf[MG_BUF_LEN];
  4931. int ch, offset, len, in_ssi_tag;
  4932. if (include_level > 10) {
  4933. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  4934. return;
  4935. }
  4936. in_ssi_tag = len = offset = 0;
  4937. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  4938. if (in_ssi_tag && ch == '>') {
  4939. in_ssi_tag = 0;
  4940. buf[len++] = (char)ch;
  4941. buf[len] = '\0';
  4942. /* assert(len <= (int) sizeof(buf)); */
  4943. if (len > (int)sizeof(buf))
  4944. break;
  4945. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  4946. /* Not an SSI tag, pass it */
  4947. (void)mg_write(conn, buf, (size_t)len);
  4948. } else {
  4949. if (!memcmp(buf + 5, "include", 7)) {
  4950. do_ssi_include(conn, path, buf + 12, include_level);
  4951. #if !defined(NO_POPEN)
  4952. } else if (!memcmp(buf + 5, "exec", 4)) {
  4953. do_ssi_exec(conn, buf + 9);
  4954. #endif /* !NO_POPEN */
  4955. } else {
  4956. mg_cry(conn, "%s: unknown SSI "
  4957. "command: \"%s\"",
  4958. path, buf);
  4959. }
  4960. }
  4961. len = 0;
  4962. } else if (in_ssi_tag) {
  4963. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  4964. /* Not an SSI tag */
  4965. in_ssi_tag = 0;
  4966. } else if (len == (int)sizeof(buf) - 2) {
  4967. mg_cry(conn, "%s: SSI tag is too large", path);
  4968. len = 0;
  4969. }
  4970. buf[len++] = ch & 0xff;
  4971. } else if (ch == '<') {
  4972. in_ssi_tag = 1;
  4973. if (len > 0) {
  4974. mg_write(conn, buf, (size_t)len);
  4975. }
  4976. len = 0;
  4977. buf[len++] = ch & 0xff;
  4978. } else {
  4979. buf[len++] = ch & 0xff;
  4980. if (len == (int)sizeof(buf)) {
  4981. mg_write(conn, buf, (size_t)len);
  4982. len = 0;
  4983. }
  4984. }
  4985. }
  4986. /* Send the rest of buffered data */
  4987. if (len > 0) {
  4988. mg_write(conn, buf, (size_t)len);
  4989. }
  4990. }
  4991. static void handle_ssi_file_request(struct mg_connection *conn,
  4992. const char *path, struct file *filep) {
  4993. char date[64];
  4994. time_t curtime = time(NULL);
  4995. const char *cors1, *cors2, *cors3;
  4996. if (!conn)
  4997. return;
  4998. if (mg_get_header(conn, "Origin")) {
  4999. /* Cross-origin resource sharing (CORS). */
  5000. cors1 = "Access-Control-Allow-Origin: ";
  5001. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5002. cors3 = "\r\n";
  5003. } else {
  5004. cors1 = cors2 = cors3 = "";
  5005. }
  5006. if (!mg_fopen(conn, path, "rb", filep)) {
  5007. /* File exists (precondition for calling this function),
  5008. * but can not be opened by the server. */
  5009. send_http_error(conn, 500, "Error: Cannot read file\nfopen(%s): %s",
  5010. path, strerror(ERRNO));
  5011. } else {
  5012. conn->must_close = 1;
  5013. gmt_time_string(date, sizeof(date), &curtime);
  5014. fclose_on_exec(filep, conn);
  5015. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  5016. "%s%s%s"
  5017. "Date: %s\r\n"
  5018. "Content-Type: text/html\r\n"
  5019. "Connection: %s\r\n\r\n",
  5020. cors1, cors2, cors3, date, suggest_connection_header(conn));
  5021. send_ssi_file(conn, path, filep, 0);
  5022. mg_fclose(filep);
  5023. }
  5024. }
  5025. static void send_options(struct mg_connection *conn) {
  5026. char date[64];
  5027. time_t curtime = time(NULL);
  5028. if (!conn)
  5029. return;
  5030. conn->status_code = 200;
  5031. conn->must_close = 1;
  5032. gmt_time_string(date, sizeof(date), &curtime);
  5033. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  5034. "Date: %s\r\n"
  5035. "Connection: %s\r\n"
  5036. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  5037. "PROPFIND, MKCOL\r\n"
  5038. "DAV: 1\r\n\r\n",
  5039. date, suggest_connection_header(conn));
  5040. }
  5041. /* Writes PROPFIND properties for a collection element */
  5042. static void print_props(struct mg_connection *conn, const char *uri,
  5043. struct file *filep) {
  5044. char mtime[64];
  5045. if (!filep || !conn)
  5046. return;
  5047. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  5048. conn->num_bytes_sent += mg_printf(
  5049. conn, "<d:response>"
  5050. "<d:href>%s</d:href>"
  5051. "<d:propstat>"
  5052. "<d:prop>"
  5053. "<d:resourcetype>%s</d:resourcetype>"
  5054. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  5055. "<d:getlastmodified>%s</d:getlastmodified>"
  5056. "</d:prop>"
  5057. "<d:status>HTTP/1.1 200 OK</d:status>"
  5058. "</d:propstat>"
  5059. "</d:response>\n",
  5060. uri, filep->is_directory ? "<d:collection/>" : "", filep->size, mtime);
  5061. }
  5062. static void print_dav_dir_entry(struct de *de, void *data) {
  5063. char href[PATH_MAX];
  5064. char href_encoded[PATH_MAX];
  5065. struct mg_connection *conn = (struct mg_connection *)data;
  5066. if (!de || !conn)
  5067. return;
  5068. mg_snprintf(conn, href, sizeof(href), "%s%s", conn->request_info.uri,
  5069. de->file_name);
  5070. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  5071. print_props(conn, href_encoded, &de->file);
  5072. }
  5073. static void handle_propfind(struct mg_connection *conn, const char *path,
  5074. struct file *filep) {
  5075. const char *depth = mg_get_header(conn, "Depth");
  5076. char date[64];
  5077. time_t curtime = time(NULL);
  5078. gmt_time_string(date, sizeof(date), &curtime);
  5079. if (!conn)
  5080. return;
  5081. conn->must_close = 1;
  5082. conn->status_code = 207;
  5083. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  5084. "Date: %s\r\n"
  5085. "Connection: %s\r\n"
  5086. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  5087. date, suggest_connection_header(conn));
  5088. conn->num_bytes_sent +=
  5089. mg_printf(conn, "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  5090. "<d:multistatus xmlns:d='DAV:'>\n");
  5091. /* Print properties for the requested resource itself */
  5092. print_props(conn, conn->request_info.uri, filep);
  5093. /* If it is a directory, print directory entries too if Depth is not 0 */
  5094. if (filep && conn->ctx && filep->is_directory &&
  5095. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  5096. (depth == NULL || strcmp(depth, "0") != 0)) {
  5097. scan_directory(conn, path, conn, &print_dav_dir_entry);
  5098. }
  5099. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  5100. }
  5101. void mg_lock_connection(struct mg_connection *conn) {
  5102. if (conn)
  5103. (void)pthread_mutex_lock(&conn->mutex);
  5104. }
  5105. void mg_unlock_connection(struct mg_connection *conn) {
  5106. if (conn)
  5107. (void)pthread_mutex_unlock(&conn->mutex);
  5108. }
  5109. void mg_lock_context(struct mg_context *ctx) {
  5110. if (ctx)
  5111. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  5112. }
  5113. void mg_unlock_context(struct mg_context *ctx) {
  5114. if (ctx)
  5115. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  5116. }
  5117. #if defined(USE_TIMERS)
  5118. #include "timer.inl"
  5119. #endif /* USE_TIMERS */
  5120. #ifdef USE_LUA
  5121. #include "mod_lua.inl"
  5122. #endif /* USE_LUA */
  5123. #if defined(USE_WEBSOCKET)
  5124. /* START OF SHA-1 code
  5125. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  5126. #define SHA1HANDSOFF
  5127. #if defined(__sun)
  5128. #include "solarisfixes.h"
  5129. #endif
  5130. static int is_big_endian(void) {
  5131. static const int n = 1;
  5132. return ((char *)&n)[0] == 0;
  5133. }
  5134. union char64long16 {
  5135. unsigned char c[64];
  5136. uint32_t l[16];
  5137. };
  5138. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5139. static uint32_t blk0(union char64long16 *block, int i) {
  5140. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  5141. if (!is_big_endian()) {
  5142. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5143. (rol(block->l[i], 8) & 0x00FF00FF);
  5144. }
  5145. return block->l[i];
  5146. }
  5147. #define blk(i) \
  5148. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5149. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5150. 1))
  5151. #define R0(v, w, x, y, z, i) \
  5152. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5153. w = rol(w, 30);
  5154. #define R1(v, w, x, y, z, i) \
  5155. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5156. w = rol(w, 30);
  5157. #define R2(v, w, x, y, z, i) \
  5158. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5159. w = rol(w, 30);
  5160. #define R3(v, w, x, y, z, i) \
  5161. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5162. w = rol(w, 30);
  5163. #define R4(v, w, x, y, z, i) \
  5164. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5165. w = rol(w, 30);
  5166. typedef struct {
  5167. uint32_t state[5];
  5168. uint32_t count[2];
  5169. unsigned char buffer[64];
  5170. } SHA1_CTX;
  5171. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  5172. uint32_t a, b, c, d, e;
  5173. union char64long16 block[1];
  5174. memcpy(block, buffer, 64);
  5175. a = state[0];
  5176. b = state[1];
  5177. c = state[2];
  5178. d = state[3];
  5179. e = state[4];
  5180. R0(a, b, c, d, e, 0);
  5181. R0(e, a, b, c, d, 1);
  5182. R0(d, e, a, b, c, 2);
  5183. R0(c, d, e, a, b, 3);
  5184. R0(b, c, d, e, a, 4);
  5185. R0(a, b, c, d, e, 5);
  5186. R0(e, a, b, c, d, 6);
  5187. R0(d, e, a, b, c, 7);
  5188. R0(c, d, e, a, b, 8);
  5189. R0(b, c, d, e, a, 9);
  5190. R0(a, b, c, d, e, 10);
  5191. R0(e, a, b, c, d, 11);
  5192. R0(d, e, a, b, c, 12);
  5193. R0(c, d, e, a, b, 13);
  5194. R0(b, c, d, e, a, 14);
  5195. R0(a, b, c, d, e, 15);
  5196. R1(e, a, b, c, d, 16);
  5197. R1(d, e, a, b, c, 17);
  5198. R1(c, d, e, a, b, 18);
  5199. R1(b, c, d, e, a, 19);
  5200. R2(a, b, c, d, e, 20);
  5201. R2(e, a, b, c, d, 21);
  5202. R2(d, e, a, b, c, 22);
  5203. R2(c, d, e, a, b, 23);
  5204. R2(b, c, d, e, a, 24);
  5205. R2(a, b, c, d, e, 25);
  5206. R2(e, a, b, c, d, 26);
  5207. R2(d, e, a, b, c, 27);
  5208. R2(c, d, e, a, b, 28);
  5209. R2(b, c, d, e, a, 29);
  5210. R2(a, b, c, d, e, 30);
  5211. R2(e, a, b, c, d, 31);
  5212. R2(d, e, a, b, c, 32);
  5213. R2(c, d, e, a, b, 33);
  5214. R2(b, c, d, e, a, 34);
  5215. R2(a, b, c, d, e, 35);
  5216. R2(e, a, b, c, d, 36);
  5217. R2(d, e, a, b, c, 37);
  5218. R2(c, d, e, a, b, 38);
  5219. R2(b, c, d, e, a, 39);
  5220. R3(a, b, c, d, e, 40);
  5221. R3(e, a, b, c, d, 41);
  5222. R3(d, e, a, b, c, 42);
  5223. R3(c, d, e, a, b, 43);
  5224. R3(b, c, d, e, a, 44);
  5225. R3(a, b, c, d, e, 45);
  5226. R3(e, a, b, c, d, 46);
  5227. R3(d, e, a, b, c, 47);
  5228. R3(c, d, e, a, b, 48);
  5229. R3(b, c, d, e, a, 49);
  5230. R3(a, b, c, d, e, 50);
  5231. R3(e, a, b, c, d, 51);
  5232. R3(d, e, a, b, c, 52);
  5233. R3(c, d, e, a, b, 53);
  5234. R3(b, c, d, e, a, 54);
  5235. R3(a, b, c, d, e, 55);
  5236. R3(e, a, b, c, d, 56);
  5237. R3(d, e, a, b, c, 57);
  5238. R3(c, d, e, a, b, 58);
  5239. R3(b, c, d, e, a, 59);
  5240. R4(a, b, c, d, e, 60);
  5241. R4(e, a, b, c, d, 61);
  5242. R4(d, e, a, b, c, 62);
  5243. R4(c, d, e, a, b, 63);
  5244. R4(b, c, d, e, a, 64);
  5245. R4(a, b, c, d, e, 65);
  5246. R4(e, a, b, c, d, 66);
  5247. R4(d, e, a, b, c, 67);
  5248. R4(c, d, e, a, b, 68);
  5249. R4(b, c, d, e, a, 69);
  5250. R4(a, b, c, d, e, 70);
  5251. R4(e, a, b, c, d, 71);
  5252. R4(d, e, a, b, c, 72);
  5253. R4(c, d, e, a, b, 73);
  5254. R4(b, c, d, e, a, 74);
  5255. R4(a, b, c, d, e, 75);
  5256. R4(e, a, b, c, d, 76);
  5257. R4(d, e, a, b, c, 77);
  5258. R4(c, d, e, a, b, 78);
  5259. R4(b, c, d, e, a, 79);
  5260. state[0] += a;
  5261. state[1] += b;
  5262. state[2] += c;
  5263. state[3] += d;
  5264. state[4] += e;
  5265. a = b = c = d = e = 0;
  5266. memset(block, '\0', sizeof(block));
  5267. }
  5268. static void SHA1Init(SHA1_CTX *context) {
  5269. context->state[0] = 0x67452301;
  5270. context->state[1] = 0xEFCDAB89;
  5271. context->state[2] = 0x98BADCFE;
  5272. context->state[3] = 0x10325476;
  5273. context->state[4] = 0xC3D2E1F0;
  5274. context->count[0] = context->count[1] = 0;
  5275. }
  5276. static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
  5277. uint32_t len) {
  5278. uint32_t i, j;
  5279. j = context->count[0];
  5280. if ((context->count[0] += len << 3) < j)
  5281. context->count[1]++;
  5282. context->count[1] += (len >> 29);
  5283. j = (j >> 3) & 63;
  5284. if ((j + len) > 63) {
  5285. memcpy(&context->buffer[j], data, (i = 64 - j));
  5286. SHA1Transform(context->state, context->buffer);
  5287. for (; i + 63 < len; i += 64) {
  5288. SHA1Transform(context->state, &data[i]);
  5289. }
  5290. j = 0;
  5291. } else
  5292. i = 0;
  5293. memcpy(&context->buffer[j], &data[i], len - i);
  5294. }
  5295. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
  5296. unsigned i;
  5297. unsigned char finalcount[8], c;
  5298. for (i = 0; i < 8; i++) {
  5299. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  5300. ((3 - (i & 3)) * 8)) &
  5301. 255);
  5302. }
  5303. c = 0200;
  5304. SHA1Update(context, &c, 1);
  5305. while ((context->count[0] & 504) != 448) {
  5306. c = 0000;
  5307. SHA1Update(context, &c, 1);
  5308. }
  5309. SHA1Update(context, finalcount, 8);
  5310. for (i = 0; i < 20; i++) {
  5311. digest[i] =
  5312. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  5313. 255);
  5314. }
  5315. memset(context, '\0', sizeof(*context));
  5316. memset(&finalcount, '\0', sizeof(finalcount));
  5317. }
  5318. /* END OF SHA1 CODE */
  5319. static void send_websocket_handshake(struct mg_connection *conn) {
  5320. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  5321. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  5322. SHA1_CTX sha_ctx;
  5323. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  5324. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  5325. SHA1Init(&sha_ctx);
  5326. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  5327. SHA1Final((unsigned char *)sha, &sha_ctx);
  5328. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  5329. mg_printf(conn, "%s%s%s", "HTTP/1.1 101 Switching Protocols\r\n"
  5330. "Upgrade: websocket\r\n"
  5331. "Connection: Upgrade\r\n"
  5332. "Sec-WebSocket-Accept: ",
  5333. b64_sha, "\r\n\r\n");
  5334. }
  5335. static void read_websocket(struct mg_connection *conn,
  5336. mg_websocket_data_handler ws_data_handler,
  5337. void *callback_data) {
  5338. /* Pointer to the beginning of the portion of the incoming websocket
  5339. * message queue.
  5340. * The original websocket upgrade request is never removed, so the queue
  5341. * begins after it. */
  5342. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  5343. int n, error, exit_by_callback;
  5344. /* body_len is the length of the entire queue in bytes
  5345. * len is the length of the current message
  5346. * data_len is the length of the current message's data payload
  5347. * header_len is the length of the current message's header */
  5348. size_t i, len, mask_len, data_len, header_len, body_len;
  5349. /* "The masking key is a 32-bit value chosen at random by the client."
  5350. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  5351. */
  5352. unsigned char mask[4];
  5353. /* data points to the place where the message is stored when passed to the
  5354. * websocket_data callback. This is either mem on the stack, or a
  5355. * dynamically allocated buffer if it is too large. */
  5356. char mem[4096];
  5357. char *data = mem;
  5358. unsigned char mop; /* mask flag and opcode */
  5359. mg_set_thread_name("wsock");
  5360. /* Loop continuously, reading messages from the socket, invoking the
  5361. * callback, and waiting repeatedly until an error occurs. */
  5362. /* TODO: Investigate if this next line is needed */
  5363. /* assert(conn->content_len == 0); */
  5364. while (!conn->ctx->stop_flag) {
  5365. header_len = 0;
  5366. assert(conn->data_len >= conn->request_len);
  5367. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  5368. len = buf[1] & 127;
  5369. mask_len = buf[1] & 128 ? 4 : 0;
  5370. if (len < 126 && body_len >= mask_len) {
  5371. data_len = len;
  5372. header_len = 2 + mask_len;
  5373. } else if (len == 126 && body_len >= 4 + mask_len) {
  5374. header_len = 4 + mask_len;
  5375. data_len = ((((int)buf[2]) << 8) + buf[3]);
  5376. } else if (body_len >= 10 + mask_len) {
  5377. header_len = 10 + mask_len;
  5378. data_len = (((uint64_t)ntohl(*(uint32_t *)&buf[2])) << 32) +
  5379. ntohl(*(uint32_t *)&buf[6]);
  5380. }
  5381. }
  5382. if (header_len > 0 && body_len >= header_len) {
  5383. /* Allocate space to hold websocket payload */
  5384. data = mem;
  5385. if (data_len > sizeof(mem)) {
  5386. data = (char *)mg_malloc(data_len);
  5387. if (data == NULL) {
  5388. /* Allocation failed, exit the loop and then close the
  5389. * connection */
  5390. mg_cry(conn, "websocket out of memory; closing connection");
  5391. break;
  5392. }
  5393. }
  5394. /* Copy the mask before we shift the queue and destroy it */
  5395. if (mask_len > 0) {
  5396. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  5397. } else {
  5398. memset(mask, 0, sizeof(mask));
  5399. }
  5400. /* Read frame payload from the first message in the queue into
  5401. * data and advance the queue by moving the memory in place. */
  5402. assert(body_len >= header_len);
  5403. if (data_len + header_len > body_len) {
  5404. mop = buf[0]; /* current mask and opcode */
  5405. /* Overflow case */
  5406. len = body_len - header_len;
  5407. memcpy(data, buf + header_len, len);
  5408. error = 0;
  5409. while (len < data_len) {
  5410. int n = pull(NULL, conn, data + len, (int)(data_len - len));
  5411. if (n <= 0) {
  5412. error = 1;
  5413. break;
  5414. }
  5415. len += n;
  5416. }
  5417. if (error) {
  5418. mg_cry(conn, "Websocket pull failed; closing connection");
  5419. break;
  5420. }
  5421. conn->data_len = conn->request_len;
  5422. } else {
  5423. mop = buf[0]; /* current mask and opcode, overwritten by
  5424. memmove() */
  5425. /* Length of the message being read at the front of the
  5426. * queue */
  5427. len = data_len + header_len;
  5428. /* Copy the data payload into the data pointer for the
  5429. * callback */
  5430. memcpy(data, buf + header_len, data_len);
  5431. /* Move the queue forward len bytes */
  5432. memmove(buf, buf + len, body_len - len);
  5433. /* Mark the queue as advanced */
  5434. conn->data_len -= (int)len;
  5435. }
  5436. /* Apply mask if necessary */
  5437. if (mask_len > 0) {
  5438. for (i = 0; i < data_len; ++i) {
  5439. data[i] ^= mask[i & 3];
  5440. }
  5441. }
  5442. /* Exit the loop if callback signals to exit (server side),
  5443. * or "connection close" opcode received (client side). */
  5444. exit_by_callback = 0;
  5445. if ((ws_data_handler != NULL) &&
  5446. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  5447. exit_by_callback = 1;
  5448. }
  5449. if (data != mem) {
  5450. mg_free(data);
  5451. }
  5452. if (exit_by_callback ||
  5453. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  5454. /* Opcode == 8, connection close */
  5455. break;
  5456. }
  5457. /* Not breaking the loop, process next websocket frame. */
  5458. } else {
  5459. /* Read from the socket into the next available location in the
  5460. * message queue. */
  5461. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  5462. conn->buf_size - conn->data_len)) <= 0) {
  5463. /* Error, no bytes read */
  5464. break;
  5465. }
  5466. conn->data_len += n;
  5467. }
  5468. }
  5469. mg_set_thread_name("worker");
  5470. }
  5471. int mg_websocket_write(struct mg_connection *conn, int opcode, const char *data,
  5472. size_t dataLen) {
  5473. unsigned char header[10];
  5474. size_t headerLen = 1;
  5475. int retval = -1;
  5476. header[0] = 0x80 + (opcode & 0xF);
  5477. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  5478. if (dataLen < 126) {
  5479. /* inline 7-bit length field */
  5480. header[1] = (unsigned char)dataLen;
  5481. headerLen = 2;
  5482. } else if (dataLen <= 0xFFFF) {
  5483. /* 16-bit length field */
  5484. header[1] = 126;
  5485. *(uint16_t *)(header + 2) = htons((uint16_t)dataLen);
  5486. headerLen = 4;
  5487. } else {
  5488. /* 64-bit length field */
  5489. header[1] = 127;
  5490. *(uint32_t *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  5491. *(uint32_t *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  5492. headerLen = 10;
  5493. }
  5494. /* Note that POSIX/Winsock's send() is threadsafe
  5495. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  5496. * but mongoose's mg_printf/mg_write is not (because of the loop in
  5497. * push(), although that is only a problem if the packet is large or
  5498. * outgoing buffer is full). */
  5499. (void)mg_lock_connection(conn);
  5500. retval = mg_write(conn, header, headerLen);
  5501. retval = mg_write(conn, data, dataLen);
  5502. mg_unlock_connection(conn);
  5503. return retval;
  5504. }
  5505. static void handle_websocket_request(
  5506. struct mg_connection *conn, const char *path, int is_callback_resource,
  5507. mg_websocket_connect_handler ws_connect_handler,
  5508. mg_websocket_ready_handler ws_ready_handler,
  5509. mg_websocket_data_handler ws_data_handler,
  5510. mg_websocket_close_handler ws_close_handler, void *cbData) {
  5511. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  5512. int lua_websock = 0;
  5513. #if !defined(USE_LUA)
  5514. (void)path;
  5515. #endif
  5516. /* Step 1: Check websocket protocol version. */
  5517. if (version == NULL || strcmp(version, "13") != 0) {
  5518. /* Reject wrong versions */
  5519. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  5520. return;
  5521. }
  5522. /* Step 2: If a callback is responsible, call it. */
  5523. if (is_callback_resource) {
  5524. if (ws_connect_handler != NULL &&
  5525. ws_connect_handler(conn, cbData) != 0) {
  5526. /* C callback has returned non-zero, do not proceed with handshake.
  5527. */
  5528. /* Note that C callbacks are no longer called when Lua is
  5529. * responsible, so C can no longer filter callbacks for Lua. */
  5530. return;
  5531. }
  5532. }
  5533. #if defined(USE_LUA)
  5534. /* Step 3: No callback. Check if Lua is responsible. */
  5535. else {
  5536. /* Step 3.1: Check if Lua is responsible. */
  5537. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  5538. lua_websock = match_prefix(
  5539. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  5540. (int)strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]), path);
  5541. }
  5542. if (lua_websock) {
  5543. /* Step 3.2: Lua is responsible: call it. */
  5544. conn->lua_websocket_state = lua_websocket_new(path, conn);
  5545. if (!conn->lua_websocket_state) {
  5546. /* Lua rejected the new client */
  5547. return;
  5548. }
  5549. }
  5550. }
  5551. #endif
  5552. /* Step 4: Check if there is a responsible websocket handler. */
  5553. if (!is_callback_resource && !lua_websock) {
  5554. /* There is no callback, an Lua is not responsible either. */
  5555. /* Reply with a 404 Not Found or with nothing at all? TODO: check if
  5556. * this is correct for websockets */
  5557. send_http_error(conn, 404, "%s", "Not found");
  5558. return;
  5559. }
  5560. /* Step 5: The websocket connection has been accepted */
  5561. send_websocket_handshake(conn);
  5562. /* Step 6: Call the ready handler */
  5563. if (is_callback_resource) {
  5564. if (ws_ready_handler != NULL) {
  5565. ws_ready_handler(conn, cbData);
  5566. }
  5567. #if defined(USE_LUA)
  5568. } else if (lua_websock) {
  5569. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  5570. /* the ready handler returned false */
  5571. return;
  5572. }
  5573. #endif
  5574. }
  5575. /* Step 7: Enter the read loop */
  5576. if (is_callback_resource) {
  5577. read_websocket(conn, ws_data_handler, cbData);
  5578. #if defined(USE_LUA)
  5579. } else if (lua_websock) {
  5580. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  5581. #endif
  5582. }
  5583. /* Step 8: Call the close handler */
  5584. if (ws_close_handler) {
  5585. ws_close_handler(conn, cbData);
  5586. }
  5587. }
  5588. static int is_websocket_protocol(const struct mg_connection *conn) {
  5589. const char *host, *upgrade, *connection, *version, *key;
  5590. upgrade = mg_get_header(conn, "Upgrade");
  5591. if (upgrade == NULL)
  5592. return 0; /* fail early, don't waste time checking other header fields
  5593. */
  5594. if (!mg_strcasestr(upgrade, "websocket"))
  5595. return 0;
  5596. connection = mg_get_header(conn, "Connection");
  5597. if (connection == NULL)
  5598. return 0;
  5599. if (!mg_strcasestr(connection, "upgrade"))
  5600. return 0;
  5601. host = mg_get_header(conn, "Host");
  5602. key = mg_get_header(conn, "Sec-WebSocket-Key");
  5603. version = mg_get_header(conn, "Sec-WebSocket-Version");
  5604. return host != NULL && key != NULL && version != NULL;
  5605. }
  5606. #endif /* !USE_WEBSOCKET */
  5607. static int isbyte(int n) { return n >= 0 && n <= 255; }
  5608. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  5609. int n, a, b, c, d, slash = 32, len = 0;
  5610. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  5611. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  5612. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  5613. slash < 33) {
  5614. len = n;
  5615. *net =
  5616. ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  5617. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  5618. }
  5619. return len;
  5620. }
  5621. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
  5622. int throttle = 0;
  5623. struct vec vec, val;
  5624. uint32_t net, mask;
  5625. char mult;
  5626. double v;
  5627. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  5628. mult = ',';
  5629. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  5630. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  5631. mult != ',')) {
  5632. continue;
  5633. }
  5634. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  5635. : 1;
  5636. if (vec.len == 1 && vec.ptr[0] == '*') {
  5637. throttle = (int)v;
  5638. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  5639. if ((remote_ip & mask) == net) {
  5640. throttle = (int)v;
  5641. }
  5642. } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
  5643. throttle = (int)v;
  5644. }
  5645. }
  5646. return throttle;
  5647. }
  5648. static uint32_t get_remote_ip(const struct mg_connection *conn) {
  5649. if (!conn)
  5650. return 0;
  5651. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  5652. }
  5653. int mg_upload(struct mg_connection *conn, const char *destination_dir) {
  5654. /* TODO: set a timeout */
  5655. const char *content_type_header, *boundary_start, *sc;
  5656. char *s;
  5657. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX], fname[1024],
  5658. boundary[100];
  5659. FILE *fp;
  5660. int bl, n, i, headers_len, boundary_len, eof, len = 0,
  5661. num_uploaded_files = 0;
  5662. struct mg_request_info part_request_info;
  5663. /* Request looks like this:
  5664. *
  5665. * POST /upload HTTP/1.1
  5666. * Host: 127.0.0.1:8080
  5667. * Content-Length: 244894
  5668. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  5669. *
  5670. * ------WebKitFormBoundaryRVr
  5671. * Content-Disposition: form-data; name="file"; filename="accum.png"
  5672. * Content-Type: image/png
  5673. *
  5674. * <89>PNG
  5675. * <PNG DATA>
  5676. * ------WebKitFormBoundaryRVr */
  5677. /* Extract boundary string from the Content-Type header */
  5678. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  5679. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  5680. NULL ||
  5681. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  5682. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  5683. boundary[0] == '\0') {
  5684. return num_uploaded_files;
  5685. }
  5686. boundary[99] = 0;
  5687. boundary_len = (int)strlen(boundary);
  5688. bl = boundary_len + 4; /* \r\n--<boundary> */
  5689. for (;;) {
  5690. /* Pull in headers */
  5691. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  5692. if (len < 0 || len > (int)sizeof(buf))
  5693. break;
  5694. while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
  5695. len += n;
  5696. /* assert(len <= (int) sizeof(buf)); */
  5697. if (len > (int)sizeof(buf))
  5698. break;
  5699. }
  5700. if ((headers_len = get_request_len(buf, len)) <= 0) {
  5701. break;
  5702. }
  5703. /* terminate header */
  5704. buf[headers_len - 1] = 0;
  5705. /* Scan for the boundary string and skip it */
  5706. if (buf[0] == '-' && buf[1] == '-' &&
  5707. !memcmp(buf + 2, boundary, boundary_len)) {
  5708. s = &buf[bl];
  5709. } else {
  5710. s = &buf[2];
  5711. }
  5712. /* Get headers for this part of the multipart message */
  5713. memset(&part_request_info, 0, sizeof(part_request_info));
  5714. parse_http_headers(&s, &part_request_info);
  5715. /* assert(&buf[headers_len-1] == s); */
  5716. if (&buf[headers_len - 1] != s)
  5717. break;
  5718. /* Fetch file name. */
  5719. sc = get_header(&part_request_info, "Content-Disposition");
  5720. if (!sc) {
  5721. /* invalid part of a multipart message */
  5722. break;
  5723. }
  5724. sc = strstr(sc, "filename");
  5725. if (!sc) {
  5726. /* no filename set */
  5727. break;
  5728. }
  5729. sc += 8; /* skip "filename" */
  5730. fname[0] = '\0';
  5731. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  5732. fname[1023] = 0;
  5733. /* Give up if the headers are not what we expect */
  5734. if (fname[0] == '\0') {
  5735. break;
  5736. }
  5737. /* Construct destination file name. Do not allow paths to have
  5738. * slashes. */
  5739. if ((s = strrchr(fname, '/')) == NULL &&
  5740. (s = strrchr(fname, '\\')) == NULL) {
  5741. s = fname;
  5742. } else {
  5743. s++;
  5744. }
  5745. /* There data is written to a temporary file first. */
  5746. /* Different users should use a different destination_dir. */
  5747. snprintf(path, sizeof(path) - 1, "%s/%s", destination_dir, s);
  5748. strcpy(tmp_path, path);
  5749. strcat(tmp_path, "~");
  5750. /* We open the file with exclusive lock held. This guarantee us
  5751. * there is no other thread can save into the same file
  5752. * simultaneously. */
  5753. fp = NULL;
  5754. /* Open file in binary mode. */
  5755. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  5756. break;
  5757. }
  5758. /* Move data to the beginning of the buffer */
  5759. /* part_request_info is no longer valid after this operation */
  5760. /* assert(len >= headers_len); */
  5761. if (len < headers_len)
  5762. break;
  5763. memmove(buf, &buf[headers_len], len - headers_len);
  5764. len -= headers_len;
  5765. /* Read POST data, write into file until boundary is found. */
  5766. eof = n = 0;
  5767. do {
  5768. len += n;
  5769. for (i = 0; i < len - bl; i++) {
  5770. if (!memcmp(&buf[i], "\r\n--", 4) &&
  5771. !memcmp(&buf[i + 4], boundary, boundary_len)) {
  5772. /* Found boundary, that's the end of file data. */
  5773. fwrite(buf, 1, i, fp);
  5774. eof = 1;
  5775. memmove(buf, &buf[i + bl], len - (i + bl));
  5776. len -= i + bl;
  5777. break;
  5778. }
  5779. }
  5780. if (!eof && len > bl) {
  5781. fwrite(buf, 1, len - bl, fp);
  5782. memmove(buf, &buf[len - bl], bl);
  5783. len = bl;
  5784. }
  5785. } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
  5786. fclose(fp);
  5787. if (eof) {
  5788. remove(path);
  5789. rename(tmp_path, path);
  5790. num_uploaded_files++;
  5791. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  5792. conn->ctx->callbacks.upload(conn, path);
  5793. }
  5794. } else {
  5795. remove(tmp_path);
  5796. }
  5797. }
  5798. return num_uploaded_files;
  5799. }
  5800. static int get_first_ssl_listener_index(const struct mg_context *ctx) {
  5801. int i, idx = -1;
  5802. if (ctx)
  5803. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  5804. idx = ctx->listening_sockets[i].is_ssl ? i : -1;
  5805. }
  5806. return idx;
  5807. }
  5808. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {
  5809. char host[1025];
  5810. const char *host_header;
  5811. size_t hostlen;
  5812. host_header = mg_get_header(conn, "Host");
  5813. hostlen = sizeof(host);
  5814. if (host_header != NULL) {
  5815. char *pos;
  5816. mg_strlcpy(host, host_header, hostlen);
  5817. host[hostlen - 1] = '\0';
  5818. pos = strchr(host, ':');
  5819. if (pos != NULL) {
  5820. *pos = '\0';
  5821. }
  5822. } else {
  5823. /* Cannot get host from the Host: header.
  5824. * Fallback to our IP address. */
  5825. if (conn)
  5826. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  5827. }
  5828. /* Send host, port, uri and (if it exists) ?query_string */
  5829. if (conn)
  5830. mg_printf(
  5831. conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  5832. host, (int)ntohs(
  5833. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  5834. conn->request_info.uri,
  5835. (conn->request_info.query_string == NULL) ? "" : "?",
  5836. (conn->request_info.query_string == NULL)
  5837. ? ""
  5838. : conn->request_info.query_string);
  5839. }
  5840. static void mg_set_request_handler_type(
  5841. struct mg_context *ctx, const char *uri, int is_websocket_handler,
  5842. int is_delete_request, mg_request_handler handler,
  5843. mg_websocket_connect_handler connect_handler,
  5844. mg_websocket_ready_handler ready_handler,
  5845. mg_websocket_data_handler data_handler,
  5846. mg_websocket_close_handler close_handler, void *cbdata) {
  5847. struct mg_request_handler_info *tmp_rh, **lastref;
  5848. size_t urilen = strlen(uri);
  5849. if (is_websocket_handler) {
  5850. /*
  5851. assert(handler == NULL);
  5852. assert(is_delete_request || connect_handler!=NULL ||
  5853. ready_handler!=NULL
  5854. ||
  5855. data_handler!=NULL || close_handler!=NULL);
  5856. */
  5857. if (handler != NULL)
  5858. return;
  5859. if (!is_delete_request && connect_handler == NULL &&
  5860. ready_handler == NULL && data_handler == NULL &&
  5861. close_handler == NULL)
  5862. return;
  5863. } else {
  5864. /*
  5865. assert(connect_handler==NULL && ready_handler==NULL &&
  5866. data_handler==NULL &&
  5867. close_handler==NULL);
  5868. assert(is_delete_request || (handler!=NULL));
  5869. */
  5870. if (connect_handler != NULL || ready_handler != NULL ||
  5871. data_handler != NULL || close_handler != NULL)
  5872. return;
  5873. if (!is_delete_request && (handler == NULL))
  5874. return;
  5875. }
  5876. if (!ctx)
  5877. return;
  5878. mg_lock_context(ctx);
  5879. /* first try to find an existing handler */
  5880. lastref = &(ctx->request_handlers);
  5881. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  5882. tmp_rh = tmp_rh->next) {
  5883. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  5884. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  5885. if (!is_delete_request) {
  5886. /* update existing handler */
  5887. if (!is_websocket_handler) {
  5888. tmp_rh->handler = handler;
  5889. } else {
  5890. tmp_rh->connect_handler = connect_handler;
  5891. tmp_rh->ready_handler = ready_handler;
  5892. tmp_rh->data_handler = data_handler;
  5893. tmp_rh->close_handler = close_handler;
  5894. }
  5895. tmp_rh->cbdata = cbdata;
  5896. } else {
  5897. /* remove existing handler */
  5898. *lastref = tmp_rh->next;
  5899. mg_free(tmp_rh->uri);
  5900. mg_free(tmp_rh);
  5901. }
  5902. mg_unlock_context(ctx);
  5903. return;
  5904. }
  5905. }
  5906. lastref = &(tmp_rh->next);
  5907. }
  5908. if (is_delete_request) {
  5909. /* no handler to set, this was a remove request to a non-existing
  5910. * handler */
  5911. mg_unlock_context(ctx);
  5912. return;
  5913. }
  5914. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  5915. sizeof(struct mg_request_handler_info), 1);
  5916. if (tmp_rh == NULL) {
  5917. mg_unlock_context(ctx);
  5918. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  5919. return;
  5920. }
  5921. tmp_rh->uri = mg_strdup(uri);
  5922. if (!tmp_rh->uri) {
  5923. mg_unlock_context(ctx);
  5924. mg_free(tmp_rh);
  5925. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  5926. return;
  5927. }
  5928. tmp_rh->uri_len = urilen;
  5929. if (!is_websocket_handler) {
  5930. tmp_rh->handler = handler;
  5931. } else {
  5932. tmp_rh->connect_handler = connect_handler;
  5933. tmp_rh->ready_handler = ready_handler;
  5934. tmp_rh->data_handler = data_handler;
  5935. tmp_rh->close_handler = close_handler;
  5936. }
  5937. tmp_rh->cbdata = cbdata;
  5938. tmp_rh->is_websocket_handler = is_websocket_handler;
  5939. tmp_rh->next = NULL;
  5940. *lastref = tmp_rh;
  5941. mg_unlock_context(ctx);
  5942. }
  5943. void mg_set_request_handler(struct mg_context *ctx, const char *uri,
  5944. mg_request_handler handler, void *cbdata) {
  5945. mg_set_request_handler_type(ctx, uri, 0, handler == NULL, handler, NULL,
  5946. NULL, NULL, NULL, cbdata);
  5947. }
  5948. void mg_set_websocket_handler(struct mg_context *ctx, const char *uri,
  5949. mg_websocket_connect_handler connect_handler,
  5950. mg_websocket_ready_handler ready_handler,
  5951. mg_websocket_data_handler data_handler,
  5952. mg_websocket_close_handler close_handler,
  5953. void *cbdata) {
  5954. int is_delete_request = (connect_handler == NULL) &&
  5955. (ready_handler == NULL) && (data_handler == NULL) &&
  5956. (close_handler == NULL);
  5957. mg_set_request_handler_type(ctx, uri, 1, is_delete_request, NULL,
  5958. connect_handler, ready_handler, data_handler,
  5959. close_handler, cbdata);
  5960. }
  5961. static int get_request_handler(struct mg_connection *conn,
  5962. int is_websocket_request,
  5963. mg_request_handler *handler,
  5964. mg_websocket_connect_handler *connect_handler,
  5965. mg_websocket_ready_handler *ready_handler,
  5966. mg_websocket_data_handler *data_handler,
  5967. mg_websocket_close_handler *close_handler,
  5968. void **cbdata) {
  5969. const struct mg_request_info *request_info = mg_get_request_info(conn);
  5970. if (request_info) {
  5971. const char *uri = request_info->uri;
  5972. size_t urilen = strlen(uri);
  5973. struct mg_request_handler_info *tmp_rh;
  5974. if (!conn || !conn->ctx)
  5975. return 0;
  5976. mg_lock_context(conn->ctx);
  5977. /* first try for an exact match */
  5978. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  5979. tmp_rh = tmp_rh->next) {
  5980. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  5981. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  5982. if (is_websocket_request) {
  5983. *connect_handler = tmp_rh->connect_handler;
  5984. *ready_handler = tmp_rh->ready_handler;
  5985. *data_handler = tmp_rh->data_handler;
  5986. *close_handler = tmp_rh->close_handler;
  5987. } else {
  5988. *handler = tmp_rh->handler;
  5989. }
  5990. *cbdata = tmp_rh->cbdata;
  5991. mg_unlock_context(conn->ctx);
  5992. return 1;
  5993. }
  5994. }
  5995. }
  5996. /* next try for a partial match, we will accept uri/something */
  5997. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  5998. tmp_rh = tmp_rh->next) {
  5999. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6000. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  6001. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  6002. if (is_websocket_request) {
  6003. *connect_handler = tmp_rh->connect_handler;
  6004. *ready_handler = tmp_rh->ready_handler;
  6005. *data_handler = tmp_rh->data_handler;
  6006. *close_handler = tmp_rh->close_handler;
  6007. } else {
  6008. *handler = tmp_rh->handler;
  6009. }
  6010. *cbdata = tmp_rh->cbdata;
  6011. mg_unlock_context(conn->ctx);
  6012. return 1;
  6013. }
  6014. }
  6015. }
  6016. /* finally try for pattern match */
  6017. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6018. tmp_rh = tmp_rh->next) {
  6019. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6020. if (match_prefix(tmp_rh->uri, (int)tmp_rh->uri_len, uri) > 0) {
  6021. if (is_websocket_request) {
  6022. *connect_handler = tmp_rh->connect_handler;
  6023. *ready_handler = tmp_rh->ready_handler;
  6024. *data_handler = tmp_rh->data_handler;
  6025. *close_handler = tmp_rh->close_handler;
  6026. } else {
  6027. *handler = tmp_rh->handler;
  6028. }
  6029. *cbdata = tmp_rh->cbdata;
  6030. mg_unlock_context(conn->ctx);
  6031. return 1;
  6032. }
  6033. }
  6034. }
  6035. mg_unlock_context(conn->ctx);
  6036. }
  6037. return 0; /* none found */
  6038. }
  6039. #if defined(USE_WEBSOCKET)
  6040. static int
  6041. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  6042. void *cbdata) {
  6043. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6044. if (pcallbacks->websocket_connect) {
  6045. return pcallbacks->websocket_connect(conn);
  6046. }
  6047. /* No handler set - assume "OK" */
  6048. return 0;
  6049. }
  6050. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  6051. void *cbdata) {
  6052. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6053. if (pcallbacks->websocket_ready) {
  6054. pcallbacks->websocket_ready(conn);
  6055. }
  6056. }
  6057. static int deprecated_websocket_data_wrapper(struct mg_connection *conn,
  6058. int bits, char *data, size_t len,
  6059. void *cbdata) {
  6060. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6061. if (pcallbacks->websocket_data) {
  6062. return pcallbacks->websocket_data(conn, bits, data, len);
  6063. }
  6064. /* No handler set - assume "OK" */
  6065. return 1;
  6066. }
  6067. #endif
  6068. /* This is the heart of the Civetweb's logic.
  6069. * This function is called when the request is read, parsed and validated,
  6070. * and Civetweb must decide what action to take: serve a file, or
  6071. * a directory, or call embedded function, etcetera. */
  6072. static void handle_request(struct mg_connection *conn) {
  6073. if (conn) {
  6074. struct mg_request_info *ri = &conn->request_info;
  6075. char path[PATH_MAX];
  6076. int uri_len, ssl_index, is_script_resource, is_websocket_request,
  6077. is_put_or_delete_request, is_callback_resource;
  6078. int i;
  6079. struct file file = STRUCT_FILE_INITIALIZER;
  6080. time_t curtime = time(NULL);
  6081. mg_request_handler callback_handler = NULL;
  6082. mg_websocket_connect_handler ws_connect_handler = NULL;
  6083. mg_websocket_ready_handler ws_ready_handler = NULL;
  6084. mg_websocket_data_handler ws_data_handler = NULL;
  6085. mg_websocket_close_handler ws_close_handler = NULL;
  6086. void *callback_data = NULL;
  6087. #if !defined(NO_FILES)
  6088. char date[64];
  6089. #endif
  6090. path[0] = 0;
  6091. if (!ri)
  6092. return;
  6093. /* 1. get the request url */
  6094. /* 1.1. split into url and query string */
  6095. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  6096. *((char *)conn->request_info.query_string++) = '\0';
  6097. }
  6098. uri_len = (int)strlen(ri->uri);
  6099. /* 1.2. decode url (if config says so) */
  6100. if (should_decode_url(conn)) {
  6101. mg_url_decode(ri->uri, uri_len, (char *)ri->uri, uri_len + 1, 0);
  6102. }
  6103. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  6104. * possible */
  6105. remove_double_dots_and_double_slashes((char *)ri->uri);
  6106. /* step 1. completed, the url is known now */
  6107. DEBUG_TRACE("URL: %s", ri->uri);
  6108. /* 2. do a https redirect, if required */
  6109. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  6110. ssl_index = get_first_ssl_listener_index(conn->ctx);
  6111. if (ssl_index >= 0) {
  6112. redirect_to_https_port(conn, ssl_index);
  6113. } else {
  6114. /* A http to https forward port has been specified,
  6115. * but no https port to forward to. */
  6116. send_http_error(conn, 503, "%s",
  6117. "Error: SSL forward not configured properly");
  6118. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  6119. }
  6120. return;
  6121. }
  6122. /* 3. if this ip has limited speed, set it for this connection */
  6123. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  6124. get_remote_ip(conn), ri->uri);
  6125. /* 4. call a "handle everything" callback, if registered */
  6126. if (conn->ctx->callbacks.begin_request != NULL) {
  6127. /* Note that since V1.7 the "begin_request" function is called
  6128. * before an authorization check. If an authorization check is
  6129. * required, use a request_handler instead. */
  6130. i = conn->ctx->callbacks.begin_request(conn);
  6131. switch (i) {
  6132. case 1:
  6133. /* callback already processed the request */
  6134. return;
  6135. case 0:
  6136. /* civetweb should process the request */
  6137. break;
  6138. default:
  6139. /* unspecified - may change with the next version */
  6140. return;
  6141. }
  6142. }
  6143. /* request not yet handled by a handler or redirect, so the request
  6144. is processed here */
  6145. /* 5. interpret the url to find out how the request must be handled */
  6146. /* 5.1. first test, if the request targets the regular http(s)://
  6147. * protocol namespace or the websocket ws(s):// protocol namespace. */
  6148. is_websocket_request = is_websocket_protocol(conn);
  6149. /* 5.2. check if the request will be handled by a callback */
  6150. if (get_request_handler(conn, is_websocket_request, &callback_handler,
  6151. &ws_connect_handler, &ws_ready_handler,
  6152. &ws_data_handler, &ws_close_handler,
  6153. &callback_data)) {
  6154. /* 5.2.1. A callback will handle this request. All requests handled
  6155. * by a callback have to be considered as requests to a script
  6156. * resource. */
  6157. is_callback_resource = 1;
  6158. is_script_resource = 1;
  6159. is_put_or_delete_request = is_put_or_delete_method(conn);
  6160. } else {
  6161. no_callback_resource:
  6162. /* 5.2.2. No callback is responsible for this request. The URI
  6163. * addresses a file based resource (static content or Lua/cgi
  6164. * scripts in the file system). */
  6165. is_callback_resource = 0;
  6166. interpret_uri(conn, path, sizeof(path), &file, &is_script_resource,
  6167. &is_websocket_request, &is_put_or_delete_request);
  6168. }
  6169. /* 6. authorization check */
  6170. if (is_put_or_delete_request && !is_script_resource &&
  6171. !is_callback_resource) {
  6172. /* 6.1. this request is a PUT/DELETE to a real file */
  6173. /* 6.1.1. thus, the server must have real files */
  6174. #if defined(NO_FILES)
  6175. if (1) {
  6176. #else
  6177. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  6178. #endif
  6179. /* This server does not have any real files, thus the
  6180. * PUT/DELETE methods are not valid. */
  6181. send_http_error(conn, 405, "%s method not allowed",
  6182. conn->request_info.request_method);
  6183. return;
  6184. }
  6185. /* 6.1.2. Check if put authorization for static files is available.
  6186. */
  6187. if (!is_authorized_for_put(conn)) {
  6188. send_authorization_request(conn);
  6189. return;
  6190. }
  6191. } else {
  6192. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  6193. * or it is a PUT or DELETE request to a resource that does not
  6194. * correspond to a file. Check authorization. */
  6195. if (!check_authorization(conn, path)) {
  6196. send_authorization_request(conn);
  6197. return;
  6198. }
  6199. }
  6200. /* request is authorized or does not need authorization */
  6201. /* 7. check if there are request handlers for this uri */
  6202. if (is_callback_resource) {
  6203. if (!is_websocket_request) {
  6204. if (callback_handler(conn, callback_data)) {
  6205. /* Do nothing, callback has served the request */
  6206. discard_unread_request_data(conn);
  6207. } else {
  6208. /* TODO: what if the handler did NOT handle the request */
  6209. /* The last version did handle this as a file request, but
  6210. * since a file request is not always a script resource,
  6211. * the authorization check might be different */
  6212. interpret_uri(conn, path, sizeof(path), &file,
  6213. &is_script_resource, &is_websocket_request,
  6214. &is_put_or_delete_request);
  6215. callback_handler = NULL;
  6216. /* TODO: for the moment, a goto is simpler than some
  6217. * curious loop. */
  6218. /* The situation "callback does not handle the request"
  6219. * needs to be reconsidered anyway. */
  6220. goto no_callback_resource;
  6221. }
  6222. } else {
  6223. #if defined(USE_WEBSOCKET)
  6224. handle_websocket_request(conn, path, is_callback_resource,
  6225. ws_connect_handler, ws_ready_handler,
  6226. ws_data_handler, ws_close_handler,
  6227. callback_data);
  6228. #endif
  6229. }
  6230. return;
  6231. }
  6232. /* 8. handle websocket requests */
  6233. #if defined(USE_WEBSOCKET)
  6234. if (is_websocket_request) {
  6235. handle_websocket_request(
  6236. conn, path,
  6237. !is_script_resource /* could be deprecated global callback */,
  6238. deprecated_websocket_connect_wrapper,
  6239. deprecated_websocket_ready_wrapper,
  6240. deprecated_websocket_data_wrapper, NULL, &conn->ctx->callbacks);
  6241. return;
  6242. } else
  6243. #endif
  6244. #if defined(NO_FILES)
  6245. /* 9a. In case the server uses only callbacks, this uri is unknown.
  6246. * Then, all request handling ends here. */
  6247. send_http_error(conn, 404, "%s", "Not Found");
  6248. #else
  6249. /* 9b. This request is either for a static file or resource handled
  6250. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  6251. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  6252. send_http_error(conn, 404, "%s", "Not Found");
  6253. return;
  6254. }
  6255. /* 10. File is handled by a script. */
  6256. if (is_script_resource) {
  6257. handle_file_based_request(conn, path, &file);
  6258. return;
  6259. }
  6260. /* 11. Handle put/delete/mkcol requests */
  6261. if (is_put_or_delete_request) {
  6262. /* 11.1. PUT method */
  6263. if (!strcmp(ri->request_method, "PUT")) {
  6264. put_file(conn, path);
  6265. return;
  6266. }
  6267. /* 11.2. DELETE method */
  6268. if (!strcmp(ri->request_method, "DELETE")) {
  6269. delete_file(conn, path);
  6270. return;
  6271. }
  6272. /* 11.3. MKCOL method */
  6273. if (!strcmp(ri->request_method, "MKCOL")) {
  6274. mkcol(conn, path);
  6275. return;
  6276. }
  6277. /* 11.4. should never reach this point */
  6278. send_http_error(conn, 405, "%s method not allowed",
  6279. conn->request_info.request_method);
  6280. return;
  6281. }
  6282. /* 11. File does not exist, or it was configured that it should be
  6283. * hidden */
  6284. if (((file.membuf == NULL) && (file.modification_time == (time_t)0)) ||
  6285. (must_hide_file(conn, path))) {
  6286. send_http_error(conn, 404, "%s", "Not found");
  6287. return;
  6288. }
  6289. /* 12. Directories uris should end with a slash */
  6290. if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  6291. gmt_time_string(date, sizeof(date), &curtime);
  6292. mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  6293. "Location: %s/\r\n"
  6294. "Date: %s\r\n"
  6295. "Content-Length: 0\r\n"
  6296. "Connection: %s\r\n\r\n",
  6297. ri->uri, date, suggest_connection_header(conn));
  6298. return;
  6299. }
  6300. /* 13. Handle other methods than GET/HEAD */
  6301. /* 13.1. Handle PROPFIND */
  6302. if (!strcmp(ri->request_method, "PROPFIND")) {
  6303. handle_propfind(conn, path, &file);
  6304. return;
  6305. }
  6306. /* 13.2. Handle OPTIONS for files */
  6307. if (!strcmp(ri->request_method, "OPTIONS")) {
  6308. /* This standard handler is only used for real files.
  6309. * Scripts should support the OPTIONS method themselves, to allow a
  6310. * maximum flexibility.
  6311. * Lua and CGI scripts may fully support CORS this way (including
  6312. * preflights). */
  6313. send_options(conn);
  6314. return;
  6315. }
  6316. /* 13.3. everything but GET and HEAD (e.g. POST) */
  6317. if (0 != strcmp(ri->request_method, "GET") &&
  6318. 0 != strcmp(ri->request_method, "HEAD")) {
  6319. send_http_error(conn, 405, "%s method not allowed",
  6320. conn->request_info.request_method);
  6321. return;
  6322. }
  6323. /* 14. directories */
  6324. if (file.is_directory) {
  6325. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  6326. /* 14.1. use a substitute file */
  6327. /* TODO: substitute index may be a script resource.
  6328. * define what should be possible in this case. */
  6329. } else {
  6330. /* 14.2. no substitute file */
  6331. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6332. "yes")) {
  6333. handle_directory_request(conn, path);
  6334. } else {
  6335. send_http_error(conn, 403, "%s",
  6336. "Error: Directory listing denied");
  6337. }
  6338. return;
  6339. }
  6340. }
  6341. handle_file_based_request(conn, path, &file);
  6342. #endif /* !defined(NO_FILES) */
  6343. #if 0
  6344. /* Perform redirect and auth checks before calling begin_request()
  6345. * handler.
  6346. * Otherwise, begin_request() would need to perform auth checks and
  6347. * redirects. */
  6348. #endif
  6349. }
  6350. return;
  6351. }
  6352. static void handle_file_based_request(struct mg_connection *conn,
  6353. const char *path, struct file *file) {
  6354. if (!conn || !conn->ctx)
  6355. return;
  6356. if (0) {
  6357. #ifdef USE_LUA
  6358. } else if (match_prefix(
  6359. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  6360. (int)strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  6361. path) > 0) {
  6362. /* Lua server page: an SSI like page containing mostly plain html code
  6363. * plus some tags with server generated contents. */
  6364. handle_lsp_request(conn, path, file, NULL);
  6365. } else if (match_prefix(
  6366. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  6367. (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6368. path) > 0) {
  6369. /* Lua in-server module script: a CGI like script used to generate the
  6370. * entire reply. */
  6371. mg_exec_lua_script(conn, path, NULL);
  6372. #endif
  6373. #if !defined(NO_CGI)
  6374. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  6375. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  6376. path) > 0) {
  6377. /* CGI scripts may support all HTTP methods */
  6378. handle_cgi_request(conn, path);
  6379. #endif /* !NO_CGI */
  6380. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6381. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6382. path) > 0) {
  6383. handle_ssi_file_request(conn, path, file);
  6384. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  6385. /* Send 304 "Not Modified" - this must not send any body data */
  6386. send_http_error(conn, 304, "%s", "");
  6387. } else {
  6388. handle_static_file_request(conn, path, file);
  6389. }
  6390. }
  6391. static void close_all_listening_sockets(struct mg_context *ctx) {
  6392. int i;
  6393. if (!ctx)
  6394. return;
  6395. for (i = 0; i < ctx->num_listening_sockets; i++) {
  6396. closesocket(ctx->listening_sockets[i].sock);
  6397. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  6398. }
  6399. mg_free(ctx->listening_sockets);
  6400. ctx->listening_sockets = NULL;
  6401. mg_free(ctx->listening_ports);
  6402. ctx->listening_ports = NULL;
  6403. }
  6404. static int is_valid_port(unsigned int port) { return port < 0xffff; }
  6405. int mg_inet_pton(int af, const char *src, void *dst) {
  6406. struct addrinfo hints, *res, *ressave;
  6407. memset(&hints, 0, sizeof(struct addrinfo));
  6408. hints.ai_family = af;
  6409. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  6410. /* bad src string or bad address family */
  6411. return 0;
  6412. }
  6413. ressave = res;
  6414. while (res) {
  6415. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6416. res = res->ai_next;
  6417. }
  6418. freeaddrinfo(ressave);
  6419. return (ressave != NULL);
  6420. }
  6421. /* Valid listening port specification is: [ip_address:]port[s]
  6422. * Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  6423. * TODO(lsm): add parsing of the IPv6 address */
  6424. static int parse_port_string(const struct vec *vec, struct socket *so) {
  6425. unsigned int a, b, c, d, port;
  6426. int ch, len;
  6427. #if defined(USE_IPV6)
  6428. char buf[100] = {0};
  6429. #endif
  6430. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  6431. * Also, all-zeroes in the socket address means binding to all addresses
  6432. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  6433. memset(so, 0, sizeof(*so));
  6434. so->lsa.sin.sin_family = AF_INET;
  6435. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  6436. 5) {
  6437. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  6438. so->lsa.sin.sin_addr.s_addr =
  6439. htonl((a << 24) | (b << 16) | (c << 8) | d);
  6440. so->lsa.sin.sin_port = htons((uint16_t)port);
  6441. #if defined(USE_IPV6)
  6442. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  6443. mg_inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
  6444. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  6445. so->lsa.sin6.sin6_family = AF_INET6;
  6446. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  6447. #endif
  6448. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  6449. /* If only port is specified, bind to IPv4, INADDR_ANY */
  6450. /* TODO: check -- so->lsa.sin6.sin6_family = AF_INET6; */
  6451. /* TODO: check -- so->lsa.sin6.sin6_port = htons((uint16_t) port); */
  6452. so->lsa.sin.sin_port = htons((uint16_t)port);
  6453. } else {
  6454. port = len = 0; /* Parsing failure. Make port invalid. */
  6455. }
  6456. /*assert((len>=0) && ((unsigned)len<=(unsigned)vec->len));*/ /* sscanf and
  6457. the
  6458. option
  6459. splitting
  6460. code
  6461. ensure this
  6462. condition
  6463. */
  6464. if ((len < 0) && ((unsigned)len > (unsigned)vec->len))
  6465. return 0;
  6466. ch = vec->ptr[len]; /* Next character after the port number */
  6467. so->is_ssl = (ch == 's');
  6468. so->ssl_redir = (ch == 'r');
  6469. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  6470. return is_valid_port(port) &&
  6471. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  6472. }
  6473. static int set_ports_option(struct mg_context *ctx) {
  6474. if (ctx) {
  6475. const char *list = ctx->config[LISTENING_PORTS];
  6476. int on = 1, success = 1;
  6477. #if defined(USE_IPV6)
  6478. int off = 0;
  6479. #endif
  6480. struct vec vec;
  6481. struct socket so, *ptr;
  6482. in_port_t *portPtr;
  6483. union usa usa;
  6484. socklen_t len;
  6485. memset(&so, 0, sizeof(so));
  6486. memset(&usa, 0, sizeof(usa));
  6487. len = sizeof(usa);
  6488. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  6489. if (!parse_port_string(&vec, &so)) {
  6490. mg_cry(fc(ctx),
  6491. "%s: %.*s: invalid port spec. Expecting list of: %s",
  6492. __func__, (int)vec.len, vec.ptr,
  6493. "[IP_ADDRESS:]PORT[s|r]");
  6494. success = 0;
  6495. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  6496. mg_cry(
  6497. fc(ctx),
  6498. "Cannot add SSL socket, is -ssl_certificate option set?");
  6499. success = 0;
  6500. } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM,
  6501. 6)) == INVALID_SOCKET ||
  6502. #ifdef _WIN32
  6503. /* Windows SO_REUSEADDR lets many procs binds to a
  6504. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  6505. * if someone already has the socket -- DTL */
  6506. setsockopt(so.sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6507. (SOCK_OPT_TYPE)&on, sizeof(on)) != 0 ||
  6508. #else
  6509. setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
  6510. (SOCK_OPT_TYPE)&on, sizeof(on)) != 0 ||
  6511. #endif
  6512. #if defined(USE_IPV6)
  6513. (so.lsa.sa.sa_family == AF_INET6 &&
  6514. setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY,
  6515. (void *)&off, sizeof(off)) != 0) ||
  6516. #endif
  6517. bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET
  6518. ? sizeof(so.lsa.sin)
  6519. : sizeof(so.lsa.sa)) !=
  6520. 0 ||
  6521. listen(so.sock, SOMAXCONN) != 0 ||
  6522. getsockname(so.sock, &(usa.sa), &len) != 0) {
  6523. /* TODO: rewrite this IF above */
  6524. mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
  6525. (int)vec.len, vec.ptr, (int)ERRNO, strerror(errno));
  6526. if (so.sock != INVALID_SOCKET) {
  6527. closesocket(so.sock);
  6528. so.sock = INVALID_SOCKET;
  6529. }
  6530. success = 0;
  6531. } else if ((ptr = (struct socket *)mg_realloc(
  6532. ctx->listening_sockets,
  6533. (ctx->num_listening_sockets + 1) *
  6534. sizeof(ctx->listening_sockets[0]))) == NULL) {
  6535. closesocket(so.sock);
  6536. so.sock = INVALID_SOCKET;
  6537. success = 0;
  6538. } else if ((portPtr = (in_port_t *)mg_realloc(
  6539. ctx->listening_ports,
  6540. (ctx->num_listening_sockets + 1) *
  6541. sizeof(ctx->listening_ports[0]))) == NULL) {
  6542. closesocket(so.sock);
  6543. so.sock = INVALID_SOCKET;
  6544. mg_free(ptr);
  6545. success = 0;
  6546. } else {
  6547. set_close_on_exec(so.sock, fc(ctx));
  6548. ctx->listening_sockets = ptr;
  6549. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  6550. ctx->listening_ports = portPtr;
  6551. ctx->listening_ports[ctx->num_listening_sockets] =
  6552. ntohs(usa.sin.sin_port);
  6553. ctx->num_listening_sockets++;
  6554. }
  6555. }
  6556. if (!success) {
  6557. close_all_listening_sockets(ctx);
  6558. }
  6559. return success;
  6560. }
  6561. return 0;
  6562. }
  6563. static const char *header_val(const struct mg_connection *conn,
  6564. const char *header) {
  6565. const char *header_value;
  6566. if ((header_value = mg_get_header(conn, header)) == NULL) {
  6567. return "-";
  6568. } else {
  6569. return header_value;
  6570. }
  6571. }
  6572. static void log_access(const struct mg_connection *conn) {
  6573. const struct mg_request_info *ri;
  6574. FILE *fp;
  6575. char date[64], src_addr[IP_ADDR_STR_LEN];
  6576. struct tm *tm;
  6577. const char *referer;
  6578. const char *user_agent;
  6579. char buf[4096];
  6580. if (!conn || !conn->ctx)
  6581. return;
  6582. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  6583. ? NULL
  6584. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  6585. if (fp == NULL && conn->ctx->callbacks.log_message == NULL)
  6586. return;
  6587. tm = localtime(&conn->conn_birth_time);
  6588. if (tm != NULL) {
  6589. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  6590. } else {
  6591. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  6592. date[sizeof(date) - 1] = '\0';
  6593. }
  6594. ri = &conn->request_info;
  6595. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6596. referer = header_val(conn, "Referer");
  6597. user_agent = header_val(conn, "User-Agent");
  6598. snprintf(buf, sizeof(buf),
  6599. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s", src_addr,
  6600. ri->remote_user == NULL ? "-" : ri->remote_user, date,
  6601. ri->request_method ? ri->request_method : "-",
  6602. ri->uri ? ri->uri : "-", ri->http_version, conn->status_code,
  6603. conn->num_bytes_sent, referer, user_agent);
  6604. if (conn->ctx->callbacks.log_access) {
  6605. conn->ctx->callbacks.log_access(conn, buf);
  6606. }
  6607. if (fp) {
  6608. flockfile(fp);
  6609. fprintf(fp, "%s", buf);
  6610. fputc('\n', fp);
  6611. fflush(fp);
  6612. funlockfile(fp);
  6613. fclose(fp);
  6614. }
  6615. }
  6616. /* Verify given socket address against the ACL.
  6617. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  6618. static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
  6619. int allowed, flag;
  6620. uint32_t net, mask;
  6621. struct vec vec;
  6622. if (ctx) {
  6623. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  6624. /* If any ACL is set, deny by default */
  6625. allowed = list == NULL ? '+' : '-';
  6626. while ((list = next_option(list, &vec, NULL)) != NULL) {
  6627. flag = vec.ptr[0];
  6628. if ((flag != '+' && flag != '-') ||
  6629. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  6630. mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]",
  6631. __func__);
  6632. return -1;
  6633. }
  6634. if (net == (remote_ip & mask)) {
  6635. allowed = flag;
  6636. }
  6637. }
  6638. return allowed == '+';
  6639. }
  6640. return -1;
  6641. }
  6642. #if !defined(_WIN32)
  6643. static int set_uid_option(struct mg_context *ctx) {
  6644. struct passwd *pw;
  6645. if (ctx) {
  6646. const char *uid = ctx->config[RUN_AS_USER];
  6647. int success = 0;
  6648. if (uid == NULL) {
  6649. success = 1;
  6650. } else {
  6651. if ((pw = getpwnam(uid)) == NULL) {
  6652. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  6653. } else if (setgid(pw->pw_gid) == -1) {
  6654. mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid,
  6655. strerror(errno));
  6656. } else if (setgroups(0, NULL)) {
  6657. mg_cry(fc(ctx), "%s: setgroups(): %s", __func__,
  6658. strerror(errno));
  6659. } else if (setuid(pw->pw_uid) == -1) {
  6660. mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid,
  6661. strerror(errno));
  6662. } else {
  6663. success = 1;
  6664. }
  6665. }
  6666. return success;
  6667. }
  6668. return 0;
  6669. }
  6670. #endif /* !_WIN32 */
  6671. #if !defined(NO_SSL)
  6672. static pthread_mutex_t *ssl_mutexes;
  6673. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
  6674. if (!conn)
  6675. return 0;
  6676. return (conn->ssl = SSL_new(s)) != NULL &&
  6677. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  6678. func(conn->ssl) == 1;
  6679. }
  6680. /* Return OpenSSL error message (from CRYPTO lib) */
  6681. static const char *ssl_error(void) {
  6682. unsigned long err;
  6683. err = ERR_get_error();
  6684. return err == 0 ? "" : ERR_error_string(err, NULL);
  6685. }
  6686. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  6687. int line) {
  6688. (void)line;
  6689. (void)file;
  6690. if (mode & 1) { /* 1 is CRYPTO_LOCK */
  6691. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  6692. } else {
  6693. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  6694. }
  6695. }
  6696. static unsigned long ssl_id_callback(void) {
  6697. return (unsigned long)pthread_self();
  6698. }
  6699. #if !defined(NO_SSL_DL)
  6700. static void *load_dll(struct mg_context *ctx, const char *dll_name,
  6701. struct ssl_func *sw) {
  6702. union {
  6703. void *p;
  6704. void (*fp)(void);
  6705. } u;
  6706. void *dll_handle;
  6707. struct ssl_func *fp;
  6708. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  6709. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  6710. return NULL;
  6711. }
  6712. for (fp = sw; fp->name != NULL; fp++) {
  6713. #ifdef _WIN32
  6714. /* GetProcAddress() returns pointer to function */
  6715. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  6716. #else
  6717. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  6718. * pointers to function pointers. We need to use a union to make a
  6719. * cast. */
  6720. u.p = dlsym(dll_handle, fp->name);
  6721. #endif /* _WIN32 */
  6722. if (u.fp == NULL) {
  6723. mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name,
  6724. fp->name);
  6725. dlclose(dll_handle);
  6726. return NULL;
  6727. } else {
  6728. fp->ptr = u.fp;
  6729. }
  6730. }
  6731. return dll_handle;
  6732. }
  6733. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  6734. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  6735. #endif /* NO_SSL_DL */
  6736. #if defined(SSL_ALREADY_INITIALIZED)
  6737. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  6738. #else
  6739. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  6740. #endif
  6741. static int initialize_ssl(struct mg_context *ctx) {
  6742. int i, size;
  6743. #if !defined(NO_SSL_DL)
  6744. if (!cryptolib_dll_handle) {
  6745. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  6746. if (!cryptolib_dll_handle) {
  6747. return 0;
  6748. }
  6749. }
  6750. #endif /* NO_SSL_DL */
  6751. if (mg_atomic_inc(&cryptolib_users) > 1)
  6752. return 1;
  6753. /* Initialize locking callbacks, needed for thread safety.
  6754. http://www.openssl.org/support/faq.html#PROG1 */
  6755. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  6756. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc((size_t)size)) == NULL) {
  6757. mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__,
  6758. ssl_error());
  6759. return 0;
  6760. }
  6761. for (i = 0; i < CRYPTO_num_locks(); i++) {
  6762. pthread_mutex_init(&ssl_mutexes[i], NULL);
  6763. }
  6764. CRYPTO_set_locking_callback(&ssl_locking_callback);
  6765. CRYPTO_set_id_callback(&ssl_id_callback);
  6766. return 1;
  6767. }
  6768. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  6769. static int set_ssl_option(struct mg_context *ctx) {
  6770. const char *pem;
  6771. int callback_ret;
  6772. /* If PEM file is not specified and the init_ssl callback
  6773. * is not specified, skip SSL initialization. */
  6774. if (!ctx)
  6775. return 0;
  6776. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  6777. ctx->callbacks.init_ssl == NULL) {
  6778. return 1;
  6779. }
  6780. if (!initialize_ssl(ctx)) {
  6781. return 0;
  6782. }
  6783. #if !defined(NO_SSL_DL)
  6784. if (!ssllib_dll_handle) {
  6785. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  6786. if (!ssllib_dll_handle) {
  6787. return 0;
  6788. }
  6789. }
  6790. #endif /* NO_SSL_DL */
  6791. /* Initialize SSL library */
  6792. SSL_library_init();
  6793. SSL_load_error_strings();
  6794. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  6795. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  6796. return 0;
  6797. }
  6798. /* If a callback has been specified, call it. */
  6799. callback_ret =
  6800. (ctx->callbacks.init_ssl == NULL)
  6801. ? 0
  6802. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  6803. /* If callback returns 0, civetweb sets up the SSL certificate.
  6804. * If it returns 1, civetweb assumes the calback already did this.
  6805. * If it returns -1, initializing ssl fails. */
  6806. if (callback_ret < 0) {
  6807. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  6808. return 0;
  6809. }
  6810. if (callback_ret == 0) {
  6811. if (pem != NULL) {
  6812. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  6813. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  6814. mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem,
  6815. ssl_error());
  6816. return 0;
  6817. }
  6818. }
  6819. }
  6820. if (pem != NULL) {
  6821. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  6822. }
  6823. return 1;
  6824. }
  6825. static void uninitialize_ssl(struct mg_context *ctx) {
  6826. int i;
  6827. (void)ctx;
  6828. if (mg_atomic_dec(&cryptolib_users) == 0) {
  6829. CRYPTO_set_locking_callback(NULL);
  6830. for (i = 0; i < CRYPTO_num_locks(); i++) {
  6831. pthread_mutex_destroy(&ssl_mutexes[i]);
  6832. }
  6833. CRYPTO_set_locking_callback(NULL);
  6834. CRYPTO_set_id_callback(NULL);
  6835. }
  6836. }
  6837. #endif /* !NO_SSL */
  6838. static int set_gpass_option(struct mg_context *ctx) {
  6839. if (ctx) {
  6840. struct file file = STRUCT_FILE_INITIALIZER;
  6841. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  6842. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  6843. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  6844. return 0;
  6845. }
  6846. return 1;
  6847. }
  6848. return 0;
  6849. }
  6850. static int set_acl_option(struct mg_context *ctx) {
  6851. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  6852. }
  6853. static void reset_per_request_attributes(struct mg_connection *conn) {
  6854. if (!conn)
  6855. return;
  6856. conn->path_info = NULL;
  6857. conn->num_bytes_sent = conn->consumed_content = 0;
  6858. conn->status_code = -1;
  6859. conn->is_chunked = 0;
  6860. conn->must_close = conn->request_len = conn->throttle = 0;
  6861. conn->request_info.content_length = -1;
  6862. conn->request_info.remote_user = NULL;
  6863. conn->request_info.request_method = NULL;
  6864. conn->request_info.uri = NULL;
  6865. conn->request_info.http_version = NULL;
  6866. conn->request_info.num_headers = 0;
  6867. conn->data_len = 0;
  6868. conn->chunk_remainder = 0;
  6869. }
  6870. static int set_sock_timeout(SOCKET sock, int milliseconds) {
  6871. int r1, r2;
  6872. #ifdef _WIN32
  6873. DWORD t = milliseconds;
  6874. #else
  6875. #if defined(TCP_USER_TIMEOUT)
  6876. unsigned int uto = (unsigned int)milliseconds;
  6877. #endif
  6878. struct timeval t;
  6879. t.tv_sec = milliseconds / 1000;
  6880. t.tv_usec = (milliseconds * 1000) % 1000000;
  6881. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  6882. * max. time waiting for the acknowledged of TCP data before the connection
  6883. * will be forcefully closed and ETIMEDOUT is returned to the application.
  6884. * If this option is not set, the default timeout of 20-30 minutes is used.
  6885. */
  6886. /* #define TCP_USER_TIMEOUT (18) */
  6887. #if defined(TCP_USER_TIMEOUT)
  6888. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  6889. #endif
  6890. #endif
  6891. r1 =
  6892. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  6893. r2 =
  6894. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  6895. return r1 || r2;
  6896. }
  6897. static void close_socket_gracefully(struct mg_connection *conn) {
  6898. #if defined(_WIN32)
  6899. char buf[MG_BUF_LEN];
  6900. int n;
  6901. #endif
  6902. struct linger linger;
  6903. /* Set linger option to avoid socket hanging out after close. This prevent
  6904. * ephemeral port exhaust problem under high QPS. */
  6905. linger.l_onoff = 1;
  6906. linger.l_linger = 1;
  6907. if (!conn)
  6908. return;
  6909. if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER, (char *)&linger,
  6910. sizeof(linger)) != 0) {
  6911. mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  6912. __func__, strerror(ERRNO));
  6913. }
  6914. /* Send FIN to the client */
  6915. shutdown(conn->client.sock, SHUT_WR);
  6916. set_non_blocking_mode(conn->client.sock);
  6917. #if defined(_WIN32)
  6918. /* Read and discard pending incoming data. If we do not do that and close
  6919. * the socket, the data in the send buffer may be discarded. This
  6920. * behaviour is seen on Windows, when client keeps sending data
  6921. * when server decides to close the connection; then when client
  6922. * does recv() it gets no data back. */
  6923. do {
  6924. n = pull(NULL, conn, buf, sizeof(buf));
  6925. } while (n > 0);
  6926. #endif
  6927. /* Now we know that our FIN is ACK-ed, safe to close */
  6928. closesocket(conn->client.sock);
  6929. conn->client.sock = INVALID_SOCKET;
  6930. }
  6931. static void close_connection(struct mg_connection *conn) {
  6932. if (!conn || !conn->ctx)
  6933. return;
  6934. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  6935. if (conn->lua_websocket_state) {
  6936. lua_websocket_close(conn, conn->lua_websocket_state);
  6937. conn->lua_websocket_state = NULL;
  6938. }
  6939. #endif
  6940. /* call the connection_close callback if assigned */
  6941. if ((conn->ctx->callbacks.connection_close != NULL) &&
  6942. (conn->ctx->context_type == 1)) {
  6943. conn->ctx->callbacks.connection_close(conn);
  6944. }
  6945. mg_lock_connection(conn);
  6946. conn->must_close = 1;
  6947. #ifndef NO_SSL
  6948. if (conn->ssl != NULL) {
  6949. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  6950. SSL_shutdown(conn->ssl);
  6951. SSL_free(conn->ssl);
  6952. conn->ssl = NULL;
  6953. }
  6954. #endif
  6955. if (conn->client.sock != INVALID_SOCKET) {
  6956. close_socket_gracefully(conn);
  6957. conn->client.sock = INVALID_SOCKET;
  6958. }
  6959. mg_unlock_connection(conn);
  6960. }
  6961. void mg_close_connection(struct mg_connection *conn) {
  6962. struct mg_context *client_ctx = NULL;
  6963. int i;
  6964. if (conn == NULL)
  6965. return;
  6966. if (conn->ctx->context_type == 2) {
  6967. client_ctx = conn->ctx;
  6968. /* client context: loops must end */
  6969. conn->ctx->stop_flag = 1;
  6970. }
  6971. #ifndef NO_SSL
  6972. if (conn->client_ssl_ctx != NULL) {
  6973. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  6974. }
  6975. #endif
  6976. close_connection(conn);
  6977. if (client_ctx != NULL) {
  6978. /* join worker thread and free context */
  6979. for (i = 0; i < client_ctx->workerthreadcount; i++) {
  6980. mg_join_thread(client_ctx->workerthreadids[i]);
  6981. }
  6982. mg_free(client_ctx->workerthreadids);
  6983. mg_free(client_ctx);
  6984. }
  6985. (void)pthread_mutex_destroy(&conn->mutex);
  6986. mg_free(conn);
  6987. }
  6988. struct mg_connection *mg_connect_client(const char *host, int port, int use_ssl,
  6989. char *ebuf, size_t ebuf_len) {
  6990. static struct mg_context fake_ctx;
  6991. struct mg_connection *conn = NULL;
  6992. SOCKET sock;
  6993. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf, ebuf_len)) ==
  6994. INVALID_SOCKET) {
  6995. } else if ((conn = (struct mg_connection *)mg_calloc(
  6996. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  6997. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  6998. closesocket(sock);
  6999. #ifndef NO_SSL
  7000. } else if (use_ssl &&
  7001. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  7002. NULL) {
  7003. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  7004. closesocket(sock);
  7005. mg_free(conn);
  7006. conn = NULL;
  7007. #endif /* NO_SSL */
  7008. } else {
  7009. socklen_t len = sizeof(struct sockaddr);
  7010. conn->buf_size = MAX_REQUEST_SIZE;
  7011. conn->buf = (char *)(conn + 1);
  7012. conn->ctx = &fake_ctx;
  7013. conn->client.sock = sock;
  7014. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  7015. mg_cry(conn, "%s: getsockname() failed: %s", __func__,
  7016. strerror(ERRNO));
  7017. }
  7018. conn->client.is_ssl = use_ssl;
  7019. (void)pthread_mutex_init(&conn->mutex, NULL);
  7020. #ifndef NO_SSL
  7021. if (use_ssl) {
  7022. /* SSL_CTX_set_verify call is needed to switch off server
  7023. * certificate checking, which is off by default in OpenSSL and on
  7024. * in yaSSL. */
  7025. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  7026. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  7027. }
  7028. #endif
  7029. }
  7030. return conn;
  7031. }
  7032. static int is_valid_uri(const char *uri) {
  7033. /* Conform to
  7034. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  7035. * URI can be an asterisk (*) or should start with slash. */
  7036. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  7037. }
  7038. static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len,
  7039. int *err) {
  7040. const char *cl;
  7041. if (ebuf_len > 0) {
  7042. ebuf[0] = '\0';
  7043. }
  7044. *err = 0;
  7045. reset_per_request_attributes(conn);
  7046. if (!conn) {
  7047. snprintf(ebuf, ebuf_len, "%s", "Internal error");
  7048. *err = 500;
  7049. return 0;
  7050. }
  7051. /* Set the time the request was received. This value should be used for
  7052. * timeouts. */
  7053. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  7054. conn->request_len =
  7055. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  7056. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  7057. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  7058. snprintf(ebuf, ebuf_len, "%s", "Invalid request size");
  7059. *err = 500;
  7060. return 0;
  7061. }
  7062. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  7063. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  7064. *err = 413;
  7065. return 0;
  7066. } else if (conn->request_len <= 0) {
  7067. if (conn->data_len > 0) {
  7068. snprintf(ebuf, ebuf_len, "%s", "Client sent malformed request");
  7069. *err = 400;
  7070. } else {
  7071. /* Server did not send anything -> just close the connection */
  7072. conn->must_close = 1;
  7073. snprintf(ebuf, ebuf_len, "%s", "Client did not send a request");
  7074. *err = 0;
  7075. }
  7076. return 0;
  7077. } else if (parse_http_message(conn->buf, conn->buf_size,
  7078. &conn->request_info) <= 0) {
  7079. snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len,
  7080. conn->buf);
  7081. *err = 400;
  7082. return 0;
  7083. } else {
  7084. /* Message is a valid request or response */
  7085. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  7086. /* Request/response has content length set */
  7087. char *endptr = "";
  7088. conn->content_len = strtoll(cl, &endptr, 10);
  7089. if (endptr == cl) {
  7090. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  7091. *err = 411;
  7092. return 0;
  7093. }
  7094. /* Publish the content length back to the request info. */
  7095. conn->request_info.content_length = conn->content_len;
  7096. } else if ((cl = get_header(&conn->request_info,
  7097. "Transfer-encoding")) != NULL &&
  7098. strcmp(cl, "chunked") == 0) {
  7099. conn->is_chunked = 1;
  7100. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  7101. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  7102. /* POST or PUT request without content length set */
  7103. conn->content_len = -1;
  7104. } else if (!mg_strncasecmp(conn->request_info.request_method, "HTTP/",
  7105. 5)) {
  7106. /* Response without content length set */
  7107. conn->content_len = -1;
  7108. } else {
  7109. /* Other request */
  7110. conn->content_len = 0;
  7111. }
  7112. }
  7113. return 1;
  7114. }
  7115. int mg_get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len,
  7116. int timeout) {
  7117. if (conn) {
  7118. /* Implementation of API function for HTTP clients */
  7119. int err, ret;
  7120. struct mg_context *octx = conn->ctx;
  7121. struct mg_context rctx = *(conn->ctx);
  7122. char txt[32];
  7123. if (timeout >= 0) {
  7124. snprintf(txt, sizeof(txt), "%i", timeout);
  7125. rctx.config[REQUEST_TIMEOUT] = txt;
  7126. set_sock_timeout(conn->client.sock, timeout);
  7127. } else {
  7128. rctx.config[REQUEST_TIMEOUT] = NULL;
  7129. }
  7130. conn->ctx = &rctx;
  7131. ret = getreq(conn, ebuf, ebuf_len, &err);
  7132. conn->ctx = octx;
  7133. /* TODO: Define proper return values - maybe return length?
  7134. * For the first test use <0 for error and >0 for OK */
  7135. return (ret == 0) ? -1 : +1;
  7136. }
  7137. return -1;
  7138. }
  7139. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  7140. char *ebuf, size_t ebuf_len, const char *fmt,
  7141. ...) {
  7142. struct mg_connection *conn;
  7143. va_list ap;
  7144. int i;
  7145. int reqerr;
  7146. va_start(ap, fmt);
  7147. ebuf[0] = '\0';
  7148. /* open a connection */
  7149. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  7150. if (conn != NULL) {
  7151. i = mg_vprintf(conn, fmt, ap);
  7152. if (i <= 0) {
  7153. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  7154. } else {
  7155. getreq(conn, ebuf, ebuf_len, &reqerr);
  7156. }
  7157. }
  7158. /* if an error occured, close the connection */
  7159. if (ebuf[0] != '\0' && conn != NULL) {
  7160. mg_close_connection(conn);
  7161. conn = NULL;
  7162. }
  7163. va_end(ap);
  7164. return conn;
  7165. }
  7166. struct websocket_client_thread_data {
  7167. struct mg_connection *conn;
  7168. mg_websocket_data_handler data_handler;
  7169. mg_websocket_close_handler close_handler;
  7170. void *callback_data;
  7171. };
  7172. #if defined(USE_WEBSOCKET)
  7173. #ifdef _WIN32
  7174. static unsigned __stdcall websocket_client_thread(void *data)
  7175. #else
  7176. static void *websocket_client_thread(void *data)
  7177. #endif
  7178. {
  7179. struct websocket_client_thread_data *cdata =
  7180. (struct websocket_client_thread_data *)data;
  7181. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  7182. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  7183. if (cdata->close_handler != NULL) {
  7184. cdata->close_handler(cdata->conn, cdata->callback_data);
  7185. }
  7186. mg_free((void *)cdata);
  7187. #ifdef _WIN32
  7188. return 0;
  7189. #else
  7190. return NULL;
  7191. #endif
  7192. }
  7193. #endif
  7194. struct mg_connection *mg_connect_websocket_client(
  7195. const char *host, int port, int use_ssl, char *error_buffer,
  7196. size_t error_buffer_size, const char *path, const char *origin,
  7197. mg_websocket_data_handler data_func, mg_websocket_close_handler close_func,
  7198. void *user_data) {
  7199. struct mg_connection *conn = NULL;
  7200. #if defined(USE_WEBSOCKET)
  7201. struct mg_context *newctx = NULL;
  7202. struct websocket_client_thread_data *thread_data;
  7203. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  7204. static const char *handshake_req;
  7205. if (origin != NULL) {
  7206. handshake_req = "GET %s HTTP/1.1\r\n"
  7207. "Host: %s\r\n"
  7208. "Upgrade: websocket\r\n"
  7209. "Connection: Upgrade\r\n"
  7210. "Sec-WebSocket-Key: %s\r\n"
  7211. "Sec-WebSocket-Version: 13\r\n"
  7212. "Origin: %s\r\n"
  7213. "\r\n";
  7214. } else {
  7215. handshake_req = "GET %s HTTP/1.1\r\n"
  7216. "Host: %s\r\n"
  7217. "Upgrade: websocket\r\n"
  7218. "Connection: Upgrade\r\n"
  7219. "Sec-WebSocket-Key: %s\r\n"
  7220. "Sec-WebSocket-Version: 13\r\n"
  7221. "\r\n";
  7222. }
  7223. /* Establish the client connection and request upgrade */
  7224. conn = mg_download(host, port, use_ssl, error_buffer, error_buffer_size,
  7225. handshake_req, path, host, magic, origin);
  7226. /* Connection object will be null if something goes wrong */
  7227. if (conn == NULL || (strcmp(conn->request_info.uri, "101") != 0)) {
  7228. if (!*error_buffer) {
  7229. /* if there is a connection, but it did not return 101,
  7230. * error_buffer is not yet set */
  7231. mg_snprintf(conn, error_buffer, error_buffer_size,
  7232. "Unexpected server reply");
  7233. }
  7234. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  7235. if (conn != NULL) {
  7236. mg_free(conn);
  7237. conn = NULL;
  7238. }
  7239. return conn;
  7240. }
  7241. /* For client connections, mg_context is fake. Since we need to set a
  7242. * callback function, we need to create a copy and modify it. */
  7243. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  7244. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  7245. newctx->user_data = user_data;
  7246. newctx->context_type = 2; /* client context type */
  7247. newctx->workerthreadcount = 1; /* one worker thread will be created */
  7248. newctx->workerthreadids =
  7249. (pthread_t *)mg_calloc(newctx->workerthreadcount, sizeof(pthread_t));
  7250. conn->ctx = newctx;
  7251. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  7252. sizeof(struct websocket_client_thread_data), 1);
  7253. thread_data->conn = conn;
  7254. thread_data->data_handler = data_func;
  7255. thread_data->close_handler = close_func;
  7256. thread_data->callback_data = NULL;
  7257. /* Start a thread to read the websocket client connection
  7258. * This thread will automatically stop when mg_disconnect is
  7259. * called on the client connection */
  7260. if (mg_start_thread_with_id(websocket_client_thread, (void *)thread_data,
  7261. newctx->workerthreadids) != 0) {
  7262. mg_free((void *)thread_data);
  7263. mg_free((void *)newctx->workerthreadids);
  7264. mg_free((void *)newctx);
  7265. mg_free((void *)conn);
  7266. conn = NULL;
  7267. DEBUG_TRACE("%s",
  7268. "Websocket client connect thread could not be started\r\n");
  7269. }
  7270. #else
  7271. /* Appease "unused parameter" warnings */
  7272. (void)host;
  7273. (void)port;
  7274. (void)use_ssl;
  7275. (void)error_buffer;
  7276. (void)error_buffer_size;
  7277. (void)path;
  7278. (void)origin;
  7279. (void)user_data;
  7280. (void)data_func;
  7281. (void)close_func;
  7282. #endif
  7283. return conn;
  7284. }
  7285. static void process_new_connection(struct mg_connection *conn) {
  7286. if (conn && conn->ctx) {
  7287. struct mg_request_info *ri = &conn->request_info;
  7288. int keep_alive_enabled, keep_alive, discard_len;
  7289. char ebuf[100];
  7290. int reqerr;
  7291. keep_alive_enabled =
  7292. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  7293. /* Important: on new connection, reset the receiving buffer. Credit
  7294. goes
  7295. to crule42. */
  7296. conn->data_len = 0;
  7297. do {
  7298. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  7299. /* The request sent by the client could not be understood by
  7300. * the server, or it was incomplete or a timeout. Send an
  7301. * error message and close the connection. */
  7302. if (reqerr > 0) {
  7303. /*assert(ebuf[0] != '\0');*/
  7304. send_http_error(conn, reqerr, "%s", ebuf);
  7305. }
  7306. } else if (!is_valid_uri(conn->request_info.uri)) {
  7307. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  7308. send_http_error(conn, 400, "%s", ebuf);
  7309. } else if (strcmp(ri->http_version, "1.0") &&
  7310. strcmp(ri->http_version, "1.1")) {
  7311. snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]",
  7312. ri->http_version);
  7313. send_http_error(conn, 505, "%s", ebuf);
  7314. }
  7315. if (ebuf[0] == '\0') {
  7316. handle_request(conn);
  7317. if (conn->ctx->callbacks.end_request != NULL) {
  7318. conn->ctx->callbacks.end_request(conn, conn->status_code);
  7319. }
  7320. log_access(conn);
  7321. } else {
  7322. conn->must_close = 1;
  7323. }
  7324. if (ri->remote_user != NULL) {
  7325. mg_free((void *)ri->remote_user);
  7326. /* Important! When having connections with and without auth
  7327. * would cause double free and then crash */
  7328. ri->remote_user = NULL;
  7329. }
  7330. /* NOTE(lsm): order is important here. should_keep_alive() call is
  7331. * using parsed request, which will be invalid after memmove's
  7332. * below.
  7333. * Therefore, memorize should_keep_alive() result now for later use
  7334. * in loop exit condition. */
  7335. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  7336. conn->content_len >= 0 && should_keep_alive(conn);
  7337. /* Discard all buffered data for this request */
  7338. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  7339. conn->request_len + conn->content_len <
  7340. (int64_t)conn->data_len
  7341. ? (int)(conn->request_len + conn->content_len)
  7342. : conn->data_len;
  7343. /*assert(discard_len >= 0);*/
  7344. if (discard_len < 0)
  7345. break;
  7346. memmove(conn->buf, conn->buf + discard_len,
  7347. conn->data_len - discard_len);
  7348. conn->data_len -= discard_len;
  7349. /*
  7350. assert(conn->data_len >= 0);
  7351. assert(conn->data_len <= conn->buf_size);
  7352. */
  7353. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size))
  7354. break;
  7355. } while (keep_alive);
  7356. }
  7357. }
  7358. /* Worker threads take accepted socket from the queue */
  7359. static int consume_socket(struct mg_context *ctx, struct socket *sp) {
  7360. if (!ctx)
  7361. return 0;
  7362. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7363. DEBUG_TRACE("%s", "going idle");
  7364. /* If the queue is empty, wait. We're idle at this point. */
  7365. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  7366. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  7367. }
  7368. /* If we're stopping, sq_head may be equal to sq_tail. */
  7369. if (ctx->sq_head > ctx->sq_tail) {
  7370. /* Copy socket from the queue and increment tail */
  7371. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  7372. ctx->sq_tail++;
  7373. if (sp)
  7374. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  7375. /* Wrap pointers if needed */
  7376. while (ctx->sq_tail > (int)ARRAY_SIZE(ctx->queue)) {
  7377. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  7378. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  7379. }
  7380. }
  7381. (void)pthread_cond_signal(&ctx->sq_empty);
  7382. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7383. return !ctx->stop_flag;
  7384. }
  7385. static void *worker_thread_run(void *thread_func_param) {
  7386. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  7387. struct mg_connection *conn;
  7388. struct mg_workerTLS tls;
  7389. mg_set_thread_name("worker");
  7390. tls.is_master = 0;
  7391. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7392. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  7393. #endif
  7394. conn =
  7395. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  7396. if (conn == NULL) {
  7397. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  7398. } else {
  7399. pthread_setspecific(sTlsKey, &tls);
  7400. conn->buf_size = MAX_REQUEST_SIZE;
  7401. conn->buf = (char *)(conn + 1);
  7402. conn->ctx = ctx;
  7403. conn->request_info.user_data = ctx->user_data;
  7404. /* Allocate a mutex for this connection to allow communication both
  7405. * within the request handler and from elsewhere in the application */
  7406. (void)pthread_mutex_init(&conn->mutex, NULL);
  7407. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  7408. signal sq_empty condvar to wake up the master waiting in
  7409. produce_socket() */
  7410. while (consume_socket(ctx, &conn->client)) {
  7411. conn->conn_birth_time = time(NULL);
  7412. /* Fill in IP, port info early so even if SSL setup below fails,
  7413. * error handler would have the corresponding info.
  7414. * Thanks to Johannes Winkelmann for the patch.
  7415. * TODO(lsm): Fix IPv6 case */
  7416. conn->request_info.remote_port =
  7417. ntohs(conn->client.rsa.sin.sin_port);
  7418. sockaddr_to_string(conn->request_info.remote_addr,
  7419. sizeof(conn->request_info.remote_addr),
  7420. &conn->client.rsa);
  7421. /* TODO: #if defined(MG_LEGACY_INTERFACE) */
  7422. memcpy(&conn->request_info.remote_ip,
  7423. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  7424. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  7425. /* #endif */
  7426. conn->request_info.is_ssl = conn->client.is_ssl;
  7427. if (!conn->client.is_ssl
  7428. #ifndef NO_SSL
  7429. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  7430. #endif
  7431. ) {
  7432. process_new_connection(conn);
  7433. }
  7434. close_connection(conn);
  7435. }
  7436. }
  7437. /* Signal master that we're done with connection and exiting */
  7438. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7439. ctx->num_threads--;
  7440. (void)pthread_cond_signal(&ctx->thread_cond);
  7441. /* assert(ctx->num_threads >= 0); */
  7442. if (ctx->num_threads < 0)
  7443. return NULL;
  7444. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7445. pthread_setspecific(sTlsKey, NULL);
  7446. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7447. CloseHandle(tls.pthread_cond_helper_mutex);
  7448. #endif
  7449. mg_free(conn);
  7450. DEBUG_TRACE("%s", "exiting");
  7451. return NULL;
  7452. }
  7453. /* Threads have different return types on Windows and Unix. */
  7454. #ifdef _WIN32
  7455. static unsigned __stdcall worker_thread(void *thread_func_param) {
  7456. worker_thread_run(thread_func_param);
  7457. return 0;
  7458. }
  7459. #else
  7460. static void *worker_thread(void *thread_func_param) {
  7461. worker_thread_run(thread_func_param);
  7462. return NULL;
  7463. }
  7464. #endif /* _WIN32 */
  7465. /* Master thread adds accepted socket to a queue */
  7466. static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
  7467. if (!ctx)
  7468. return;
  7469. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7470. /* If the queue is full, wait */
  7471. while (ctx->stop_flag == 0 &&
  7472. ctx->sq_head - ctx->sq_tail >= (int)ARRAY_SIZE(ctx->queue)) {
  7473. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  7474. }
  7475. if (ctx->sq_head - ctx->sq_tail < (int)ARRAY_SIZE(ctx->queue)) {
  7476. /* Copy socket to the queue and increment head */
  7477. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  7478. ctx->sq_head++;
  7479. if (sp)
  7480. DEBUG_TRACE("queued socket %d", sp->sock);
  7481. }
  7482. (void)pthread_cond_signal(&ctx->sq_full);
  7483. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7484. }
  7485. static void accept_new_connection(const struct socket *listener,
  7486. struct mg_context *ctx) {
  7487. struct socket so;
  7488. char src_addr[IP_ADDR_STR_LEN];
  7489. socklen_t len = sizeof(so.rsa);
  7490. int on = 1;
  7491. int timeout;
  7492. if (!listener)
  7493. return;
  7494. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  7495. INVALID_SOCKET) {
  7496. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  7497. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  7498. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  7499. closesocket(so.sock);
  7500. so.sock = INVALID_SOCKET;
  7501. } else {
  7502. /* Put so socket structure into the queue */
  7503. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  7504. set_close_on_exec(so.sock, fc(ctx));
  7505. so.is_ssl = listener->is_ssl;
  7506. so.ssl_redir = listener->ssl_redir;
  7507. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  7508. mg_cry(fc(ctx), "%s: getsockname() failed: %s", __func__,
  7509. strerror(ERRNO));
  7510. }
  7511. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  7512. * is enabled, and client resets the connection, server won't get
  7513. * TCP FIN or RST and will keep the connection open forever. With TCP
  7514. * keep-alive, next keep-alive handshake will figure out that the
  7515. * client is down and will close the server end.
  7516. * Thanks to Igor Klopov who suggested the patch. */
  7517. if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SOCK_OPT_TYPE)&on,
  7518. sizeof(on)) != 0) {
  7519. mg_cry(fc(ctx),
  7520. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  7521. __func__, strerror(ERRNO));
  7522. }
  7523. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  7524. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  7525. } else {
  7526. timeout = -1;
  7527. }
  7528. /* Set socket timeout to the given value, but not more than 10 seconds,
  7529. * so the server can exit after 10 seconds if required. */
  7530. /* TODO: Currently values > 10 s are round up to the next 10 s.
  7531. * For values like 24 s a socket timeout of 8 or 12 s would be better.
  7532. */
  7533. if ((timeout > 0) && (timeout < 10000)) {
  7534. set_sock_timeout(so.sock, timeout);
  7535. } else {
  7536. set_sock_timeout(so.sock, 10000);
  7537. }
  7538. produce_socket(ctx, &so);
  7539. }
  7540. }
  7541. static void master_thread_run(void *thread_func_param) {
  7542. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  7543. struct mg_workerTLS tls;
  7544. struct pollfd *pfd;
  7545. int i;
  7546. int workerthreadcount;
  7547. if (!ctx)
  7548. return;
  7549. mg_set_thread_name("master");
  7550. /* Increase priority of the master thread */
  7551. #if defined(_WIN32)
  7552. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  7553. #elif defined(USE_MASTER_THREAD_PRIORITY)
  7554. int min_prio = sched_get_priority_min(SCHED_RR);
  7555. int max_prio = sched_get_priority_max(SCHED_RR);
  7556. if ((min_prio >= 0) && (max_prio >= 0) &&
  7557. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  7558. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  7559. struct sched_param sched_param = {0};
  7560. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  7561. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  7562. }
  7563. #endif
  7564. /* Initialize thread local storage */
  7565. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7566. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  7567. #endif
  7568. tls.is_master = 1;
  7569. pthread_setspecific(sTlsKey, &tls);
  7570. /* Server starts *now* */
  7571. ctx->start_time = (unsigned long)time(NULL);
  7572. /* Allocate memory for the listening sockets, and start the server */
  7573. pfd =
  7574. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  7575. while (pfd != NULL && ctx->stop_flag == 0) {
  7576. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7577. pfd[i].fd = ctx->listening_sockets[i].sock;
  7578. pfd[i].events = POLLIN;
  7579. }
  7580. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  7581. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7582. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  7583. * successful poll, and POLLIN is defined as
  7584. * (POLLRDNORM | POLLRDBAND)
  7585. * Therefore, we're checking pfd[i].revents & POLLIN, not
  7586. * pfd[i].revents == POLLIN. */
  7587. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  7588. accept_new_connection(&ctx->listening_sockets[i], ctx);
  7589. }
  7590. }
  7591. }
  7592. }
  7593. mg_free(pfd);
  7594. DEBUG_TRACE("%s", "stopping workers");
  7595. /* Stop signal received: somebody called mg_stop. Quit. */
  7596. close_all_listening_sockets(ctx);
  7597. /* Wakeup workers that are waiting for connections to handle. */
  7598. pthread_cond_broadcast(&ctx->sq_full);
  7599. /* Wait until all threads finish */
  7600. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7601. while (ctx->num_threads > 0) {
  7602. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  7603. }
  7604. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7605. /* Join all worker threads to avoid leaking threads. */
  7606. workerthreadcount = ctx->workerthreadcount;
  7607. for (i = 0; i < workerthreadcount; i++) {
  7608. mg_join_thread(ctx->workerthreadids[i]);
  7609. }
  7610. #if !defined(NO_SSL)
  7611. if (ctx->ssl_ctx != NULL) {
  7612. uninitialize_ssl(ctx);
  7613. }
  7614. #endif
  7615. DEBUG_TRACE("%s", "exiting");
  7616. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7617. CloseHandle(tls.pthread_cond_helper_mutex);
  7618. #endif
  7619. pthread_setspecific(sTlsKey, NULL);
  7620. /* Signal mg_stop() that we're done.
  7621. * WARNING: This must be the very last thing this
  7622. * thread does, as ctx becomes invalid after this line. */
  7623. ctx->stop_flag = 2;
  7624. }
  7625. /* Threads have different return types on Windows and Unix. */
  7626. #ifdef _WIN32
  7627. static unsigned __stdcall master_thread(void *thread_func_param) {
  7628. master_thread_run(thread_func_param);
  7629. return 0;
  7630. }
  7631. #else
  7632. static void *master_thread(void *thread_func_param) {
  7633. master_thread_run(thread_func_param);
  7634. return NULL;
  7635. }
  7636. #endif /* _WIN32 */
  7637. static void free_context(struct mg_context *ctx) {
  7638. int i;
  7639. struct mg_request_handler_info *tmp_rh;
  7640. if (ctx == NULL)
  7641. return;
  7642. if (ctx->callbacks.exit_context) {
  7643. ctx->callbacks.exit_context(ctx);
  7644. }
  7645. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  7646. */
  7647. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  7648. (void)pthread_cond_destroy(&ctx->thread_cond);
  7649. (void)pthread_cond_destroy(&ctx->sq_empty);
  7650. (void)pthread_cond_destroy(&ctx->sq_full);
  7651. /* Destroy other context global data structures mutex */
  7652. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  7653. #if defined(USE_TIMERS)
  7654. timers_exit(ctx);
  7655. #endif
  7656. /* Deallocate config parameters */
  7657. for (i = 0; i < NUM_OPTIONS; i++) {
  7658. if (ctx->config[i] != NULL)
  7659. #if defined(_MSC_VER)
  7660. #pragma warning(suppress : 6001)
  7661. #endif
  7662. mg_free(ctx->config[i]);
  7663. }
  7664. /* Deallocate request handlers */
  7665. while (ctx->request_handlers) {
  7666. tmp_rh = ctx->request_handlers;
  7667. ctx->request_handlers = tmp_rh->next;
  7668. mg_free(tmp_rh->uri);
  7669. mg_free(tmp_rh);
  7670. }
  7671. #ifndef NO_SSL
  7672. /* Deallocate SSL context */
  7673. if (ctx->ssl_ctx != NULL) {
  7674. SSL_CTX_free(ctx->ssl_ctx);
  7675. }
  7676. if (ssl_mutexes != NULL) {
  7677. mg_free(ssl_mutexes);
  7678. ssl_mutexes = NULL;
  7679. }
  7680. #endif /* !NO_SSL */
  7681. /* Deallocate worker thread ID array */
  7682. if (ctx->workerthreadids != NULL) {
  7683. mg_free(ctx->workerthreadids);
  7684. }
  7685. /* Deallocate the tls variable */
  7686. if (mg_atomic_dec(&sTlsInit) == 0) {
  7687. pthread_key_delete(sTlsKey);
  7688. }
  7689. /* deallocate system name string */
  7690. mg_free(ctx->systemName);
  7691. /* Deallocate context itself */
  7692. mg_free(ctx);
  7693. }
  7694. void mg_stop(struct mg_context *ctx) {
  7695. if (!ctx)
  7696. return;
  7697. ctx->stop_flag = 1;
  7698. /* Wait until mg_fini() stops */
  7699. while (ctx->stop_flag != 2) {
  7700. (void)mg_sleep(10);
  7701. }
  7702. mg_join_thread(ctx->masterthreadid);
  7703. free_context(ctx);
  7704. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7705. (void)WSACleanup();
  7706. #endif /* _WIN32 && !__SYMBIAN32__ */
  7707. }
  7708. static void get_system_name(char **sysName) {
  7709. #if defined(_WIN32)
  7710. #if !defined(__SYMBIAN32__)
  7711. char name[128];
  7712. DWORD dwVersion = 0;
  7713. DWORD dwMajorVersion = 0;
  7714. DWORD dwMinorVersion = 0;
  7715. DWORD dwBuild = 0;
  7716. dwVersion = GetVersion();
  7717. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  7718. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  7719. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  7720. (void)dwBuild;
  7721. sprintf(name, "Windows %u.%u", (unsigned)dwMajorVersion,
  7722. (unsigned)dwMinorVersion);
  7723. *sysName = mg_strdup(name);
  7724. #else
  7725. *sysName = mg_strdup("Symbian");
  7726. #endif
  7727. #else
  7728. struct utsname name;
  7729. memset(&name, 0, sizeof(name));
  7730. uname(&name);
  7731. *sysName = mg_strdup(name.sysname);
  7732. #endif
  7733. }
  7734. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  7735. void *user_data, const char **options) {
  7736. struct mg_context *ctx;
  7737. const char *name, *value, *default_value;
  7738. int i, ok;
  7739. int workerthreadcount;
  7740. void (*exit_callback)(const struct mg_context *ctx) = 0;
  7741. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  7742. WSADATA data;
  7743. WSAStartup(MAKEWORD(2, 2), &data);
  7744. #if defined(_MSC_VER)
  7745. #pragma warning(suppress : 28125)
  7746. #endif
  7747. if (!sTlsInit)
  7748. InitializeCriticalSection(&global_log_file_lock);
  7749. #endif /* _WIN32 && !__SYMBIAN32__ */
  7750. /* Allocate context and initialize reasonable general case defaults.
  7751. * TODO(lsm): do proper error handling here. */
  7752. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  7753. return NULL;
  7754. }
  7755. if (mg_atomic_inc(&sTlsInit) == 1) {
  7756. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  7757. /* Fatal error - abort start. However, this situation should never
  7758. * occur in practice. */
  7759. mg_atomic_dec(&sTlsInit);
  7760. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  7761. mg_free(ctx);
  7762. return NULL;
  7763. }
  7764. } else {
  7765. /* TODO: check if sTlsKey is already initialized */
  7766. mg_sleep(1);
  7767. }
  7768. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  7769. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  7770. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  7771. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  7772. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  7773. if (!ok) {
  7774. /* Fatal error - abort start. However, this situation should never
  7775. * occur in practice. */
  7776. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  7777. mg_free(ctx);
  7778. return NULL;
  7779. }
  7780. if (callbacks) {
  7781. ctx->callbacks = *callbacks;
  7782. exit_callback = callbacks->exit_context;
  7783. ctx->callbacks.exit_context = 0;
  7784. }
  7785. ctx->user_data = user_data;
  7786. ctx->request_handlers = NULL;
  7787. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  7788. ctx->shared_lua_websockets = 0;
  7789. #endif
  7790. while (options && (name = *options++) != NULL) {
  7791. if ((i = get_option_index(name)) == -1) {
  7792. mg_cry(fc(ctx), "Invalid option: %s", name);
  7793. free_context(ctx);
  7794. return NULL;
  7795. } else if ((value = *options++) == NULL) {
  7796. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  7797. free_context(ctx);
  7798. return NULL;
  7799. }
  7800. if (ctx->config[i] != NULL) {
  7801. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  7802. mg_free(ctx->config[i]);
  7803. }
  7804. ctx->config[i] = mg_strdup(value);
  7805. DEBUG_TRACE("[%s] -> [%s]", name, value);
  7806. }
  7807. /* Set default value if needed */
  7808. for (i = 0; config_options[i].name != NULL; i++) {
  7809. default_value = config_options[i].default_value;
  7810. if (ctx->config[i] == NULL && default_value != NULL) {
  7811. ctx->config[i] = mg_strdup(default_value);
  7812. }
  7813. }
  7814. #if defined(NO_FILES)
  7815. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  7816. mg_cry(fc(ctx), "%s", "Document root must not be set");
  7817. free_context(ctx);
  7818. return NULL;
  7819. }
  7820. #endif
  7821. get_system_name(&ctx->systemName);
  7822. /* NOTE(lsm): order is important here. SSL certificates must
  7823. * be initialized before listening ports. UID must be set last. */
  7824. if (!set_gpass_option(ctx) ||
  7825. #if !defined(NO_SSL)
  7826. !set_ssl_option(ctx) ||
  7827. #endif
  7828. !set_ports_option(ctx) ||
  7829. #if !defined(_WIN32)
  7830. !set_uid_option(ctx) ||
  7831. #endif
  7832. !set_acl_option(ctx)) {
  7833. free_context(ctx);
  7834. return NULL;
  7835. }
  7836. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  7837. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  7838. * won't kill the whole process. */
  7839. (void)signal(SIGPIPE, SIG_IGN);
  7840. #endif /* !_WIN32 && !__SYMBIAN32__ */
  7841. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  7842. if (workerthreadcount > MAX_WORKER_THREADS) {
  7843. mg_cry(fc(ctx), "Too many worker threads");
  7844. free_context(ctx);
  7845. return NULL;
  7846. }
  7847. if (workerthreadcount > 0) {
  7848. ctx->workerthreadcount = workerthreadcount;
  7849. ctx->workerthreadids =
  7850. (pthread_t *)mg_calloc(workerthreadcount, sizeof(pthread_t));
  7851. if (ctx->workerthreadids == NULL) {
  7852. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  7853. free_context(ctx);
  7854. return NULL;
  7855. }
  7856. }
  7857. #if defined(USE_TIMERS)
  7858. if (timers_init(ctx) != 0) {
  7859. mg_cry(fc(ctx), "Error creating timers");
  7860. free_context(ctx);
  7861. return NULL;
  7862. }
  7863. #endif
  7864. /* Context has been created - init user libraries */
  7865. if (ctx->callbacks.init_context) {
  7866. ctx->callbacks.init_context(ctx);
  7867. }
  7868. ctx->callbacks.exit_context = exit_callback;
  7869. ctx->context_type = 1; /* server context */
  7870. /* Start master (listening) thread */
  7871. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  7872. /* Start worker threads */
  7873. for (i = 0; i < workerthreadcount; i++) {
  7874. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7875. ctx->num_threads++;
  7876. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7877. if (mg_start_thread_with_id(worker_thread, ctx,
  7878. &ctx->workerthreadids[i]) != 0) {
  7879. (void)pthread_mutex_lock(&ctx->thread_mutex);
  7880. ctx->num_threads--;
  7881. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  7882. if (i > 0) {
  7883. mg_cry(fc(ctx), "Cannot start worker thread %i: error %ld",
  7884. i + 1, (long)ERRNO);
  7885. } else {
  7886. mg_cry(fc(ctx), "Cannot create threads: error %ld",
  7887. (long)ERRNO);
  7888. free_context(ctx);
  7889. return NULL;
  7890. }
  7891. break;
  7892. }
  7893. }
  7894. return ctx;
  7895. }