civetweb.c 298 KB

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