civetweb.c 340 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  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. /* Include the header file here, so the CivetWeb interface is defined for the
  103. * entire implementation, including the following forward definitions. */
  104. #include "civetweb.h"
  105. #ifndef IGNORE_UNUSED_RESULT
  106. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  107. #endif
  108. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  109. #include <sys/types.h>
  110. #include <sys/stat.h>
  111. #include <errno.h>
  112. #include <signal.h>
  113. #include <fcntl.h>
  114. #endif /* !_WIN32_WCE */
  115. #ifdef __MACH__
  116. #define CLOCK_MONOTONIC (1)
  117. #define CLOCK_REALTIME (2)
  118. #include <sys/time.h>
  119. #include <mach/clock.h>
  120. #include <mach/mach.h>
  121. #include <mach/mach_time.h>
  122. #include <assert.h>
  123. /* clock_gettime is not implemented on OSX */
  124. int clock_gettime(int clk_id, struct timespec *t);
  125. int
  126. clock_gettime(int clk_id, struct timespec *t)
  127. {
  128. memset(t, 0, sizeof(*t));
  129. if (clk_id == CLOCK_REALTIME) {
  130. struct timeval now;
  131. int rv = gettimeofday(&now, NULL);
  132. if (rv) {
  133. return rv;
  134. }
  135. t->tv_sec = now.tv_sec;
  136. t->tv_nsec = now.tv_usec * 1000;
  137. return 0;
  138. } else if (clk_id == CLOCK_MONOTONIC) {
  139. static uint64_t clock_start_time = 0;
  140. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  141. uint64_t now = mach_absolute_time();
  142. if (clock_start_time == 0) {
  143. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  144. #if defined(DEBUG)
  145. assert(mach_status == KERN_SUCCESS);
  146. #else
  147. /* appease "unused variable" warning for release builds */
  148. (void)mach_status;
  149. #endif
  150. clock_start_time = now;
  151. }
  152. now = (uint64_t)((double)(now - clock_start_time)
  153. * (double)timebase_ifo.numer
  154. / (double)timebase_ifo.denom);
  155. t->tv_sec = now / 1000000000;
  156. t->tv_nsec = now % 1000000000;
  157. return 0;
  158. }
  159. return -1; /* EINVAL - Clock ID is unknown */
  160. }
  161. #endif
  162. #include <time.h>
  163. #include <stdlib.h>
  164. #include <stdarg.h>
  165. #include <assert.h>
  166. #include <string.h>
  167. #include <ctype.h>
  168. #include <limits.h>
  169. #include <stddef.h>
  170. #include <stdio.h>
  171. #ifndef MAX_WORKER_THREADS
  172. #define MAX_WORKER_THREADS (1024 * 64)
  173. #endif
  174. #ifndef SOCKET_TIMEOUT_QUANTUM
  175. #define SOCKET_TIMEOUT_QUANTUM (10000)
  176. #endif
  177. mg_static_assert(MAX_WORKER_THREADS >= 1,
  178. "worker threads must be a positive number");
  179. #if defined(_WIN32) \
  180. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  181. #include <windows.h>
  182. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  183. #include <ws2tcpip.h>
  184. typedef const char *SOCK_OPT_TYPE;
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (MAX_PATH)
  187. #endif
  188. #if !defined(PATH_MAX)
  189. #define PATH_MAX (4096)
  190. #endif
  191. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  192. #ifndef _IN_PORT_T
  193. #ifndef in_port_t
  194. #define in_port_t u_short
  195. #endif
  196. #endif
  197. #ifndef _WIN32_WCE
  198. #include <process.h>
  199. #include <direct.h>
  200. #include <io.h>
  201. #else /* _WIN32_WCE */
  202. #define NO_CGI /* WinCE has no pipes */
  203. typedef long off_t;
  204. #define errno ((int)(GetLastError()))
  205. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  206. #endif /* _WIN32_WCE */
  207. #define MAKEUQUAD(lo, hi) \
  208. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  209. #define RATE_DIFF (10000000) /* 100 nsecs */
  210. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  211. #define SYS2UNIX_TIME(lo, hi) \
  212. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  213. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  214. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  215. * Also use _strtoui64 on modern M$ compilers */
  216. #if defined(_MSC_VER)
  217. #if (_MSC_VER < 1300)
  218. #define STRX(x) #x
  219. #define STR(x) STRX(x)
  220. #define __func__ __FILE__ ":" STR(__LINE__)
  221. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  222. #define strtoll(x, y, z) (_atoi64(x))
  223. #else
  224. #define __func__ __FUNCTION__
  225. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  226. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  227. #endif
  228. #endif /* _MSC_VER */
  229. #define ERRNO ((int)(GetLastError()))
  230. #define NO_SOCKLEN_T
  231. #if defined(_WIN64) || defined(__MINGW64__)
  232. #define SSL_LIB "ssleay64.dll"
  233. #define CRYPTO_LIB "libeay64.dll"
  234. #else
  235. #define SSL_LIB "ssleay32.dll"
  236. #define CRYPTO_LIB "libeay32.dll"
  237. #endif
  238. #define O_NONBLOCK (0)
  239. #ifndef W_OK
  240. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  241. #endif
  242. #if !defined(EWOULDBLOCK)
  243. #define EWOULDBLOCK WSAEWOULDBLOCK
  244. #endif /* !EWOULDBLOCK */
  245. #define _POSIX_
  246. #define INT64_FMT "I64d"
  247. #define UINT64_FMT "I64u"
  248. #define WINCDECL __cdecl
  249. #define SHUT_RD (0)
  250. #define SHUT_WR (1)
  251. #define SHUT_BOTH (2)
  252. #define vsnprintf_impl _vsnprintf
  253. #define access _access
  254. #define mg_sleep(x) (Sleep(x))
  255. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  256. #ifndef popen
  257. #define popen(x, y) (_popen(x, y))
  258. #endif
  259. #ifndef pclose
  260. #define pclose(x) (_pclose(x))
  261. #endif
  262. #define close(x) (_close(x))
  263. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  264. #define RTLD_LAZY (0)
  265. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  266. #define fdopen(x, y) (_fdopen((x), (y)))
  267. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  268. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  269. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  270. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  271. #define sleep(x) (Sleep((x)*1000))
  272. #define rmdir(x) (_rmdir(x))
  273. #define timegm(x) (_mkgmtime(x))
  274. #if !defined(fileno)
  275. #define fileno(x) (_fileno(x))
  276. #endif /* !fileno MINGW #defines fileno */
  277. typedef HANDLE pthread_mutex_t;
  278. typedef DWORD pthread_key_t;
  279. typedef HANDLE pthread_t;
  280. typedef struct {
  281. CRITICAL_SECTION threadIdSec;
  282. int waitingthreadcount; /* The number of threads queued. */
  283. pthread_t *waitingthreadhdls; /* The thread handles. */
  284. } pthread_cond_t;
  285. #ifndef __clockid_t_defined
  286. typedef DWORD clockid_t;
  287. #endif
  288. #ifndef CLOCK_MONOTONIC
  289. #define CLOCK_MONOTONIC (1)
  290. #endif
  291. #ifndef CLOCK_REALTIME
  292. #define CLOCK_REALTIME (2)
  293. #endif
  294. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  295. #define _TIMESPEC_DEFINED
  296. #endif
  297. #ifndef _TIMESPEC_DEFINED
  298. struct timespec {
  299. time_t tv_sec; /* seconds */
  300. long tv_nsec; /* nanoseconds */
  301. };
  302. #endif
  303. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  304. static int pthread_mutex_lock(pthread_mutex_t *);
  305. static int pthread_mutex_unlock(pthread_mutex_t *);
  306. static void path_to_unicode(const struct mg_connection *conn,
  307. const char *path,
  308. wchar_t *wbuf,
  309. size_t wbuf_len);
  310. struct file;
  311. static const char *
  312. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  313. #if defined(HAVE_STDINT)
  314. #include <stdint.h>
  315. #else
  316. typedef unsigned char uint8_t;
  317. typedef unsigned short uint16_t;
  318. typedef unsigned int uint32_t;
  319. typedef unsigned __int64 uint64_t;
  320. typedef __int64 int64_t;
  321. #define INT64_MAX (9223372036854775807)
  322. #endif /* HAVE_STDINT */
  323. /* POSIX dirent interface */
  324. struct dirent {
  325. char d_name[PATH_MAX];
  326. };
  327. typedef struct DIR {
  328. HANDLE handle;
  329. WIN32_FIND_DATAW info;
  330. struct dirent result;
  331. } DIR;
  332. #if defined(_WIN32) && !defined(POLLIN)
  333. #ifndef HAVE_POLL
  334. struct pollfd {
  335. SOCKET fd;
  336. short events;
  337. short revents;
  338. };
  339. #define POLLIN (0x0300)
  340. #endif
  341. #endif
  342. /* Mark required libraries */
  343. #if defined(_MSC_VER)
  344. #pragma comment(lib, "Ws2_32.lib")
  345. #endif
  346. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  347. block */
  348. #include <sys/wait.h>
  349. #include <sys/socket.h>
  350. #include <sys/poll.h>
  351. #include <netinet/in.h>
  352. #include <arpa/inet.h>
  353. #include <sys/time.h>
  354. #include <sys/utsname.h>
  355. #include <stdint.h>
  356. #include <inttypes.h>
  357. #include <netdb.h>
  358. #include <netinet/tcp.h>
  359. typedef const void *SOCK_OPT_TYPE;
  360. #if defined(ANDROID)
  361. typedef unsigned short int in_port_t;
  362. #endif
  363. #include <pwd.h>
  364. #include <unistd.h>
  365. #include <grp.h>
  366. #include <dirent.h>
  367. #define vsnprintf_impl vsnprintf
  368. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  369. #include <dlfcn.h>
  370. #endif
  371. #include <pthread.h>
  372. #if defined(__MACH__)
  373. #define SSL_LIB "libssl.dylib"
  374. #define CRYPTO_LIB "libcrypto.dylib"
  375. #else
  376. #if !defined(SSL_LIB)
  377. #define SSL_LIB "libssl.so"
  378. #endif
  379. #if !defined(CRYPTO_LIB)
  380. #define CRYPTO_LIB "libcrypto.so"
  381. #endif
  382. #endif
  383. #ifndef O_BINARY
  384. #define O_BINARY (0)
  385. #endif /* O_BINARY */
  386. #define closesocket(a) (close(a))
  387. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  388. #define mg_remove(conn, x) (remove(x))
  389. #define mg_sleep(x) (usleep((x)*1000))
  390. #define mg_opendir(conn, x) (opendir(x))
  391. #define mg_closedir(x) (closedir(x))
  392. #define mg_readdir(x) (readdir(x))
  393. #define ERRNO (errno)
  394. #define INVALID_SOCKET (-1)
  395. #define INT64_FMT PRId64
  396. #define UINT64_FMT PRIu64
  397. typedef int SOCKET;
  398. #define WINCDECL
  399. #if defined(__hpux)
  400. /* HPUX 11 does not have monotonic, fall back to realtime */
  401. #ifndef CLOCK_MONOTONIC
  402. #define CLOCK_MONOTONIC CLOCK_REALTIME
  403. #endif
  404. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  405. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  406. * the prototypes use int* rather than socklen_t* which matches the
  407. * actual library expectation. When called with the wrong size arg
  408. * accept() returns a zero client inet addr and check_acl() always
  409. * fails. Since socklen_t is widely used below, just force replace
  410. * their typedef with int. - DTL
  411. */
  412. #define socklen_t int
  413. #endif /* hpux */
  414. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  415. block */
  416. /* va_copy should always be a macro, C99 and C++11 - DTL */
  417. #ifndef va_copy
  418. #define va_copy(x, y) ((x) = (y))
  419. #endif
  420. #ifdef _WIN32
  421. /* Create substitutes for POSIX functions in Win32. */
  422. #if defined(__MINGW32__)
  423. /* Show no warning in case system functions are not used. */
  424. #pragma GCC diagnostic push
  425. #pragma GCC diagnostic ignored "-Wunused-function"
  426. #endif
  427. static CRITICAL_SECTION global_log_file_lock;
  428. static DWORD
  429. pthread_self(void)
  430. {
  431. return GetCurrentThreadId();
  432. }
  433. static int
  434. pthread_key_create(
  435. pthread_key_t *key,
  436. void (*_ignored)(void *) /* destructor not supported for Windows */
  437. )
  438. {
  439. (void)_ignored;
  440. if ((key != 0)) {
  441. *key = TlsAlloc();
  442. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  443. }
  444. return -2;
  445. }
  446. static int
  447. pthread_key_delete(pthread_key_t key)
  448. {
  449. return TlsFree(key) ? 0 : 1;
  450. }
  451. static int
  452. pthread_setspecific(pthread_key_t key, void *value)
  453. {
  454. return TlsSetValue(key, value) ? 0 : 1;
  455. }
  456. static void *
  457. pthread_getspecific(pthread_key_t key)
  458. {
  459. return TlsGetValue(key);
  460. }
  461. #if defined(__MINGW32__)
  462. /* Enable unused function warning again */
  463. #pragma GCC diagnostic pop
  464. #endif
  465. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  466. #else
  467. static pthread_mutexattr_t pthread_mutex_attr;
  468. #endif /* _WIN32 */
  469. #define PASSWORDS_FILE_NAME ".htpasswd"
  470. #define CGI_ENVIRONMENT_SIZE (4096)
  471. #define MAX_CGI_ENVIR_VARS (256)
  472. #define MG_BUF_LEN (8192)
  473. #ifndef MAX_REQUEST_SIZE
  474. #define MAX_REQUEST_SIZE (16384)
  475. #endif
  476. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  477. "request size length must be a positive number");
  478. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  479. #if !defined(DEBUG_TRACE)
  480. #if defined(DEBUG)
  481. static void DEBUG_TRACE_FUNC(const char *func,
  482. unsigned line,
  483. PRINTF_FORMAT_STRING(const char *fmt),
  484. ...) PRINTF_ARGS(3, 4);
  485. static void
  486. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  487. {
  488. va_list args;
  489. flockfile(stdout);
  490. printf("*** %lu.%p.%s.%u: ",
  491. (unsigned long)time(NULL),
  492. (void *)pthread_self(),
  493. func,
  494. line);
  495. va_start(args, fmt);
  496. vprintf(fmt, args);
  497. va_end(args);
  498. putchar('\n');
  499. fflush(stdout);
  500. funlockfile(stdout);
  501. }
  502. #define DEBUG_TRACE(fmt, ...) \
  503. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  504. #else
  505. #define DEBUG_TRACE(fmt, ...) \
  506. do { \
  507. } while (0)
  508. #endif /* DEBUG */
  509. #endif /* DEBUG_TRACE */
  510. #if defined(MEMORY_DEBUGGING)
  511. unsigned long mg_memory_debug_blockCount = 0;
  512. unsigned long mg_memory_debug_totalMemUsed = 0;
  513. static void *
  514. mg_malloc_ex(size_t size, const char *file, unsigned line)
  515. {
  516. void *data = malloc(size + sizeof(size_t));
  517. void *memory = 0;
  518. char mallocStr[256];
  519. if (data) {
  520. *(size_t *)data = size;
  521. mg_memory_debug_totalMemUsed += size;
  522. mg_memory_debug_blockCount++;
  523. memory = (void *)(((char *)data) + sizeof(size_t));
  524. }
  525. sprintf(mallocStr,
  526. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  527. memory,
  528. (unsigned long)size,
  529. mg_memory_debug_totalMemUsed,
  530. mg_memory_debug_blockCount,
  531. file,
  532. line);
  533. #if defined(_WIN32)
  534. OutputDebugStringA(mallocStr);
  535. #else
  536. DEBUG_TRACE("%s", mallocStr);
  537. #endif
  538. return memory;
  539. }
  540. static void *
  541. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  542. {
  543. void *data = mg_malloc_ex(size * count, file, line);
  544. if (data) {
  545. memset(data, 0, size);
  546. }
  547. return data;
  548. }
  549. static void
  550. mg_free_ex(void *memory, const char *file, unsigned line)
  551. {
  552. char mallocStr[256];
  553. void *data = (void *)(((char *)memory) - sizeof(size_t));
  554. size_t size;
  555. if (memory) {
  556. size = *(size_t *)data;
  557. mg_memory_debug_totalMemUsed -= size;
  558. mg_memory_debug_blockCount--;
  559. sprintf(mallocStr,
  560. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  561. memory,
  562. (unsigned long)size,
  563. mg_memory_debug_totalMemUsed,
  564. mg_memory_debug_blockCount,
  565. file,
  566. line);
  567. #if defined(_WIN32)
  568. OutputDebugStringA(mallocStr);
  569. #else
  570. DEBUG_TRACE("%s", mallocStr);
  571. #endif
  572. free(data);
  573. }
  574. }
  575. static void *
  576. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  577. {
  578. char mallocStr[256];
  579. void *data;
  580. void *_realloc;
  581. size_t oldsize;
  582. if (newsize) {
  583. if (memory) {
  584. data = (void *)(((char *)memory) - sizeof(size_t));
  585. oldsize = *(size_t *)data;
  586. _realloc = realloc(data, newsize + sizeof(size_t));
  587. if (_realloc) {
  588. data = _realloc;
  589. mg_memory_debug_totalMemUsed -= oldsize;
  590. sprintf(mallocStr,
  591. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  592. memory,
  593. (unsigned long)oldsize,
  594. mg_memory_debug_totalMemUsed,
  595. mg_memory_debug_blockCount,
  596. file,
  597. line);
  598. #if defined(_WIN32)
  599. OutputDebugStringA(mallocStr);
  600. #else
  601. DEBUG_TRACE("%s", mallocStr);
  602. #endif
  603. mg_memory_debug_totalMemUsed += newsize;
  604. sprintf(mallocStr,
  605. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  606. memory,
  607. (unsigned long)newsize,
  608. mg_memory_debug_totalMemUsed,
  609. mg_memory_debug_blockCount,
  610. file,
  611. line);
  612. #if defined(_WIN32)
  613. OutputDebugStringA(mallocStr);
  614. #else
  615. DEBUG_TRACE("%s", mallocStr);
  616. #endif
  617. *(size_t *)data = newsize;
  618. data = (void *)(((char *)data) + sizeof(size_t));
  619. } else {
  620. #if defined(_WIN32)
  621. OutputDebugStringA("MEM: realloc failed\n");
  622. #else
  623. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  624. #endif
  625. return _realloc;
  626. }
  627. } else {
  628. data = mg_malloc_ex(newsize, file, line);
  629. }
  630. } else {
  631. data = 0;
  632. mg_free_ex(memory, file, line);
  633. }
  634. return data;
  635. }
  636. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  637. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  638. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  639. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  640. #else
  641. static __inline void *
  642. mg_malloc(size_t a)
  643. {
  644. return malloc(a);
  645. }
  646. static __inline void *
  647. mg_calloc(size_t a, size_t b)
  648. {
  649. return calloc(a, b);
  650. }
  651. static __inline void *
  652. mg_realloc(void *a, size_t b)
  653. {
  654. return realloc(a, b);
  655. }
  656. static __inline void
  657. mg_free(void *a)
  658. {
  659. free(a);
  660. }
  661. #endif
  662. static void mg_vsnprintf(const struct mg_connection *conn,
  663. int *truncated,
  664. char *buf,
  665. size_t buflen,
  666. const char *fmt,
  667. va_list ap);
  668. static void mg_snprintf(const struct mg_connection *conn,
  669. int *truncated,
  670. char *buf,
  671. size_t buflen,
  672. PRINTF_FORMAT_STRING(const char *fmt),
  673. ...) PRINTF_ARGS(5, 6);
  674. /* This following lines are just meant as a reminder to use the mg-functions
  675. * for memory management */
  676. #ifdef malloc
  677. #undef malloc
  678. #endif
  679. #ifdef calloc
  680. #undef calloc
  681. #endif
  682. #ifdef realloc
  683. #undef realloc
  684. #endif
  685. #ifdef free
  686. #undef free
  687. #endif
  688. #ifdef snprintf
  689. #undef snprintf
  690. #endif
  691. #ifdef vsnprintf
  692. #undef vsnprintf
  693. #endif
  694. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  695. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  696. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  697. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  698. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  699. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  700. * but this define only works well for Windows. */
  701. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  702. #endif
  703. #define MD5_STATIC static
  704. #include "md5.inl"
  705. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  706. #ifdef NO_SOCKLEN_T
  707. typedef int socklen_t;
  708. #endif /* NO_SOCKLEN_T */
  709. #define _DARWIN_UNLIMITED_SELECT
  710. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  711. #if !defined(MSG_NOSIGNAL)
  712. #define MSG_NOSIGNAL (0)
  713. #endif
  714. #if !defined(SOMAXCONN)
  715. #define SOMAXCONN (100)
  716. #endif
  717. /* Size of the accepted socket queue */
  718. #if !defined(MGSQLEN)
  719. #define MGSQLEN (20)
  720. #endif
  721. #if defined(NO_SSL_DL)
  722. #include <openssl/ssl.h>
  723. #include <openssl/err.h>
  724. #include <openssl/crypto.h>
  725. #include <openssl/x509.h>
  726. #include <openssl/pem.h>
  727. #else
  728. /* SSL loaded dynamically from DLL.
  729. * I put the prototypes here to be independent from OpenSSL source
  730. * installation. */
  731. typedef struct ssl_st SSL;
  732. typedef struct ssl_method_st SSL_METHOD;
  733. typedef struct ssl_ctx_st SSL_CTX;
  734. typedef struct x509_store_ctx_st X509_STORE_CTX;
  735. #define SSL_CTRL_OPTIONS (32)
  736. #define SSL_CTRL_CLEAR_OPTIONS (77)
  737. #define SSL_CTRL_SET_ECDH_AUTO (94)
  738. #define SSL_VERIFY_NONE (0)
  739. #define SSL_VERIFY_PEER (1)
  740. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  741. #define SSL_VERIFY_CLIENT_ONCE (4)
  742. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  743. #define SSL_OP_NO_SSLv2 (0x01000000L)
  744. #define SSL_OP_NO_SSLv3 (0x02000000L)
  745. #define SSL_OP_NO_TLSv1 (0x04000000L)
  746. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  747. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  748. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  749. struct ssl_func {
  750. const char *name; /* SSL function name */
  751. void (*ptr)(void); /* Function pointer */
  752. };
  753. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  754. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  755. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  756. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  757. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  758. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  759. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  760. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  761. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  762. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  763. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  764. #define SSL_CTX_use_PrivateKey_file \
  765. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  766. #define SSL_CTX_use_certificate_file \
  767. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  768. #define SSL_CTX_set_default_passwd_cb \
  769. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  770. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  771. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  772. #define SSL_CTX_use_certificate_chain_file \
  773. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  774. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  775. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  776. #define SSL_CTX_set_verify \
  777. (*(void (*)(SSL_CTX *, \
  778. int, \
  779. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  780. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  781. #define SSL_CTX_load_verify_locations \
  782. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  783. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  784. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  785. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  786. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  787. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  788. #define SSL_CIPHER_get_name \
  789. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  790. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  791. #define SSL_CTX_set_session_id_context \
  792. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  793. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  794. #define SSL_CTX_set_cipher_list \
  795. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  796. #define SSL_CTX_set_options(ctx, op) \
  797. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  798. #define SSL_CTX_clear_options(ctx, op) \
  799. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  800. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  801. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  802. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  803. #define CRYPTO_set_locking_callback \
  804. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  805. #define CRYPTO_set_id_callback \
  806. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  807. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  808. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  809. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  810. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  811. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  812. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  813. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  814. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  815. /* set_ssl_option() function updates this array.
  816. * It loads SSL library dynamically and changes NULLs to the actual addresses
  817. * of respective functions. The macros above (like SSL_connect()) are really
  818. * just calling these functions indirectly via the pointer. */
  819. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  820. {"SSL_accept", NULL},
  821. {"SSL_connect", NULL},
  822. {"SSL_read", NULL},
  823. {"SSL_write", NULL},
  824. {"SSL_get_error", NULL},
  825. {"SSL_set_fd", NULL},
  826. {"SSL_new", NULL},
  827. {"SSL_CTX_new", NULL},
  828. {"SSLv23_server_method", NULL},
  829. {"SSL_library_init", NULL},
  830. {"SSL_CTX_use_PrivateKey_file", NULL},
  831. {"SSL_CTX_use_certificate_file", NULL},
  832. {"SSL_CTX_set_default_passwd_cb", NULL},
  833. {"SSL_CTX_free", NULL},
  834. {"SSL_load_error_strings", NULL},
  835. {"SSL_CTX_use_certificate_chain_file", NULL},
  836. {"SSLv23_client_method", NULL},
  837. {"SSL_pending", NULL},
  838. {"SSL_CTX_set_verify", NULL},
  839. {"SSL_shutdown", NULL},
  840. {"SSL_CTX_load_verify_locations", NULL},
  841. {"SSL_CTX_set_default_verify_paths", NULL},
  842. {"SSL_CTX_set_verify_depth", NULL},
  843. {"SSL_get_peer_certificate", NULL},
  844. {"SSL_get_version", NULL},
  845. {"SSL_get_current_cipher", NULL},
  846. {"SSL_CIPHER_get_name", NULL},
  847. {"SSL_CTX_check_private_key", NULL},
  848. {"SSL_CTX_set_session_id_context", NULL},
  849. {"SSL_CTX_ctrl", NULL},
  850. {"SSL_CTX_set_cipher_list", NULL},
  851. {NULL, NULL}};
  852. /* Similar array as ssl_sw. These functions could be located in different
  853. * lib. */
  854. #if !defined(NO_SSL)
  855. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  856. {"CRYPTO_set_locking_callback", NULL},
  857. {"CRYPTO_set_id_callback", NULL},
  858. {"ERR_get_error", NULL},
  859. {"ERR_error_string", NULL},
  860. {"ERR_remove_state", NULL},
  861. {"ERR_free_strings", NULL},
  862. {"ENGINE_cleanup", NULL},
  863. {"CONF_modules_unload", NULL},
  864. {"CRYPTO_cleanup_all_ex_data", NULL},
  865. {"EVP_cleanup", NULL},
  866. {NULL, NULL}};
  867. #endif /* NO_SSL */
  868. #endif /* NO_SSL_DL */
  869. #if !defined(NO_CACHING)
  870. static const char *month_names[] = {"Jan",
  871. "Feb",
  872. "Mar",
  873. "Apr",
  874. "May",
  875. "Jun",
  876. "Jul",
  877. "Aug",
  878. "Sep",
  879. "Oct",
  880. "Nov",
  881. "Dec"};
  882. #endif /* !NO_CACHING */
  883. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  884. * union u. */
  885. union usa {
  886. struct sockaddr sa;
  887. struct sockaddr_in sin;
  888. #if defined(USE_IPV6)
  889. struct sockaddr_in6 sin6;
  890. #endif
  891. };
  892. /* Describes a string (chunk of memory). */
  893. struct vec {
  894. const char *ptr;
  895. size_t len;
  896. };
  897. struct file {
  898. uint64_t size;
  899. time_t last_modified;
  900. FILE *fp;
  901. const char *membuf; /* Non-NULL if file data is in memory */
  902. int is_directory;
  903. int gzipped; /* set to 1 if the content is gzipped
  904. * in which case we need a content-encoding: gzip header */
  905. };
  906. #define STRUCT_FILE_INITIALIZER \
  907. { \
  908. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  909. }
  910. /* Describes listening socket, or socket which was accept()-ed by the master
  911. * thread and queued for future handling by the worker thread. */
  912. struct socket {
  913. SOCKET sock; /* Listening socket */
  914. union usa lsa; /* Local socket address */
  915. union usa rsa; /* Remote socket address */
  916. unsigned char is_ssl; /* Is port SSL-ed */
  917. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  918. * port */
  919. };
  920. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  921. enum {
  922. CGI_EXTENSIONS,
  923. CGI_ENVIRONMENT,
  924. PUT_DELETE_PASSWORDS_FILE,
  925. CGI_INTERPRETER,
  926. PROTECT_URI,
  927. AUTHENTICATION_DOMAIN,
  928. SSI_EXTENSIONS,
  929. THROTTLE,
  930. ACCESS_LOG_FILE,
  931. ENABLE_DIRECTORY_LISTING,
  932. ERROR_LOG_FILE,
  933. GLOBAL_PASSWORDS_FILE,
  934. INDEX_FILES,
  935. ENABLE_KEEP_ALIVE,
  936. ACCESS_CONTROL_LIST,
  937. EXTRA_MIME_TYPES,
  938. LISTENING_PORTS,
  939. DOCUMENT_ROOT,
  940. SSL_CERTIFICATE,
  941. NUM_THREADS,
  942. RUN_AS_USER,
  943. REWRITE,
  944. HIDE_FILES,
  945. REQUEST_TIMEOUT,
  946. SSL_DO_VERIFY_PEER,
  947. SSL_CA_PATH,
  948. SSL_CA_FILE,
  949. SSL_VERIFY_DEPTH,
  950. SSL_DEFAULT_VERIFY_PATHS,
  951. SSL_CIPHER_LIST,
  952. SSL_PROTOCOL_VERSION,
  953. SSL_SHORT_TRUST,
  954. #if defined(USE_WEBSOCKET)
  955. WEBSOCKET_TIMEOUT,
  956. #endif
  957. DECODE_URL,
  958. #if defined(USE_LUA)
  959. LUA_PRELOAD_FILE,
  960. LUA_SCRIPT_EXTENSIONS,
  961. LUA_SERVER_PAGE_EXTENSIONS,
  962. #endif
  963. #if defined(USE_DUKTAPE)
  964. DUKTAPE_SCRIPT_EXTENSIONS,
  965. #endif
  966. #if defined(USE_WEBSOCKET)
  967. WEBSOCKET_ROOT,
  968. #endif
  969. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  970. LUA_WEBSOCKET_EXTENSIONS,
  971. #endif
  972. ACCESS_CONTROL_ALLOW_ORIGIN,
  973. ERROR_PAGES,
  974. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  975. * socket option typedef TCP_NODELAY. */
  976. #if !defined(NO_CACHING)
  977. STATIC_FILE_MAX_AGE,
  978. #endif
  979. NUM_OPTIONS
  980. };
  981. /* Config option name, config types, default value */
  982. static struct mg_option config_options[] = {
  983. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  984. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  985. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  986. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  987. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  988. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  989. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  990. {"throttle", CONFIG_TYPE_STRING, NULL},
  991. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  992. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  993. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  994. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  995. {"index_files",
  996. CONFIG_TYPE_STRING,
  997. #ifdef USE_LUA
  998. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  999. "index.shtml,index.php"},
  1000. #else
  1001. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1002. #endif
  1003. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1004. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1005. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1006. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1007. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1008. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1009. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1010. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1011. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1012. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1013. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1014. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1015. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1016. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1017. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1018. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1019. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1020. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1021. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1022. #if defined(USE_WEBSOCKET)
  1023. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1024. #endif
  1025. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1026. #if defined(USE_LUA)
  1027. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1028. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1029. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1030. #endif
  1031. #if defined(USE_DUKTAPE)
  1032. /* The support for duktape is still in alpha version state.
  1033. * The name of this config option might change. */
  1034. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1035. #endif
  1036. #if defined(USE_WEBSOCKET)
  1037. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1038. #endif
  1039. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1040. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1041. #endif
  1042. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1043. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1044. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1045. #if !defined(NO_CACHING)
  1046. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1047. #endif
  1048. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1049. /* Check if the config_options and the corresponding enum have compatible
  1050. * sizes. */
  1051. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1052. == (NUM_OPTIONS + 1),
  1053. "config_options and enum not sync");
  1054. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1055. struct mg_handler_info {
  1056. /* Name/Pattern of the URI. */
  1057. char *uri;
  1058. size_t uri_len;
  1059. /* handler type */
  1060. int handler_type;
  1061. /* Handler for http/https or authorization requests. */
  1062. mg_request_handler handler;
  1063. /* Handler for ws/wss (websocket) requests. */
  1064. mg_websocket_connect_handler connect_handler;
  1065. mg_websocket_ready_handler ready_handler;
  1066. mg_websocket_data_handler data_handler;
  1067. mg_websocket_close_handler close_handler;
  1068. /* Handler for authorization requests */
  1069. mg_authorization_handler auth_handler;
  1070. /* User supplied argument for the handler function. */
  1071. void *cbdata;
  1072. /* next handler in a linked list */
  1073. struct mg_handler_info *next;
  1074. };
  1075. struct mg_context {
  1076. volatile int stop_flag; /* Should we stop event loop */
  1077. SSL_CTX *ssl_ctx; /* SSL context */
  1078. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1079. struct mg_callbacks callbacks; /* User-defined callback function */
  1080. void *user_data; /* User-defined data */
  1081. int context_type; /* 1 = server context, 2 = client context */
  1082. struct socket *listening_sockets;
  1083. in_port_t *listening_ports;
  1084. unsigned int num_listening_sockets;
  1085. volatile int
  1086. running_worker_threads; /* Number of currently running worker threads */
  1087. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1088. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1089. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1090. volatile int sq_head; /* Head of the socket queue */
  1091. volatile int sq_tail; /* Tail of the socket queue */
  1092. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1093. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1094. pthread_t masterthreadid; /* The master thread ID */
  1095. unsigned int
  1096. cfg_worker_threads; /* The number of configured worker threads. */
  1097. pthread_t *workerthreadids; /* The worker thread IDs */
  1098. time_t start_time; /* Server start time, used for authentication */
  1099. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1100. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1101. unsigned long nonce_count; /* Used nonces, used for authentication */
  1102. char *systemName; /* What operating system is running */
  1103. /* linked list of uri handlers */
  1104. struct mg_handler_info *handlers;
  1105. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1106. /* linked list of shared lua websockets */
  1107. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1108. #endif
  1109. #ifdef USE_TIMERS
  1110. struct ttimers *timers;
  1111. #endif
  1112. };
  1113. struct mg_connection {
  1114. struct mg_request_info request_info;
  1115. struct mg_context *ctx;
  1116. SSL *ssl; /* SSL descriptor */
  1117. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1118. struct socket client; /* Connected client */
  1119. time_t conn_birth_time; /* Time (wall clock) when connection was
  1120. * established */
  1121. struct timespec req_time; /* Time (since system start) when the request
  1122. * was received */
  1123. int64_t num_bytes_sent; /* Total bytes sent to client */
  1124. int64_t content_len; /* Content-Length header value */
  1125. int64_t consumed_content; /* How many bytes of content have been read */
  1126. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1127. * data available, 2: all data read */
  1128. size_t chunk_remainder; /* Unread data from the last chunk */
  1129. char *buf; /* Buffer for received data */
  1130. char *path_info; /* PATH_INFO part of the URL */
  1131. int must_close; /* 1 if connection must be closed */
  1132. int in_error_handler; /* 1 if in handler for user defined error
  1133. * pages */
  1134. int internal_error; /* 1 if an error occured while processing the
  1135. * request */
  1136. int buf_size; /* Buffer size */
  1137. int request_len; /* Size of the request + headers in a buffer */
  1138. int data_len; /* Total size of data in a buffer */
  1139. int status_code; /* HTTP reply status code, e.g. 200 */
  1140. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1141. * throttle */
  1142. time_t last_throttle_time; /* Last time throttled data was sent */
  1143. int64_t last_throttle_bytes; /* Bytes sent this second */
  1144. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1145. * atomic transmissions for websockets */
  1146. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1147. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1148. #endif
  1149. };
  1150. static pthread_key_t sTlsKey; /* Thread local storage index */
  1151. static int sTlsInit = 0;
  1152. static int thread_idx_max = 0;
  1153. struct mg_workerTLS {
  1154. int is_master;
  1155. unsigned long thread_idx;
  1156. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1157. HANDLE pthread_cond_helper_mutex;
  1158. #endif
  1159. };
  1160. /* Directory entry */
  1161. struct de {
  1162. struct mg_connection *conn;
  1163. char *file_name;
  1164. struct file file;
  1165. };
  1166. #if defined(USE_WEBSOCKET)
  1167. static int is_websocket_protocol(const struct mg_connection *conn);
  1168. #else
  1169. #define is_websocket_protocol(conn) (0)
  1170. #endif
  1171. static int
  1172. mg_atomic_inc(volatile int *addr)
  1173. {
  1174. int ret;
  1175. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1176. /* Depending on the SDK, this function uses either
  1177. * (volatile unsigned int *) or (volatile LONG *),
  1178. * so whatever you use, the other SDK is likely to raise a warning. */
  1179. ret = InterlockedIncrement((volatile long *)addr);
  1180. #elif defined(__GNUC__) \
  1181. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1182. ret = __sync_add_and_fetch(addr, 1);
  1183. #else
  1184. ret = (++(*addr));
  1185. #endif
  1186. return ret;
  1187. }
  1188. static int
  1189. mg_atomic_dec(volatile int *addr)
  1190. {
  1191. int ret;
  1192. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1193. /* Depending on the SDK, this function uses either
  1194. * (volatile unsigned int *) or (volatile LONG *),
  1195. * so whatever you use, the other SDK is likely to raise a warning. */
  1196. ret = InterlockedDecrement((volatile long *)addr);
  1197. #elif defined(__GNUC__) \
  1198. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1199. ret = __sync_sub_and_fetch(addr, 1);
  1200. #else
  1201. ret = (--(*addr));
  1202. #endif
  1203. return ret;
  1204. }
  1205. #if !defined(NO_THREAD_NAME)
  1206. #if defined(_WIN32) && defined(_MSC_VER)
  1207. /* Set the thread name for debugging purposes in Visual Studio
  1208. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1209. */
  1210. #pragma pack(push, 8)
  1211. typedef struct tagTHREADNAME_INFO {
  1212. DWORD dwType; /* Must be 0x1000. */
  1213. LPCSTR szName; /* Pointer to name (in user addr space). */
  1214. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1215. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1216. } THREADNAME_INFO;
  1217. #pragma pack(pop)
  1218. #elif defined(__linux__)
  1219. #include <sys/prctl.h>
  1220. #include <sys/sendfile.h>
  1221. #endif
  1222. static void
  1223. mg_set_thread_name(const char *name)
  1224. {
  1225. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1226. mg_snprintf(
  1227. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1228. #if defined(_WIN32)
  1229. #if defined(_MSC_VER)
  1230. /* Windows and Visual Studio Compiler */
  1231. __try
  1232. {
  1233. THREADNAME_INFO info;
  1234. info.dwType = 0x1000;
  1235. info.szName = threadName;
  1236. info.dwThreadID = ~0U;
  1237. info.dwFlags = 0;
  1238. RaiseException(0x406D1388,
  1239. 0,
  1240. sizeof(info) / sizeof(ULONG_PTR),
  1241. (ULONG_PTR *)&info);
  1242. }
  1243. __except(EXCEPTION_EXECUTE_HANDLER)
  1244. {
  1245. }
  1246. #elif defined(__MINGW32__)
  1247. /* No option known to set thread name for MinGW */
  1248. #endif
  1249. #elif defined(__GLIBC__) \
  1250. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1251. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1252. (void)pthread_setname_np(pthread_self(), threadName);
  1253. #elif defined(__linux__)
  1254. /* on linux we can use the old prctl function */
  1255. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1256. #endif
  1257. }
  1258. #else /* !defined(NO_THREAD_NAME) */
  1259. void
  1260. mg_set_thread_name(const char *threadName)
  1261. {
  1262. }
  1263. #endif
  1264. #if defined(MG_LEGACY_INTERFACE)
  1265. const char **
  1266. mg_get_valid_option_names(void)
  1267. {
  1268. /* This function is deprecated. Use mg_get_valid_options instead. */
  1269. static const char *
  1270. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1271. int i;
  1272. for (i = 0; config_options[i].name != NULL; i++) {
  1273. data[i * 2] = config_options[i].name;
  1274. data[i * 2 + 1] = config_options[i].default_value;
  1275. }
  1276. return data;
  1277. }
  1278. #endif
  1279. const struct mg_option *
  1280. mg_get_valid_options(void)
  1281. {
  1282. return config_options;
  1283. }
  1284. static int
  1285. is_file_in_memory(const struct mg_connection *conn,
  1286. const char *path,
  1287. struct file *filep)
  1288. {
  1289. size_t size = 0;
  1290. if (!conn || !filep) {
  1291. return 0;
  1292. }
  1293. if (conn->ctx->callbacks.open_file) {
  1294. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1295. if (filep->membuf != NULL) {
  1296. /* NOTE: override filep->size only on success. Otherwise, it might
  1297. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1298. filep->size = size;
  1299. }
  1300. }
  1301. return filep->membuf != NULL;
  1302. }
  1303. static int
  1304. is_file_opened(const struct file *filep)
  1305. {
  1306. if (!filep) {
  1307. return 0;
  1308. }
  1309. return filep->membuf != NULL || filep->fp != NULL;
  1310. }
  1311. /* mg_fopen will open a file either in memory or on the disk.
  1312. * The input parameter path is a string in UTF-8 encoding.
  1313. * The input parameter mode is the same as for fopen.
  1314. * Either fp or membuf will be set in the output struct filep.
  1315. * The function returns 1 on success, 0 on error. */
  1316. static int
  1317. mg_fopen(const struct mg_connection *conn,
  1318. const char *path,
  1319. const char *mode,
  1320. struct file *filep)
  1321. {
  1322. struct stat st;
  1323. if (!filep) {
  1324. return 0;
  1325. }
  1326. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1327. * only get the file status. They should not work on different members of
  1328. * the same structure (bad cohesion). */
  1329. memset(filep, 0, sizeof(*filep));
  1330. if (stat(path, &st) == 0) {
  1331. filep->size = (uint64_t)(st.st_size);
  1332. }
  1333. if (!is_file_in_memory(conn, path, filep)) {
  1334. #ifdef _WIN32
  1335. wchar_t wbuf[PATH_MAX], wmode[20];
  1336. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1337. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1338. filep->fp = _wfopen(wbuf, wmode);
  1339. #else
  1340. /* Linux et al already use unicode. No need to convert. */
  1341. filep->fp = fopen(path, mode);
  1342. #endif
  1343. }
  1344. return is_file_opened(filep);
  1345. }
  1346. static void
  1347. mg_fclose(struct file *filep)
  1348. {
  1349. if (filep != NULL && filep->fp != NULL) {
  1350. fclose(filep->fp);
  1351. }
  1352. }
  1353. static void
  1354. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1355. {
  1356. for (; *src != '\0' && n > 1; n--) {
  1357. *dst++ = *src++;
  1358. }
  1359. *dst = '\0';
  1360. }
  1361. static int
  1362. lowercase(const char *s)
  1363. {
  1364. return tolower(*(const unsigned char *)s);
  1365. }
  1366. int
  1367. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1368. {
  1369. int diff = 0;
  1370. if (len > 0) {
  1371. do {
  1372. diff = lowercase(s1++) - lowercase(s2++);
  1373. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1374. }
  1375. return diff;
  1376. }
  1377. static int
  1378. mg_strcasecmp(const char *s1, const char *s2)
  1379. {
  1380. int diff;
  1381. do {
  1382. diff = lowercase(s1++) - lowercase(s2++);
  1383. } while (diff == 0 && s1[-1] != '\0');
  1384. return diff;
  1385. }
  1386. static char *
  1387. mg_strndup(const char *ptr, size_t len)
  1388. {
  1389. char *p;
  1390. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1391. mg_strlcpy(p, ptr, len + 1);
  1392. }
  1393. return p;
  1394. }
  1395. static char *
  1396. mg_strdup(const char *str)
  1397. {
  1398. return mg_strndup(str, strlen(str));
  1399. }
  1400. static const char *
  1401. mg_strcasestr(const char *big_str, const char *small_str)
  1402. {
  1403. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1404. if (big_len >= small_len) {
  1405. for (i = 0; i <= (big_len - small_len); i++) {
  1406. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1407. return big_str + i;
  1408. }
  1409. }
  1410. }
  1411. return NULL;
  1412. }
  1413. /* Return null terminated string of given maximum length.
  1414. * Report errors if length is exceeded. */
  1415. static void
  1416. mg_vsnprintf(const struct mg_connection *conn,
  1417. int *truncated,
  1418. char *buf,
  1419. size_t buflen,
  1420. const char *fmt,
  1421. va_list ap)
  1422. {
  1423. int n, ok;
  1424. if (buflen == 0) {
  1425. return;
  1426. }
  1427. #ifdef __clang__
  1428. #pragma clang diagnostic push
  1429. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1430. /* Using fmt as a non-literal is intended here, since it is mostly called
  1431. * indirectly by mg_snprintf */
  1432. #endif
  1433. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1434. ok = (n >= 0) && ((size_t)n < buflen);
  1435. #ifdef __clang__
  1436. #pragma clang diagnostic pop
  1437. #endif
  1438. if (ok) {
  1439. if (truncated) {
  1440. *truncated = 0;
  1441. }
  1442. } else {
  1443. if (truncated) {
  1444. *truncated = 1;
  1445. }
  1446. mg_cry(conn,
  1447. "truncating vsnprintf buffer: [%.*s]",
  1448. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1449. buf);
  1450. n = (int)buflen - 1;
  1451. }
  1452. buf[n] = '\0';
  1453. }
  1454. static void
  1455. mg_snprintf(const struct mg_connection *conn,
  1456. int *truncated,
  1457. char *buf,
  1458. size_t buflen,
  1459. const char *fmt,
  1460. ...)
  1461. {
  1462. va_list ap;
  1463. va_start(ap, fmt);
  1464. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1465. va_end(ap);
  1466. }
  1467. static int
  1468. get_option_index(const char *name)
  1469. {
  1470. int i;
  1471. for (i = 0; config_options[i].name != NULL; i++) {
  1472. if (strcmp(config_options[i].name, name) == 0) {
  1473. return i;
  1474. }
  1475. }
  1476. return -1;
  1477. }
  1478. const char *
  1479. mg_get_option(const struct mg_context *ctx, const char *name)
  1480. {
  1481. int i;
  1482. if ((i = get_option_index(name)) == -1) {
  1483. return NULL;
  1484. } else if (!ctx || ctx->config[i] == NULL) {
  1485. return "";
  1486. } else {
  1487. return ctx->config[i];
  1488. }
  1489. }
  1490. struct mg_context *
  1491. mg_get_context(const struct mg_connection *conn)
  1492. {
  1493. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1494. }
  1495. void *
  1496. mg_get_user_data(const struct mg_context *ctx)
  1497. {
  1498. return (ctx == NULL) ? NULL : ctx->user_data;
  1499. }
  1500. void
  1501. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1502. {
  1503. if (conn != NULL) {
  1504. conn->request_info.conn_data = data;
  1505. }
  1506. }
  1507. void *
  1508. mg_get_user_connection_data(const struct mg_connection *conn)
  1509. {
  1510. if (conn != NULL) {
  1511. return conn->request_info.conn_data;
  1512. }
  1513. return NULL;
  1514. }
  1515. size_t
  1516. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1517. {
  1518. size_t i;
  1519. if (!ctx) {
  1520. return 0;
  1521. }
  1522. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1523. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1524. ports[i] = ctx->listening_ports[i];
  1525. }
  1526. return i;
  1527. }
  1528. int
  1529. mg_get_server_ports(const struct mg_context *ctx,
  1530. int size,
  1531. struct mg_server_ports *ports)
  1532. {
  1533. int i, cnt = 0;
  1534. if (size <= 0) {
  1535. return -1;
  1536. }
  1537. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1538. if (!ctx) {
  1539. return -1;
  1540. }
  1541. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1542. return -1;
  1543. }
  1544. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1545. ports[cnt].port = ctx->listening_ports[i];
  1546. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1547. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1548. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1549. /* IPv4 */
  1550. ports[cnt].protocol = 1;
  1551. cnt++;
  1552. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1553. /* IPv6 */
  1554. ports[cnt].protocol = 3;
  1555. cnt++;
  1556. }
  1557. }
  1558. return cnt;
  1559. }
  1560. static void
  1561. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1562. {
  1563. buf[0] = '\0';
  1564. if (!usa) {
  1565. return;
  1566. }
  1567. if (usa->sa.sa_family == AF_INET) {
  1568. getnameinfo(&usa->sa,
  1569. sizeof(usa->sin),
  1570. buf,
  1571. (unsigned)len,
  1572. NULL,
  1573. 0,
  1574. NI_NUMERICHOST);
  1575. }
  1576. #if defined(USE_IPV6)
  1577. else if (usa->sa.sa_family == AF_INET6) {
  1578. getnameinfo(&usa->sa,
  1579. sizeof(usa->sin6),
  1580. buf,
  1581. (unsigned)len,
  1582. NULL,
  1583. 0,
  1584. NI_NUMERICHOST);
  1585. }
  1586. #endif
  1587. }
  1588. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1589. * included in all responses other than 100, 101, 5xx. */
  1590. static void
  1591. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1592. {
  1593. struct tm *tm;
  1594. tm = gmtime(t);
  1595. if (tm != NULL) {
  1596. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1597. } else {
  1598. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1599. buf[buf_len - 1] = '\0';
  1600. }
  1601. }
  1602. /* difftime for struct timespec. Return value is in seconds. */
  1603. static double
  1604. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1605. {
  1606. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1607. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1608. }
  1609. /* Print error message to the opened error log stream. */
  1610. void
  1611. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1612. {
  1613. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1614. va_list ap;
  1615. struct file fi;
  1616. time_t timestamp;
  1617. va_start(ap, fmt);
  1618. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1619. va_end(ap);
  1620. buf[sizeof(buf) - 1] = 0;
  1621. if (!conn) {
  1622. puts(buf);
  1623. return;
  1624. }
  1625. /* Do not lock when getting the callback value, here and below.
  1626. * I suppose this is fine, since function cannot disappear in the
  1627. * same way string option can. */
  1628. if ((conn->ctx->callbacks.log_message == NULL)
  1629. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1630. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1631. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1632. == 0) {
  1633. fi.fp = NULL;
  1634. }
  1635. } else {
  1636. fi.fp = NULL;
  1637. }
  1638. if (fi.fp != NULL) {
  1639. flockfile(fi.fp);
  1640. timestamp = time(NULL);
  1641. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1642. fprintf(fi.fp,
  1643. "[%010lu] [error] [client %s] ",
  1644. (unsigned long)timestamp,
  1645. src_addr);
  1646. if (conn->request_info.request_method != NULL) {
  1647. fprintf(fi.fp,
  1648. "%s %s: ",
  1649. conn->request_info.request_method,
  1650. conn->request_info.request_uri);
  1651. }
  1652. fprintf(fi.fp, "%s", buf);
  1653. fputc('\n', fi.fp);
  1654. fflush(fi.fp);
  1655. funlockfile(fi.fp);
  1656. mg_fclose(&fi);
  1657. }
  1658. }
  1659. }
  1660. /* Return fake connection structure. Used for logging, if connection
  1661. * is not applicable at the moment of logging. */
  1662. static struct mg_connection *
  1663. fc(struct mg_context *ctx)
  1664. {
  1665. static struct mg_connection fake_connection;
  1666. fake_connection.ctx = ctx;
  1667. return &fake_connection;
  1668. }
  1669. const char *
  1670. mg_version(void)
  1671. {
  1672. return CIVETWEB_VERSION;
  1673. }
  1674. const struct mg_request_info *
  1675. mg_get_request_info(const struct mg_connection *conn)
  1676. {
  1677. if (!conn) {
  1678. return NULL;
  1679. }
  1680. return &conn->request_info;
  1681. }
  1682. /* Skip the characters until one of the delimiters characters found.
  1683. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1684. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1685. * Delimiters can be quoted with quotechar. */
  1686. static char *
  1687. skip_quoted(char **buf,
  1688. const char *delimiters,
  1689. const char *whitespace,
  1690. char quotechar)
  1691. {
  1692. char *p, *begin_word, *end_word, *end_whitespace;
  1693. begin_word = *buf;
  1694. end_word = begin_word + strcspn(begin_word, delimiters);
  1695. /* Check for quotechar */
  1696. if (end_word > begin_word) {
  1697. p = end_word - 1;
  1698. while (*p == quotechar) {
  1699. /* While the delimiter is quoted, look for the next delimiter. */
  1700. /* This happens, e.g., in calls from parse_auth_header,
  1701. * if the user name contains a " character. */
  1702. /* If there is anything beyond end_word, copy it. */
  1703. if (*end_word != '\0') {
  1704. size_t end_off = strcspn(end_word + 1, delimiters);
  1705. memmove(p, end_word, end_off + 1);
  1706. p += end_off; /* p must correspond to end_word - 1 */
  1707. end_word += end_off + 1;
  1708. } else {
  1709. *p = '\0';
  1710. break;
  1711. }
  1712. }
  1713. for (p++; p < end_word; p++) {
  1714. *p = '\0';
  1715. }
  1716. }
  1717. if (*end_word == '\0') {
  1718. *buf = end_word;
  1719. } else {
  1720. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1721. for (p = end_word; p < end_whitespace; p++) {
  1722. *p = '\0';
  1723. }
  1724. *buf = end_whitespace;
  1725. }
  1726. return begin_word;
  1727. }
  1728. /* Simplified version of skip_quoted without quote char
  1729. * and whitespace == delimiters */
  1730. static char *
  1731. skip(char **buf, const char *delimiters)
  1732. {
  1733. return skip_quoted(buf, delimiters, delimiters, 0);
  1734. }
  1735. /* Return HTTP header value, or NULL if not found. */
  1736. static const char *
  1737. get_header(const struct mg_request_info *ri, const char *name)
  1738. {
  1739. int i;
  1740. if (ri) {
  1741. for (i = 0; i < ri->num_headers; i++) {
  1742. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1743. return ri->http_headers[i].value;
  1744. }
  1745. }
  1746. }
  1747. return NULL;
  1748. }
  1749. const char *
  1750. mg_get_header(const struct mg_connection *conn, const char *name)
  1751. {
  1752. if (!conn) {
  1753. return NULL;
  1754. }
  1755. return get_header(&conn->request_info, name);
  1756. }
  1757. /* A helper function for traversing a comma separated list of values.
  1758. * It returns a list pointer shifted to the next value, or NULL if the end
  1759. * of the list found.
  1760. * Value is stored in val vector. If value has form "x=y", then eq_val
  1761. * vector is initialized to point to the "y" part, and val vector length
  1762. * is adjusted to point only to "x". */
  1763. static const char *
  1764. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1765. {
  1766. int end;
  1767. reparse:
  1768. if (val == NULL || list == NULL || *list == '\0') {
  1769. /* End of the list */
  1770. list = NULL;
  1771. } else {
  1772. /* Skip over leading LWS */
  1773. while (*list == ' ' || *list == '\t')
  1774. list++;
  1775. val->ptr = list;
  1776. if ((list = strchr(val->ptr, ',')) != NULL) {
  1777. /* Comma found. Store length and shift the list ptr */
  1778. val->len = ((size_t)(list - val->ptr));
  1779. list++;
  1780. } else {
  1781. /* This value is the last one */
  1782. list = val->ptr + strlen(val->ptr);
  1783. val->len = ((size_t)(list - val->ptr));
  1784. }
  1785. /* Adjust length for trailing LWS */
  1786. end = (int)val->len - 1;
  1787. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1788. end--;
  1789. val->len = (size_t)(end + 1);
  1790. if (val->len == 0) {
  1791. /* Ignore any empty entries. */
  1792. goto reparse;
  1793. }
  1794. if (eq_val != NULL) {
  1795. /* Value has form "x=y", adjust pointers and lengths
  1796. * so that val points to "x", and eq_val points to "y". */
  1797. eq_val->len = 0;
  1798. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1799. if (eq_val->ptr != NULL) {
  1800. eq_val->ptr++; /* Skip over '=' character */
  1801. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1802. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1803. }
  1804. }
  1805. }
  1806. return list;
  1807. }
  1808. /* A helper function for checking if a comma separated list of values contains
  1809. * the given option (case insensitvely).
  1810. * 'header' can be NULL, in which case false is returned. */
  1811. static int
  1812. header_has_option(const char *header, const char *option)
  1813. {
  1814. struct vec opt_vec;
  1815. struct vec eq_vec;
  1816. assert(option != NULL);
  1817. assert(option[0] != '\0');
  1818. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1819. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1820. return 1;
  1821. }
  1822. return 0;
  1823. }
  1824. /* Perform case-insensitive match of string against pattern */
  1825. static int
  1826. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1827. {
  1828. const char *or_str;
  1829. size_t i;
  1830. int j, len, res;
  1831. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1832. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1833. return res > 0 ? res : match_prefix(or_str + 1,
  1834. (size_t)((pattern + pattern_len)
  1835. - (or_str + 1)),
  1836. str);
  1837. }
  1838. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1839. if (pattern[i] == '?' && str[j] != '\0') {
  1840. continue;
  1841. } else if (pattern[i] == '$') {
  1842. return str[j] == '\0' ? j : -1;
  1843. } else if (pattern[i] == '*') {
  1844. i++;
  1845. if (pattern[i] == '*') {
  1846. i++;
  1847. len = (int)strlen(str + j);
  1848. } else {
  1849. len = (int)strcspn(str + j, "/");
  1850. }
  1851. if (i == pattern_len) {
  1852. return j + len;
  1853. }
  1854. do {
  1855. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1856. } while (res == -1 && len-- > 0);
  1857. return res == -1 ? -1 : j + res + len;
  1858. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1859. return -1;
  1860. }
  1861. }
  1862. return j;
  1863. }
  1864. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1865. * This function must tolerate situations when connection info is not
  1866. * set up, for example if request parsing failed. */
  1867. static int
  1868. should_keep_alive(const struct mg_connection *conn)
  1869. {
  1870. if (conn != NULL) {
  1871. const char *http_version = conn->request_info.http_version;
  1872. const char *header = mg_get_header(conn, "Connection");
  1873. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1874. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1875. || (header != NULL && !header_has_option(header, "keep-alive"))
  1876. || (header == NULL && http_version
  1877. && 0 != strcmp(http_version, "1.1"))) {
  1878. return 0;
  1879. }
  1880. return 1;
  1881. }
  1882. return 0;
  1883. }
  1884. static int
  1885. should_decode_url(const struct mg_connection *conn)
  1886. {
  1887. if (!conn || !conn->ctx) {
  1888. return 0;
  1889. }
  1890. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1891. }
  1892. static const char *
  1893. suggest_connection_header(const struct mg_connection *conn)
  1894. {
  1895. return should_keep_alive(conn) ? "keep-alive" : "close";
  1896. }
  1897. static int
  1898. send_no_cache_header(struct mg_connection *conn)
  1899. {
  1900. /* Send all current and obsolete cache opt-out directives. */
  1901. return mg_printf(conn,
  1902. "Cache-Control: no-cache, no-store, "
  1903. "must-revalidate, private, max-age=0\r\n"
  1904. "Pragma: no-cache\r\n"
  1905. "Expires: 0\r\n");
  1906. }
  1907. static int
  1908. send_static_cache_header(struct mg_connection *conn)
  1909. {
  1910. #if !defined(NO_CACHING)
  1911. /* Read the server config to check how long a file may be cached.
  1912. * The configuration is in seconds. */
  1913. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1914. if (max_age <= 0) {
  1915. /* 0 means "do not cache". All values <0 are reserved
  1916. * and may be used differently in the future. */
  1917. /* If a file should not be cached, do not only send
  1918. * max-age=0, but also pragmas and Expires headers. */
  1919. return send_no_cache_header(conn);
  1920. }
  1921. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1922. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1923. /* See also https://www.mnot.net/cache_docs/ */
  1924. /* According to RFC 2616, Section 14.21, caching times should not exceed
  1925. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  1926. * year to 31622400 seconds. For the moment, we just send whatever has
  1927. * been configured, still the behavior for >1 year should be considered
  1928. * as undefined. */
  1929. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1930. #else /* NO_CACHING */
  1931. return send_no_cache_header(conn);
  1932. #endif /* !NO_CACHING */
  1933. }
  1934. static void handle_file_based_request(struct mg_connection *conn,
  1935. const char *path,
  1936. struct file *filep);
  1937. static int
  1938. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1939. static const char *
  1940. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1941. {
  1942. /* See IANA HTTP status code assignment:
  1943. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1944. */
  1945. switch (response_code) {
  1946. /* RFC2616 Section 10.1 - Informational 1xx */
  1947. case 100:
  1948. return "Continue"; /* RFC2616 Section 10.1.1 */
  1949. case 101:
  1950. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1951. case 102:
  1952. return "Processing"; /* RFC2518 Section 10.1 */
  1953. /* RFC2616 Section 10.2 - Successful 2xx */
  1954. case 200:
  1955. return "OK"; /* RFC2616 Section 10.2.1 */
  1956. case 201:
  1957. return "Created"; /* RFC2616 Section 10.2.2 */
  1958. case 202:
  1959. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1960. case 203:
  1961. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1962. case 204:
  1963. return "No Content"; /* RFC2616 Section 10.2.5 */
  1964. case 205:
  1965. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1966. case 206:
  1967. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1968. case 207:
  1969. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1970. case 208:
  1971. return "Already Reported"; /* RFC5842 Section 7.1 */
  1972. case 226:
  1973. return "IM used"; /* RFC3229 Section 10.4.1 */
  1974. /* RFC2616 Section 10.3 - Redirection 3xx */
  1975. case 300:
  1976. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1977. case 301:
  1978. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1979. case 302:
  1980. return "Found"; /* RFC2616 Section 10.3.3 */
  1981. case 303:
  1982. return "See Other"; /* RFC2616 Section 10.3.4 */
  1983. case 304:
  1984. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1985. case 305:
  1986. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1987. case 307:
  1988. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1989. case 308:
  1990. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1991. /* RFC2616 Section 10.4 - Client Error 4xx */
  1992. case 400:
  1993. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1994. case 401:
  1995. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1996. case 402:
  1997. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1998. case 403:
  1999. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2000. case 404:
  2001. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2002. case 405:
  2003. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2004. case 406:
  2005. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2006. case 407:
  2007. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2008. case 408:
  2009. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2010. case 409:
  2011. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2012. case 410:
  2013. return "Gone"; /* RFC2616 Section 10.4.11 */
  2014. case 411:
  2015. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2016. case 412:
  2017. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2018. case 413:
  2019. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2020. case 414:
  2021. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2022. case 415:
  2023. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2024. case 416:
  2025. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2026. case 417:
  2027. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2028. case 421:
  2029. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2030. case 422:
  2031. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2032. * Section 11.2 */
  2033. case 423:
  2034. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2035. case 424:
  2036. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2037. * Section 11.4 */
  2038. case 426:
  2039. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2040. case 428:
  2041. return "Precondition Required"; /* RFC 6585, Section 3 */
  2042. case 429:
  2043. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2044. case 431:
  2045. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2046. case 451:
  2047. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2048. * Section 3 */
  2049. /* RFC2616 Section 10.5 - Server Error 5xx */
  2050. case 500:
  2051. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2052. case 501:
  2053. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2054. case 502:
  2055. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2056. case 503:
  2057. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2058. case 504:
  2059. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2060. case 505:
  2061. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2062. case 506:
  2063. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2064. case 507:
  2065. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2066. * Section 11.5 */
  2067. case 508:
  2068. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2069. case 510:
  2070. return "Not Extended"; /* RFC 2774, Section 7 */
  2071. case 511:
  2072. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2073. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2074. * E.g., "de facto" standards due to common use, ... */
  2075. case 418:
  2076. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2077. case 419:
  2078. return "Authentication Timeout"; /* common use */
  2079. default:
  2080. /* This error code is unknown. This should not happen. */
  2081. if (conn) {
  2082. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2083. }
  2084. /* Return at least a category according to RFC 2616 Section 10. */
  2085. if (response_code >= 100 && response_code < 200) {
  2086. /* Unknown informational status code */
  2087. return "Information";
  2088. }
  2089. if (response_code >= 200 && response_code < 300) {
  2090. /* Unknown success code */
  2091. return "Success";
  2092. }
  2093. if (response_code >= 300 && response_code < 400) {
  2094. /* Unknown redirection code */
  2095. return "Redirection";
  2096. }
  2097. if (response_code >= 400 && response_code < 500) {
  2098. /* Unknown request error code */
  2099. return "Client Error";
  2100. }
  2101. if (response_code >= 500 && response_code < 600) {
  2102. /* Unknown server error code */
  2103. return "Server Error";
  2104. }
  2105. /* Response code not even within reasonable range */
  2106. return "";
  2107. }
  2108. }
  2109. static void send_http_error(struct mg_connection *,
  2110. int,
  2111. PRINTF_FORMAT_STRING(const char *fmt),
  2112. ...) PRINTF_ARGS(3, 4);
  2113. static void
  2114. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2115. {
  2116. char buf[MG_BUF_LEN];
  2117. va_list ap;
  2118. int len, i, page_handler_found, scope, truncated;
  2119. char date[64];
  2120. time_t curtime = time(NULL);
  2121. const char *error_handler = NULL;
  2122. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2123. const char *error_page_file_ext, *tstr;
  2124. const char *status_text = mg_get_response_code_text(status, conn);
  2125. if (conn == NULL) {
  2126. return;
  2127. }
  2128. conn->status_code = status;
  2129. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2130. || conn->ctx->callbacks.http_error(conn, status)) {
  2131. if (!conn->in_error_handler) {
  2132. /* Send user defined error pages, if defined */
  2133. error_handler = conn->ctx->config[ERROR_PAGES];
  2134. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2135. page_handler_found = 0;
  2136. if (error_handler != NULL) {
  2137. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2138. switch (scope) {
  2139. case 1: /* Handler for specific error, e.g. 404 error */
  2140. mg_snprintf(conn,
  2141. &truncated,
  2142. buf,
  2143. sizeof(buf) - 32,
  2144. "%serror%03u.",
  2145. error_handler,
  2146. status);
  2147. break;
  2148. case 2: /* Handler for error group, e.g., 5xx error handler
  2149. * for all server errors (500-599) */
  2150. mg_snprintf(conn,
  2151. &truncated,
  2152. buf,
  2153. sizeof(buf) - 32,
  2154. "%serror%01uxx.",
  2155. error_handler,
  2156. status / 100);
  2157. break;
  2158. default: /* Handler for all errors */
  2159. mg_snprintf(conn,
  2160. &truncated,
  2161. buf,
  2162. sizeof(buf) - 32,
  2163. "%serror.",
  2164. error_handler);
  2165. break;
  2166. }
  2167. /* String truncation in buf may only occur if error_handler
  2168. * is too long. This string is from the config, not from a
  2169. * client. */
  2170. (void)truncated;
  2171. len = (int)strlen(buf);
  2172. tstr = strchr(error_page_file_ext, '.');
  2173. while (tstr) {
  2174. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2175. i++)
  2176. buf[len + i - 1] = tstr[i];
  2177. buf[len + i - 1] = 0;
  2178. if (mg_stat(conn, buf, &error_page_file)) {
  2179. page_handler_found = 1;
  2180. break;
  2181. }
  2182. tstr = strchr(tstr + i, '.');
  2183. }
  2184. }
  2185. }
  2186. if (page_handler_found) {
  2187. conn->in_error_handler = 1;
  2188. handle_file_based_request(conn, buf, &error_page_file);
  2189. conn->in_error_handler = 0;
  2190. return;
  2191. }
  2192. }
  2193. /* No custom error page. Send default error page. */
  2194. gmt_time_string(date, sizeof(date), &curtime);
  2195. conn->must_close = 1;
  2196. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2197. send_no_cache_header(conn);
  2198. mg_printf(conn,
  2199. "Date: %s\r\n"
  2200. "Connection: close\r\n\r\n",
  2201. date);
  2202. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2203. if (status > 199 && status != 204 && status != 304) {
  2204. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2205. if (fmt != NULL) {
  2206. va_start(ap, fmt);
  2207. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2208. va_end(ap);
  2209. mg_write(conn, buf, strlen(buf));
  2210. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2211. }
  2212. } else {
  2213. /* No body allowed. Close the connection. */
  2214. DEBUG_TRACE("Error %i", status);
  2215. }
  2216. }
  2217. }
  2218. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2219. /* Create substitutes for POSIX functions in Win32. */
  2220. #if defined(__MINGW32__)
  2221. /* Show no warning in case system functions are not used. */
  2222. #pragma GCC diagnostic push
  2223. #pragma GCC diagnostic ignored "-Wunused-function"
  2224. #endif
  2225. static int
  2226. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2227. {
  2228. (void)unused;
  2229. *mutex = CreateMutex(NULL, FALSE, NULL);
  2230. return *mutex == NULL ? -1 : 0;
  2231. }
  2232. static int
  2233. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2234. {
  2235. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2236. }
  2237. static int
  2238. pthread_mutex_lock(pthread_mutex_t *mutex)
  2239. {
  2240. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2241. }
  2242. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2243. static int
  2244. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2245. {
  2246. switch (WaitForSingleObject(*mutex, 0)) {
  2247. case WAIT_OBJECT_0:
  2248. return 0;
  2249. case WAIT_TIMEOUT:
  2250. return -2; /* EBUSY */
  2251. }
  2252. return -1;
  2253. }
  2254. #endif
  2255. static int
  2256. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2257. {
  2258. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2259. }
  2260. #ifndef WIN_PTHREADS_TIME_H
  2261. static int
  2262. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2263. {
  2264. FILETIME ft;
  2265. ULARGE_INTEGER li;
  2266. BOOL ok = FALSE;
  2267. double d;
  2268. static double perfcnt_per_sec = 0.0;
  2269. if (tp) {
  2270. memset(tp, 0, sizeof(*tp));
  2271. if (clk_id == CLOCK_REALTIME) {
  2272. GetSystemTimeAsFileTime(&ft);
  2273. li.LowPart = ft.dwLowDateTime;
  2274. li.HighPart = ft.dwHighDateTime;
  2275. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2276. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2277. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2278. ok = TRUE;
  2279. } else if (clk_id == CLOCK_MONOTONIC) {
  2280. if (perfcnt_per_sec == 0.0) {
  2281. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2282. perfcnt_per_sec = 1.0 / li.QuadPart;
  2283. }
  2284. if (perfcnt_per_sec != 0.0) {
  2285. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2286. d = li.QuadPart * perfcnt_per_sec;
  2287. tp->tv_sec = (time_t)d;
  2288. d -= tp->tv_sec;
  2289. tp->tv_nsec = (long)(d * 1.0E9);
  2290. ok = TRUE;
  2291. }
  2292. }
  2293. }
  2294. return ok ? 0 : -1;
  2295. }
  2296. #endif
  2297. static int
  2298. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2299. {
  2300. (void)unused;
  2301. InitializeCriticalSection(&cv->threadIdSec);
  2302. cv->waitingthreadcount = 0;
  2303. cv->waitingthreadhdls =
  2304. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2305. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2306. }
  2307. static int
  2308. pthread_cond_timedwait(pthread_cond_t *cv,
  2309. pthread_mutex_t *mutex,
  2310. const struct timespec *abstime)
  2311. {
  2312. struct mg_workerTLS *tls =
  2313. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2314. int ok;
  2315. struct timespec tsnow;
  2316. int64_t nsnow, nswaitabs, nswaitrel;
  2317. DWORD mswaitrel;
  2318. EnterCriticalSection(&cv->threadIdSec);
  2319. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2320. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2321. tls->pthread_cond_helper_mutex;
  2322. cv->waitingthreadcount++;
  2323. LeaveCriticalSection(&cv->threadIdSec);
  2324. if (abstime) {
  2325. clock_gettime(CLOCK_REALTIME, &tsnow);
  2326. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2327. nswaitabs =
  2328. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2329. nswaitrel = nswaitabs - nsnow;
  2330. if (nswaitrel < 0) {
  2331. nswaitrel = 0;
  2332. }
  2333. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2334. } else {
  2335. mswaitrel = INFINITE;
  2336. }
  2337. pthread_mutex_unlock(mutex);
  2338. ok = (WAIT_OBJECT_0
  2339. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2340. pthread_mutex_lock(mutex);
  2341. return ok ? 0 : -1;
  2342. }
  2343. static int
  2344. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2345. {
  2346. return pthread_cond_timedwait(cv, mutex, NULL);
  2347. }
  2348. static int
  2349. pthread_cond_signal(pthread_cond_t *cv)
  2350. {
  2351. int i;
  2352. HANDLE wkup = NULL;
  2353. BOOL ok = FALSE;
  2354. EnterCriticalSection(&cv->threadIdSec);
  2355. if (cv->waitingthreadcount) {
  2356. wkup = cv->waitingthreadhdls[0];
  2357. ok = SetEvent(wkup);
  2358. for (i = 1; i < cv->waitingthreadcount; i++) {
  2359. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2360. }
  2361. cv->waitingthreadcount--;
  2362. assert(ok);
  2363. }
  2364. LeaveCriticalSection(&cv->threadIdSec);
  2365. return ok ? 0 : 1;
  2366. }
  2367. static int
  2368. pthread_cond_broadcast(pthread_cond_t *cv)
  2369. {
  2370. EnterCriticalSection(&cv->threadIdSec);
  2371. while (cv->waitingthreadcount) {
  2372. pthread_cond_signal(cv);
  2373. }
  2374. LeaveCriticalSection(&cv->threadIdSec);
  2375. return 0;
  2376. }
  2377. static int
  2378. pthread_cond_destroy(pthread_cond_t *cv)
  2379. {
  2380. EnterCriticalSection(&cv->threadIdSec);
  2381. assert(cv->waitingthreadcount == 0);
  2382. mg_free(cv->waitingthreadhdls);
  2383. cv->waitingthreadhdls = 0;
  2384. LeaveCriticalSection(&cv->threadIdSec);
  2385. DeleteCriticalSection(&cv->threadIdSec);
  2386. return 0;
  2387. }
  2388. #if defined(__MINGW32__)
  2389. /* Enable unused function warning again */
  2390. #pragma GCC diagnostic pop
  2391. #endif
  2392. /* For Windows, change all slashes to backslashes in path names. */
  2393. static void
  2394. change_slashes_to_backslashes(char *path)
  2395. {
  2396. int i;
  2397. for (i = 0; path[i] != '\0'; i++) {
  2398. if (path[i] == '/') {
  2399. path[i] = '\\';
  2400. }
  2401. /* remove double backslash (check i > 0 to preserve UNC paths,
  2402. * like \\server\file.txt) */
  2403. if ((path[i] == '\\') && (i > 0)) {
  2404. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2405. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2406. }
  2407. }
  2408. }
  2409. }
  2410. static int
  2411. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2412. {
  2413. int diff;
  2414. do {
  2415. diff = tolower(*s1) - tolower(*s2);
  2416. s1++;
  2417. s2++;
  2418. } while (diff == 0 && s1[-1] != '\0');
  2419. return diff;
  2420. }
  2421. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2422. * wbuf and wbuf_len is a target buffer and its length. */
  2423. static void
  2424. path_to_unicode(const struct mg_connection *conn,
  2425. const char *path,
  2426. wchar_t *wbuf,
  2427. size_t wbuf_len)
  2428. {
  2429. char buf[PATH_MAX], buf2[PATH_MAX];
  2430. wchar_t wbuf2[MAX_PATH + 1];
  2431. DWORD long_len, err;
  2432. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2433. mg_strlcpy(buf, path, sizeof(buf));
  2434. change_slashes_to_backslashes(buf);
  2435. /* Convert to Unicode and back. If doubly-converted string does not
  2436. * match the original, something is fishy, reject. */
  2437. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2438. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2439. WideCharToMultiByte(
  2440. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2441. if (strcmp(buf, buf2) != 0) {
  2442. wbuf[0] = L'\0';
  2443. }
  2444. /* TODO: Add a configuration to switch between case sensitive and
  2445. * case insensitive URIs for Windows server. */
  2446. /*
  2447. if (conn) {
  2448. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2449. fcompare = wcscmp;
  2450. }
  2451. }
  2452. */
  2453. (void)conn; /* conn is currently unused */
  2454. /* Only accept a full file path, not a Windows short (8.3) path. */
  2455. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2456. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2457. if (long_len == 0) {
  2458. err = GetLastError();
  2459. if (err == ERROR_FILE_NOT_FOUND) {
  2460. /* File does not exist. This is not always a problem here. */
  2461. return;
  2462. }
  2463. }
  2464. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2465. /* Short name is used. */
  2466. wbuf[0] = L'\0';
  2467. }
  2468. }
  2469. #if defined(_WIN32_WCE)
  2470. /* Create substitutes for POSIX functions in Win32. */
  2471. #if defined(__MINGW32__)
  2472. /* Show no warning in case system functions are not used. */
  2473. #pragma GCC diagnostic push
  2474. #pragma GCC diagnostic ignored "-Wunused-function"
  2475. #endif
  2476. static time_t
  2477. time(time_t *ptime)
  2478. {
  2479. time_t t;
  2480. SYSTEMTIME st;
  2481. FILETIME ft;
  2482. GetSystemTime(&st);
  2483. SystemTimeToFileTime(&st, &ft);
  2484. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2485. if (ptime != NULL) {
  2486. *ptime = t;
  2487. }
  2488. return t;
  2489. }
  2490. static struct tm *
  2491. localtime(const time_t *ptime, struct tm *ptm)
  2492. {
  2493. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2494. FILETIME ft, lft;
  2495. SYSTEMTIME st;
  2496. TIME_ZONE_INFORMATION tzinfo;
  2497. if (ptm == NULL) {
  2498. return NULL;
  2499. }
  2500. *(int64_t *)&ft = t;
  2501. FileTimeToLocalFileTime(&ft, &lft);
  2502. FileTimeToSystemTime(&lft, &st);
  2503. ptm->tm_year = st.wYear - 1900;
  2504. ptm->tm_mon = st.wMonth - 1;
  2505. ptm->tm_wday = st.wDayOfWeek;
  2506. ptm->tm_mday = st.wDay;
  2507. ptm->tm_hour = st.wHour;
  2508. ptm->tm_min = st.wMinute;
  2509. ptm->tm_sec = st.wSecond;
  2510. ptm->tm_yday = 0; /* hope nobody uses this */
  2511. ptm->tm_isdst =
  2512. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2513. return ptm;
  2514. }
  2515. static struct tm *
  2516. gmtime(const time_t *ptime, struct tm *ptm)
  2517. {
  2518. /* FIXME(lsm): fix this. */
  2519. return localtime(ptime, ptm);
  2520. }
  2521. static size_t
  2522. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2523. {
  2524. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2525. return 0;
  2526. }
  2527. #if defined(__MINGW32__)
  2528. /* Enable unused function warning again */
  2529. #pragma GCC diagnostic pop
  2530. #endif
  2531. #endif
  2532. /* Windows happily opens files with some garbage at the end of file name.
  2533. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2534. * "a.cgi", despite one would expect an error back.
  2535. * This function returns non-0 if path ends with some garbage. */
  2536. static int
  2537. path_cannot_disclose_cgi(const char *path)
  2538. {
  2539. static const char *allowed_last_characters = "_-";
  2540. int last = path[strlen(path) - 1];
  2541. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2542. }
  2543. static int
  2544. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2545. {
  2546. wchar_t wbuf[PATH_MAX];
  2547. WIN32_FILE_ATTRIBUTE_DATA info;
  2548. time_t creation_time;
  2549. if (!filep) {
  2550. return 0;
  2551. }
  2552. memset(filep, 0, sizeof(*filep));
  2553. if (conn && is_file_in_memory(conn, path, filep)) {
  2554. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2555. * memset */
  2556. filep->last_modified = time(NULL);
  2557. /* last_modified = now ... assumes the file may change during runtime,
  2558. * so every mg_fopen call may return different data */
  2559. /* last_modified = conn->ctx.start_time;
  2560. * May be used it the data does not change during runtime. This allows
  2561. * browser caching. Since we do not know, we have to assume the file
  2562. * in memory may change. */
  2563. return 1;
  2564. }
  2565. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2566. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2567. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2568. filep->last_modified =
  2569. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2570. info.ftLastWriteTime.dwHighDateTime);
  2571. /* On Windows, the file creation time can be higher than the
  2572. * modification time, e.g. when a file is copied.
  2573. * Since the Last-Modified timestamp is used for caching
  2574. * it should be based on the most recent timestamp. */
  2575. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2576. info.ftCreationTime.dwHighDateTime);
  2577. if (creation_time > filep->last_modified) {
  2578. filep->last_modified = creation_time;
  2579. }
  2580. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2581. /* If file name is fishy, reset the file structure and return
  2582. * error.
  2583. * Note it is important to reset, not just return the error, cause
  2584. * functions like is_file_opened() check the struct. */
  2585. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2586. memset(filep, 0, sizeof(*filep));
  2587. return 0;
  2588. }
  2589. return 1;
  2590. }
  2591. return 0;
  2592. }
  2593. static int
  2594. mg_remove(const struct mg_connection *conn, const char *path)
  2595. {
  2596. wchar_t wbuf[PATH_MAX];
  2597. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2598. return DeleteFileW(wbuf) ? 0 : -1;
  2599. }
  2600. static int
  2601. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2602. {
  2603. wchar_t wbuf[PATH_MAX];
  2604. (void)mode;
  2605. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2606. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2607. }
  2608. /* Create substitutes for POSIX functions in Win32. */
  2609. #if defined(__MINGW32__)
  2610. /* Show no warning in case system functions are not used. */
  2611. #pragma GCC diagnostic push
  2612. #pragma GCC diagnostic ignored "-Wunused-function"
  2613. #endif
  2614. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2615. static DIR *
  2616. mg_opendir(const struct mg_connection *conn, const char *name)
  2617. {
  2618. DIR *dir = NULL;
  2619. wchar_t wpath[PATH_MAX];
  2620. DWORD attrs;
  2621. if (name == NULL) {
  2622. SetLastError(ERROR_BAD_ARGUMENTS);
  2623. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2624. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2625. } else {
  2626. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2627. attrs = GetFileAttributesW(wpath);
  2628. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2629. == FILE_ATTRIBUTE_DIRECTORY)) {
  2630. (void)wcscat(wpath, L"\\*");
  2631. dir->handle = FindFirstFileW(wpath, &dir->info);
  2632. dir->result.d_name[0] = '\0';
  2633. } else {
  2634. mg_free(dir);
  2635. dir = NULL;
  2636. }
  2637. }
  2638. return dir;
  2639. }
  2640. static int
  2641. mg_closedir(DIR *dir)
  2642. {
  2643. int result = 0;
  2644. if (dir != NULL) {
  2645. if (dir->handle != INVALID_HANDLE_VALUE)
  2646. result = FindClose(dir->handle) ? 0 : -1;
  2647. mg_free(dir);
  2648. } else {
  2649. result = -1;
  2650. SetLastError(ERROR_BAD_ARGUMENTS);
  2651. }
  2652. return result;
  2653. }
  2654. static struct dirent *
  2655. mg_readdir(DIR *dir)
  2656. {
  2657. struct dirent *result = 0;
  2658. if (dir) {
  2659. if (dir->handle != INVALID_HANDLE_VALUE) {
  2660. result = &dir->result;
  2661. (void)WideCharToMultiByte(CP_UTF8,
  2662. 0,
  2663. dir->info.cFileName,
  2664. -1,
  2665. result->d_name,
  2666. sizeof(result->d_name),
  2667. NULL,
  2668. NULL);
  2669. if (!FindNextFileW(dir->handle, &dir->info)) {
  2670. (void)FindClose(dir->handle);
  2671. dir->handle = INVALID_HANDLE_VALUE;
  2672. }
  2673. } else {
  2674. SetLastError(ERROR_FILE_NOT_FOUND);
  2675. }
  2676. } else {
  2677. SetLastError(ERROR_BAD_ARGUMENTS);
  2678. }
  2679. return result;
  2680. }
  2681. #ifndef HAVE_POLL
  2682. static int
  2683. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2684. {
  2685. struct timeval tv;
  2686. fd_set set;
  2687. unsigned int i;
  2688. int result;
  2689. SOCKET maxfd = 0;
  2690. memset(&tv, 0, sizeof(tv));
  2691. tv.tv_sec = milliseconds / 1000;
  2692. tv.tv_usec = (milliseconds % 1000) * 1000;
  2693. FD_ZERO(&set);
  2694. for (i = 0; i < n; i++) {
  2695. FD_SET((SOCKET)pfd[i].fd, &set);
  2696. pfd[i].revents = 0;
  2697. if (pfd[i].fd > maxfd) {
  2698. maxfd = pfd[i].fd;
  2699. }
  2700. }
  2701. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2702. for (i = 0; i < n; i++) {
  2703. if (FD_ISSET(pfd[i].fd, &set)) {
  2704. pfd[i].revents = POLLIN;
  2705. }
  2706. }
  2707. }
  2708. return result;
  2709. }
  2710. #endif /* HAVE_POLL */
  2711. #if defined(__MINGW32__)
  2712. /* Enable unused function warning again */
  2713. #pragma GCC diagnostic pop
  2714. #endif
  2715. static void
  2716. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2717. {
  2718. (void)conn; /* Unused. */
  2719. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2720. }
  2721. int
  2722. mg_start_thread(mg_thread_func_t f, void *p)
  2723. {
  2724. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2725. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2726. */
  2727. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2728. == ((uintptr_t)(-1L)))
  2729. ? -1
  2730. : 0);
  2731. #else
  2732. return (
  2733. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2734. ? -1
  2735. : 0);
  2736. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2737. }
  2738. /* Start a thread storing the thread context. */
  2739. static int
  2740. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2741. void *p,
  2742. pthread_t *threadidptr)
  2743. {
  2744. uintptr_t uip;
  2745. HANDLE threadhandle;
  2746. int result = -1;
  2747. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2748. threadhandle = (HANDLE)uip;
  2749. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2750. *threadidptr = threadhandle;
  2751. result = 0;
  2752. }
  2753. return result;
  2754. }
  2755. /* Wait for a thread to finish. */
  2756. static int
  2757. mg_join_thread(pthread_t threadid)
  2758. {
  2759. int result;
  2760. DWORD dwevent;
  2761. result = -1;
  2762. dwevent = WaitForSingleObject(threadid, INFINITE);
  2763. if (dwevent == WAIT_FAILED) {
  2764. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2765. } else {
  2766. if (dwevent == WAIT_OBJECT_0) {
  2767. CloseHandle(threadid);
  2768. result = 0;
  2769. }
  2770. }
  2771. return result;
  2772. }
  2773. #if !defined(NO_SSL_DL)
  2774. /* Create substitutes for POSIX functions in Win32. */
  2775. #if defined(__MINGW32__)
  2776. /* Show no warning in case system functions are not used. */
  2777. #pragma GCC diagnostic push
  2778. #pragma GCC diagnostic ignored "-Wunused-function"
  2779. #endif
  2780. static HANDLE
  2781. dlopen(const char *dll_name, int flags)
  2782. {
  2783. wchar_t wbuf[PATH_MAX];
  2784. (void)flags;
  2785. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2786. return LoadLibraryW(wbuf);
  2787. }
  2788. static int
  2789. dlclose(void *handle)
  2790. {
  2791. int result;
  2792. if (FreeLibrary((HMODULE)handle) != 0) {
  2793. result = 0;
  2794. } else {
  2795. result = -1;
  2796. }
  2797. return result;
  2798. }
  2799. #if defined(__MINGW32__)
  2800. /* Enable unused function warning again */
  2801. #pragma GCC diagnostic pop
  2802. #endif
  2803. #endif
  2804. #if !defined(NO_CGI)
  2805. #define SIGKILL (0)
  2806. static int
  2807. kill(pid_t pid, int sig_num)
  2808. {
  2809. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2810. (void)CloseHandle((HANDLE)pid);
  2811. return 0;
  2812. }
  2813. static void
  2814. trim_trailing_whitespaces(char *s)
  2815. {
  2816. char *e = s + strlen(s) - 1;
  2817. while (e > s && isspace(*(unsigned char *)e)) {
  2818. *e-- = '\0';
  2819. }
  2820. }
  2821. static pid_t
  2822. spawn_process(struct mg_connection *conn,
  2823. const char *prog,
  2824. char *envblk,
  2825. char *envp[],
  2826. int fdin[2],
  2827. int fdout[2],
  2828. int fderr[2],
  2829. const char *dir)
  2830. {
  2831. HANDLE me;
  2832. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2833. cmdline[PATH_MAX], buf[PATH_MAX];
  2834. int truncated;
  2835. struct file file = STRUCT_FILE_INITIALIZER;
  2836. STARTUPINFOA si;
  2837. PROCESS_INFORMATION pi = {0};
  2838. (void)envp;
  2839. memset(&si, 0, sizeof(si));
  2840. si.cb = sizeof(si);
  2841. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2842. si.wShowWindow = SW_HIDE;
  2843. me = GetCurrentProcess();
  2844. DuplicateHandle(me,
  2845. (HANDLE)_get_osfhandle(fdin[0]),
  2846. me,
  2847. &si.hStdInput,
  2848. 0,
  2849. TRUE,
  2850. DUPLICATE_SAME_ACCESS);
  2851. DuplicateHandle(me,
  2852. (HANDLE)_get_osfhandle(fdout[1]),
  2853. me,
  2854. &si.hStdOutput,
  2855. 0,
  2856. TRUE,
  2857. DUPLICATE_SAME_ACCESS);
  2858. DuplicateHandle(me,
  2859. (HANDLE)_get_osfhandle(fderr[1]),
  2860. me,
  2861. &si.hStdError,
  2862. 0,
  2863. TRUE,
  2864. DUPLICATE_SAME_ACCESS);
  2865. /* Mark handles that should not be inherited. See
  2866. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  2867. */
  2868. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  2869. HANDLE_FLAG_INHERIT,
  2870. 0);
  2871. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  2872. HANDLE_FLAG_INHERIT,
  2873. 0);
  2874. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  2875. HANDLE_FLAG_INHERIT,
  2876. 0);
  2877. /* If CGI file is a script, try to read the interpreter line */
  2878. interp = conn->ctx->config[CGI_INTERPRETER];
  2879. if (interp == NULL) {
  2880. buf[0] = buf[1] = '\0';
  2881. /* Read the first line of the script into the buffer */
  2882. mg_snprintf(
  2883. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2884. if (truncated) {
  2885. pi.hProcess = (pid_t)-1;
  2886. goto spawn_cleanup;
  2887. }
  2888. if (mg_fopen(conn, cmdline, "r", &file)) {
  2889. p = (char *)file.membuf;
  2890. mg_fgets(buf, sizeof(buf), &file, &p);
  2891. mg_fclose(&file);
  2892. buf[sizeof(buf) - 1] = '\0';
  2893. }
  2894. if (buf[0] == '#' && buf[1] == '!') {
  2895. trim_trailing_whitespaces(buf + 2);
  2896. } else {
  2897. buf[2] = '\0';
  2898. }
  2899. interp = buf + 2;
  2900. }
  2901. if (interp[0] != '\0') {
  2902. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2903. interp = full_interp;
  2904. }
  2905. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2906. if (interp[0] != '\0') {
  2907. mg_snprintf(conn,
  2908. &truncated,
  2909. cmdline,
  2910. sizeof(cmdline),
  2911. "\"%s\" \"%s\\%s\"",
  2912. interp,
  2913. full_dir,
  2914. prog);
  2915. } else {
  2916. mg_snprintf(conn,
  2917. &truncated,
  2918. cmdline,
  2919. sizeof(cmdline),
  2920. "\"%s\\%s\"",
  2921. full_dir,
  2922. prog);
  2923. }
  2924. if (truncated) {
  2925. pi.hProcess = (pid_t)-1;
  2926. goto spawn_cleanup;
  2927. }
  2928. DEBUG_TRACE("Running [%s]", cmdline);
  2929. if (CreateProcessA(NULL,
  2930. cmdline,
  2931. NULL,
  2932. NULL,
  2933. TRUE,
  2934. CREATE_NEW_PROCESS_GROUP,
  2935. envblk,
  2936. NULL,
  2937. &si,
  2938. &pi) == 0) {
  2939. mg_cry(
  2940. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2941. pi.hProcess = (pid_t)-1;
  2942. /* goto spawn_cleanup; */
  2943. }
  2944. spawn_cleanup:
  2945. (void)CloseHandle(si.hStdOutput);
  2946. (void)CloseHandle(si.hStdError);
  2947. (void)CloseHandle(si.hStdInput);
  2948. if (pi.hThread != NULL) {
  2949. (void)CloseHandle(pi.hThread);
  2950. }
  2951. return (pid_t)pi.hProcess;
  2952. }
  2953. #endif /* !NO_CGI */
  2954. static int
  2955. set_non_blocking_mode(SOCKET sock)
  2956. {
  2957. unsigned long on = 1;
  2958. return ioctlsocket(sock, (long)FIONBIO, &on);
  2959. }
  2960. #else
  2961. static int
  2962. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2963. {
  2964. struct stat st;
  2965. if (!filep) {
  2966. return 0;
  2967. }
  2968. memset(filep, 0, sizeof(*filep));
  2969. if (conn && is_file_in_memory(conn, path, filep)) {
  2970. return 1;
  2971. }
  2972. if (0 == stat(path, &st)) {
  2973. filep->size = (uint64_t)(st.st_size);
  2974. filep->last_modified = st.st_mtime;
  2975. filep->is_directory = S_ISDIR(st.st_mode);
  2976. return 1;
  2977. }
  2978. return 0;
  2979. }
  2980. static void
  2981. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2982. {
  2983. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2984. if (conn) {
  2985. mg_cry(conn,
  2986. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2987. __func__,
  2988. strerror(ERRNO));
  2989. }
  2990. }
  2991. }
  2992. int
  2993. mg_start_thread(mg_thread_func_t func, void *param)
  2994. {
  2995. pthread_t thread_id;
  2996. pthread_attr_t attr;
  2997. int result;
  2998. (void)pthread_attr_init(&attr);
  2999. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3000. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3001. /* Compile-time option to control stack size,
  3002. * e.g. -DUSE_STACK_SIZE=16384 */
  3003. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3004. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3005. result = pthread_create(&thread_id, &attr, func, param);
  3006. pthread_attr_destroy(&attr);
  3007. return result;
  3008. }
  3009. /* Start a thread storing the thread context. */
  3010. static int
  3011. mg_start_thread_with_id(mg_thread_func_t func,
  3012. void *param,
  3013. pthread_t *threadidptr)
  3014. {
  3015. pthread_t thread_id;
  3016. pthread_attr_t attr;
  3017. int result;
  3018. (void)pthread_attr_init(&attr);
  3019. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3020. /* Compile-time option to control stack size,
  3021. * e.g. -DUSE_STACK_SIZE=16384 */
  3022. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3023. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3024. result = pthread_create(&thread_id, &attr, func, param);
  3025. pthread_attr_destroy(&attr);
  3026. if ((result == 0) && (threadidptr != NULL)) {
  3027. *threadidptr = thread_id;
  3028. }
  3029. return result;
  3030. }
  3031. /* Wait for a thread to finish. */
  3032. static int
  3033. mg_join_thread(pthread_t threadid)
  3034. {
  3035. int result;
  3036. result = pthread_join(threadid, NULL);
  3037. return result;
  3038. }
  3039. #ifndef NO_CGI
  3040. static pid_t
  3041. spawn_process(struct mg_connection *conn,
  3042. const char *prog,
  3043. char *envblk,
  3044. char *envp[],
  3045. int fdin[2],
  3046. int fdout[2],
  3047. int fderr[2],
  3048. const char *dir)
  3049. {
  3050. pid_t pid;
  3051. const char *interp;
  3052. (void)envblk;
  3053. if (conn == NULL) {
  3054. return 0;
  3055. }
  3056. if ((pid = fork()) == -1) {
  3057. /* Parent */
  3058. send_http_error(conn,
  3059. 500,
  3060. "Error: Creating CGI process\nfork(): %s",
  3061. strerror(ERRNO));
  3062. } else if (pid == 0) {
  3063. /* Child */
  3064. if (chdir(dir) != 0) {
  3065. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3066. } else if (dup2(fdin[0], 0) == -1) {
  3067. mg_cry(conn,
  3068. "%s: dup2(%d, 0): %s",
  3069. __func__,
  3070. fdin[0],
  3071. strerror(ERRNO));
  3072. } else if (dup2(fdout[1], 1) == -1) {
  3073. mg_cry(conn,
  3074. "%s: dup2(%d, 1): %s",
  3075. __func__,
  3076. fdout[1],
  3077. strerror(ERRNO));
  3078. } else if (dup2(fderr[1], 2) == -1) {
  3079. mg_cry(conn,
  3080. "%s: dup2(%d, 2): %s",
  3081. __func__,
  3082. fderr[1],
  3083. strerror(ERRNO));
  3084. } else {
  3085. /* Keep stderr and stdout in two different pipes.
  3086. * Stdout will be sent back to the client,
  3087. * stderr should go into a server error log. */
  3088. (void)close(fdin[0]);
  3089. (void)close(fdout[1]);
  3090. (void)close(fderr[1]);
  3091. /* Close write end fdin and read end fdout and fderr */
  3092. (void)close(fdin[1]);
  3093. (void)close(fdout[0]);
  3094. (void)close(fderr[0]);
  3095. /* After exec, all signal handlers are restored to their default
  3096. * values, with one exception of SIGCHLD. According to
  3097. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3098. * leave unchanged after exec if it was set to be ignored. Restore
  3099. * it to default action. */
  3100. signal(SIGCHLD, SIG_DFL);
  3101. interp = conn->ctx->config[CGI_INTERPRETER];
  3102. if (interp == NULL) {
  3103. (void)execle(prog, prog, NULL, envp);
  3104. mg_cry(conn,
  3105. "%s: execle(%s): %s",
  3106. __func__,
  3107. prog,
  3108. strerror(ERRNO));
  3109. } else {
  3110. (void)execle(interp, interp, prog, NULL, envp);
  3111. mg_cry(conn,
  3112. "%s: execle(%s %s): %s",
  3113. __func__,
  3114. interp,
  3115. prog,
  3116. strerror(ERRNO));
  3117. }
  3118. }
  3119. exit(EXIT_FAILURE);
  3120. }
  3121. return pid;
  3122. }
  3123. #endif /* !NO_CGI */
  3124. static int
  3125. set_non_blocking_mode(SOCKET sock)
  3126. {
  3127. int flags;
  3128. flags = fcntl(sock, F_GETFL, 0);
  3129. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3130. return 0;
  3131. }
  3132. #endif /* _WIN32 */
  3133. /* End of initial operating system specific define block. */
  3134. /* Get a random number (independent of C rand function) */
  3135. static uint64_t
  3136. get_random(void)
  3137. {
  3138. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3139. static uint64_t lcg = 0; /* Linear congruential generator */
  3140. struct timespec now;
  3141. memset(&now, 0, sizeof(now));
  3142. clock_gettime(CLOCK_MONOTONIC, &now);
  3143. if (lfsr == 0) {
  3144. /* lfsr will be only 0 if has not been initialized,
  3145. * so this code is called only once. */
  3146. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3147. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3148. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3149. + (uint64_t)(ptrdiff_t)&now;
  3150. } else {
  3151. /* Get the next step of both random number generators. */
  3152. lfsr = (lfsr >> 1)
  3153. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3154. << 63);
  3155. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3156. }
  3157. /* Combining two pseudo-random number generators and a high resolution part
  3158. * of the current server time will make it hard (impossible?) to guess the
  3159. * next number. */
  3160. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3161. }
  3162. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3163. * descriptor. Return number of bytes written. */
  3164. static int
  3165. push(struct mg_context *ctx,
  3166. FILE *fp,
  3167. SOCKET sock,
  3168. SSL *ssl,
  3169. const char *buf,
  3170. int len,
  3171. double timeout)
  3172. {
  3173. struct timespec start, now;
  3174. int n, err;
  3175. #ifdef _WIN32
  3176. typedef int len_t;
  3177. #else
  3178. typedef size_t len_t;
  3179. #endif
  3180. if (timeout > 0) {
  3181. memset(&start, 0, sizeof(start));
  3182. memset(&now, 0, sizeof(now));
  3183. clock_gettime(CLOCK_MONOTONIC, &start);
  3184. }
  3185. if (ctx == NULL) {
  3186. return -1;
  3187. }
  3188. #ifdef NO_SSL
  3189. if (ssl) {
  3190. return -1;
  3191. }
  3192. #endif
  3193. do {
  3194. #ifndef NO_SSL
  3195. if (ssl != NULL) {
  3196. n = SSL_write(ssl, buf, len);
  3197. if (n <= 0) {
  3198. err = SSL_get_error(ssl, n);
  3199. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3200. err = ERRNO;
  3201. } else {
  3202. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3203. return -1;
  3204. }
  3205. } else {
  3206. err = 0;
  3207. }
  3208. } else
  3209. #endif
  3210. if (fp != NULL) {
  3211. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3212. if (ferror(fp)) {
  3213. n = -1;
  3214. err = ERRNO;
  3215. } else {
  3216. err = 0;
  3217. }
  3218. } else {
  3219. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3220. err = (n < 0) ? ERRNO : 0;
  3221. }
  3222. if (ctx->stop_flag) {
  3223. return -1;
  3224. }
  3225. if ((n > 0) || (n == 0 && len == 0)) {
  3226. /* some data has been read, or no data was requested */
  3227. return n;
  3228. }
  3229. if (n == 0) {
  3230. /* shutdown of the socket at client side */
  3231. return -1;
  3232. }
  3233. if (n < 0) {
  3234. /* socket error - check errno */
  3235. DEBUG_TRACE("send() failed, error %d", err);
  3236. /* TODO: error handling depending on the error code.
  3237. * These codes are different between Windows and Linux.
  3238. */
  3239. return -1;
  3240. }
  3241. /* This code is not reached in the moment.
  3242. * ==> Fix the TODOs above first. */
  3243. if (timeout > 0) {
  3244. clock_gettime(CLOCK_MONOTONIC, &now);
  3245. }
  3246. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3247. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3248. used */
  3249. return -1;
  3250. }
  3251. static int64_t
  3252. push_all(struct mg_context *ctx,
  3253. FILE *fp,
  3254. SOCKET sock,
  3255. SSL *ssl,
  3256. const char *buf,
  3257. int64_t len)
  3258. {
  3259. double timeout = -1.0;
  3260. int64_t n, nwritten = 0;
  3261. if (ctx == NULL) {
  3262. return -1;
  3263. }
  3264. if (ctx->config[REQUEST_TIMEOUT]) {
  3265. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3266. }
  3267. while (len > 0 && ctx->stop_flag == 0) {
  3268. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3269. if (n < 0) {
  3270. if (nwritten == 0) {
  3271. nwritten = n; /* Propagate the error */
  3272. }
  3273. break;
  3274. } else if (n == 0) {
  3275. break; /* No more data to write */
  3276. } else {
  3277. nwritten += n;
  3278. len -= n;
  3279. }
  3280. }
  3281. return nwritten;
  3282. }
  3283. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3284. * Return negative value on error, or number of bytes read on success. */
  3285. static int
  3286. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3287. {
  3288. int nread, err;
  3289. struct timespec start, now;
  3290. #ifdef _WIN32
  3291. typedef int len_t;
  3292. #else
  3293. typedef size_t len_t;
  3294. #endif
  3295. if (timeout > 0) {
  3296. memset(&start, 0, sizeof(start));
  3297. memset(&now, 0, sizeof(now));
  3298. clock_gettime(CLOCK_MONOTONIC, &start);
  3299. }
  3300. do {
  3301. if (fp != NULL) {
  3302. /* Use read() instead of fread(), because if we're reading from the
  3303. * CGI pipe, fread() may block until IO buffer is filled up. We
  3304. * cannot afford to block and must pass all read bytes immediately
  3305. * to the client. */
  3306. nread = (int)read(fileno(fp), buf, (size_t)len);
  3307. err = (nread < 0) ? ERRNO : 0;
  3308. #ifndef NO_SSL
  3309. } else if (conn->ssl != NULL) {
  3310. nread = SSL_read(conn->ssl, buf, len);
  3311. if (nread <= 0) {
  3312. err = SSL_get_error(conn->ssl, nread);
  3313. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3314. err = ERRNO;
  3315. } else {
  3316. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3317. return -1;
  3318. }
  3319. } else {
  3320. err = 0;
  3321. }
  3322. #endif
  3323. } else {
  3324. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3325. err = (nread < 0) ? ERRNO : 0;
  3326. }
  3327. if (conn->ctx->stop_flag) {
  3328. return -1;
  3329. }
  3330. if ((nread > 0) || (nread == 0 && len == 0)) {
  3331. /* some data has been read, or no data was requested */
  3332. return nread;
  3333. }
  3334. if (nread == 0) {
  3335. /* shutdown of the socket at client side */
  3336. return -1;
  3337. }
  3338. if (nread < 0) {
  3339. /* socket error - check errno */
  3340. #ifdef _WIN32
  3341. if (err == WSAEWOULDBLOCK) {
  3342. /* standard case if called from close_socket_gracefully */
  3343. return -1;
  3344. } else if (err == WSAETIMEDOUT) {
  3345. /* timeout is handled by the while loop */
  3346. } else {
  3347. DEBUG_TRACE("recv() failed, error %d", err);
  3348. return -1;
  3349. }
  3350. #else
  3351. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3352. * if the timeout is reached and if the socket was set to non-
  3353. * blocking in close_socket_gracefully, so we can not distinguish
  3354. * here. We have to wait for the timeout in both cases for now.
  3355. */
  3356. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3357. /* EAGAIN/EWOULDBLOCK:
  3358. * standard case if called from close_socket_gracefully
  3359. * => should return -1 */
  3360. /* or timeout occured
  3361. * => the code must stay in the while loop */
  3362. /* EINTR can be generated on a socket with a timeout set even
  3363. * when SA_RESTART is effective for all relevant signals
  3364. * (see signal(7)).
  3365. * => stay in the while loop */
  3366. } else {
  3367. DEBUG_TRACE("recv() failed, error %d", err);
  3368. return -1;
  3369. }
  3370. #endif
  3371. }
  3372. if (timeout > 0) {
  3373. clock_gettime(CLOCK_MONOTONIC, &now);
  3374. }
  3375. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3376. /* Timeout occured, but no data available. */
  3377. return -1;
  3378. }
  3379. static int
  3380. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3381. {
  3382. int n, nread = 0;
  3383. double timeout = -1.0;
  3384. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3385. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3386. }
  3387. while (len > 0 && conn->ctx->stop_flag == 0) {
  3388. n = pull(fp, conn, buf + nread, len, timeout);
  3389. if (n < 0) {
  3390. if (nread == 0) {
  3391. nread = n; /* Propagate the error */
  3392. }
  3393. break;
  3394. } else if (n == 0) {
  3395. break; /* No more data to read */
  3396. } else {
  3397. conn->consumed_content += n;
  3398. nread += n;
  3399. len -= n;
  3400. }
  3401. }
  3402. return nread;
  3403. }
  3404. static void
  3405. discard_unread_request_data(struct mg_connection *conn)
  3406. {
  3407. char buf[MG_BUF_LEN];
  3408. size_t to_read;
  3409. int nread;
  3410. if (conn == NULL) {
  3411. return;
  3412. }
  3413. to_read = sizeof(buf);
  3414. if (conn->is_chunked) {
  3415. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3416. * completely */
  3417. while (conn->is_chunked == 1) {
  3418. nread = mg_read(conn, buf, to_read);
  3419. if (nread <= 0) {
  3420. break;
  3421. }
  3422. }
  3423. } else {
  3424. /* Not chunked: content length is known */
  3425. while (conn->consumed_content < conn->content_len) {
  3426. if (to_read
  3427. > (size_t)(conn->content_len - conn->consumed_content)) {
  3428. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3429. }
  3430. nread = mg_read(conn, buf, to_read);
  3431. if (nread <= 0) {
  3432. break;
  3433. }
  3434. }
  3435. }
  3436. }
  3437. static int
  3438. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3439. {
  3440. int64_t n, buffered_len, nread;
  3441. int64_t len64 =
  3442. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3443. * int, we may not read more
  3444. * bytes */
  3445. const char *body;
  3446. if (conn == NULL) {
  3447. return 0;
  3448. }
  3449. /* If Content-Length is not set for a PUT or POST request, read until
  3450. * socket is closed */
  3451. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3452. conn->content_len = INT64_MAX;
  3453. conn->must_close = 1;
  3454. }
  3455. nread = 0;
  3456. if (conn->consumed_content < conn->content_len) {
  3457. /* Adjust number of bytes to read. */
  3458. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3459. if (left_to_read < len64) {
  3460. /* Do not read more than the total content length of the request.
  3461. */
  3462. len64 = left_to_read;
  3463. }
  3464. /* Return buffered data */
  3465. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3466. - conn->consumed_content;
  3467. if (buffered_len > 0) {
  3468. if (len64 < buffered_len) {
  3469. buffered_len = len64;
  3470. }
  3471. body = conn->buf + conn->request_len + conn->consumed_content;
  3472. memcpy(buf, body, (size_t)buffered_len);
  3473. len64 -= buffered_len;
  3474. conn->consumed_content += buffered_len;
  3475. nread += buffered_len;
  3476. buf = (char *)buf + buffered_len;
  3477. }
  3478. /* We have returned all buffered data. Read new data from the remote
  3479. * socket.
  3480. */
  3481. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3482. nread += n;
  3483. } else {
  3484. nread = (nread > 0 ? nread : n);
  3485. }
  3486. }
  3487. return (int)nread;
  3488. }
  3489. static char
  3490. mg_getc(struct mg_connection *conn)
  3491. {
  3492. char c;
  3493. if (conn == NULL) {
  3494. return 0;
  3495. }
  3496. conn->content_len++;
  3497. if (mg_read_inner(conn, &c, 1) <= 0) {
  3498. return (char)0;
  3499. }
  3500. return c;
  3501. }
  3502. int
  3503. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3504. {
  3505. if (len > INT_MAX) {
  3506. len = INT_MAX;
  3507. }
  3508. if (conn == NULL) {
  3509. return 0;
  3510. }
  3511. if (conn->is_chunked) {
  3512. size_t all_read = 0;
  3513. while (len > 0) {
  3514. if (conn->chunk_remainder) {
  3515. /* copy from the remainder of the last received chunk */
  3516. long read_ret;
  3517. size_t read_now =
  3518. ((conn->chunk_remainder > len) ? (len)
  3519. : (conn->chunk_remainder));
  3520. conn->content_len += (int)read_now;
  3521. read_ret =
  3522. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3523. all_read += (size_t)read_ret;
  3524. conn->chunk_remainder -= read_now;
  3525. len -= read_now;
  3526. if (conn->chunk_remainder == 0) {
  3527. /* the rest of the data in the current chunk has been read
  3528. */
  3529. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3530. /* Protocol violation */
  3531. return -1;
  3532. }
  3533. }
  3534. } else {
  3535. /* fetch a new chunk */
  3536. int i = 0;
  3537. char lenbuf[64];
  3538. char *end = 0;
  3539. unsigned long chunkSize = 0;
  3540. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3541. lenbuf[i] = mg_getc(conn);
  3542. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3543. continue;
  3544. }
  3545. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3546. lenbuf[i + 1] = 0;
  3547. chunkSize = strtoul(lenbuf, &end, 16);
  3548. break;
  3549. }
  3550. if (!isalnum(lenbuf[i])) {
  3551. /* illegal character for chunk length */
  3552. return -1;
  3553. }
  3554. }
  3555. if ((end == NULL) || (*end != '\r')) {
  3556. /* chunksize not set correctly */
  3557. return -1;
  3558. }
  3559. conn->chunk_remainder = chunkSize;
  3560. if (chunkSize == 0) {
  3561. /* regular end of content */
  3562. conn->is_chunked = 2;
  3563. break;
  3564. }
  3565. }
  3566. }
  3567. return (int)all_read;
  3568. }
  3569. return mg_read_inner(conn, buf, len);
  3570. }
  3571. int
  3572. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3573. {
  3574. time_t now;
  3575. int64_t n, total, allowed;
  3576. if (conn == NULL) {
  3577. return 0;
  3578. }
  3579. if (conn->throttle > 0) {
  3580. if ((now = time(NULL)) != conn->last_throttle_time) {
  3581. conn->last_throttle_time = now;
  3582. conn->last_throttle_bytes = 0;
  3583. }
  3584. allowed = conn->throttle - conn->last_throttle_bytes;
  3585. if (allowed > (int64_t)len) {
  3586. allowed = (int64_t)len;
  3587. }
  3588. if ((total = push_all(conn->ctx,
  3589. NULL,
  3590. conn->client.sock,
  3591. conn->ssl,
  3592. (const char *)buf,
  3593. (int64_t)allowed)) == allowed) {
  3594. buf = (const char *)buf + total;
  3595. conn->last_throttle_bytes += total;
  3596. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3597. allowed = conn->throttle > (int64_t)len - total
  3598. ? (int64_t)len - total
  3599. : conn->throttle;
  3600. if ((n = push_all(conn->ctx,
  3601. NULL,
  3602. conn->client.sock,
  3603. conn->ssl,
  3604. (const char *)buf,
  3605. (int64_t)allowed)) != allowed) {
  3606. break;
  3607. }
  3608. sleep(1);
  3609. conn->last_throttle_bytes = allowed;
  3610. conn->last_throttle_time = time(NULL);
  3611. buf = (const char *)buf + n;
  3612. total += n;
  3613. }
  3614. }
  3615. } else {
  3616. total = push_all(conn->ctx,
  3617. NULL,
  3618. conn->client.sock,
  3619. conn->ssl,
  3620. (const char *)buf,
  3621. (int64_t)len);
  3622. }
  3623. return (int)total;
  3624. }
  3625. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3626. static int
  3627. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3628. {
  3629. va_list ap_copy;
  3630. size_t size = MG_BUF_LEN / 4;
  3631. int len = -1;
  3632. *buf = NULL;
  3633. while (len < 0) {
  3634. if (*buf) {
  3635. mg_free(*buf);
  3636. }
  3637. size *= 4;
  3638. *buf = (char *)mg_malloc(size);
  3639. if (!*buf) {
  3640. break;
  3641. }
  3642. va_copy(ap_copy, ap);
  3643. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3644. va_end(ap_copy);
  3645. (*buf)[size - 1] = 0;
  3646. }
  3647. return len;
  3648. }
  3649. /* Print message to buffer. If buffer is large enough to hold the message,
  3650. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3651. * and return allocated buffer. */
  3652. static int
  3653. alloc_vprintf(char **out_buf,
  3654. char *prealloc_buf,
  3655. size_t prealloc_size,
  3656. const char *fmt,
  3657. va_list ap)
  3658. {
  3659. va_list ap_copy;
  3660. int len;
  3661. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3662. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3663. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3664. * Therefore, we make two passes: on first pass, get required message
  3665. * length.
  3666. * On second pass, actually print the message. */
  3667. va_copy(ap_copy, ap);
  3668. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3669. va_end(ap_copy);
  3670. if (len < 0) {
  3671. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3672. * Switch to alternative code path that uses incremental allocations.
  3673. */
  3674. va_copy(ap_copy, ap);
  3675. len = alloc_vprintf2(out_buf, fmt, ap);
  3676. va_end(ap_copy);
  3677. } else if ((size_t)(len) >= prealloc_size) {
  3678. /* The pre-allocated buffer not large enough. */
  3679. /* Allocate a new buffer. */
  3680. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3681. if (!*out_buf) {
  3682. /* Allocation failed. Return -1 as "out of memory" error. */
  3683. return -1;
  3684. }
  3685. /* Buffer allocation successful. Store the string there. */
  3686. va_copy(ap_copy, ap);
  3687. IGNORE_UNUSED_RESULT(
  3688. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3689. va_end(ap_copy);
  3690. } else {
  3691. /* The pre-allocated buffer is large enough.
  3692. * Use it to store the string and return the address. */
  3693. va_copy(ap_copy, ap);
  3694. IGNORE_UNUSED_RESULT(
  3695. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3696. va_end(ap_copy);
  3697. *out_buf = prealloc_buf;
  3698. }
  3699. return len;
  3700. }
  3701. static int
  3702. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3703. {
  3704. char mem[MG_BUF_LEN];
  3705. char *buf = NULL;
  3706. int len;
  3707. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3708. len = mg_write(conn, buf, (size_t)len);
  3709. }
  3710. if (buf != mem && buf != NULL) {
  3711. mg_free(buf);
  3712. }
  3713. return len;
  3714. }
  3715. int
  3716. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3717. {
  3718. va_list ap;
  3719. int result;
  3720. va_start(ap, fmt);
  3721. result = mg_vprintf(conn, fmt, ap);
  3722. va_end(ap);
  3723. return result;
  3724. }
  3725. int
  3726. mg_url_decode(const char *src,
  3727. int src_len,
  3728. char *dst,
  3729. int dst_len,
  3730. int is_form_url_encoded)
  3731. {
  3732. int i, j, a, b;
  3733. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3734. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3735. if (i < src_len - 2 && src[i] == '%'
  3736. && isxdigit(*(const unsigned char *)(src + i + 1))
  3737. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3738. a = tolower(*(const unsigned char *)(src + i + 1));
  3739. b = tolower(*(const unsigned char *)(src + i + 2));
  3740. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3741. i += 2;
  3742. } else if (is_form_url_encoded && src[i] == '+') {
  3743. dst[j] = ' ';
  3744. } else {
  3745. dst[j] = src[i];
  3746. }
  3747. }
  3748. dst[j] = '\0'; /* Null-terminate the destination */
  3749. return i >= src_len ? j : -1;
  3750. }
  3751. int
  3752. mg_get_var(const char *data,
  3753. size_t data_len,
  3754. const char *name,
  3755. char *dst,
  3756. size_t dst_len)
  3757. {
  3758. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3759. }
  3760. int
  3761. mg_get_var2(const char *data,
  3762. size_t data_len,
  3763. const char *name,
  3764. char *dst,
  3765. size_t dst_len,
  3766. size_t occurrence)
  3767. {
  3768. const char *p, *e, *s;
  3769. size_t name_len;
  3770. int len;
  3771. if (dst == NULL || dst_len == 0) {
  3772. len = -2;
  3773. } else if (data == NULL || name == NULL || data_len == 0) {
  3774. len = -1;
  3775. dst[0] = '\0';
  3776. } else {
  3777. name_len = strlen(name);
  3778. e = data + data_len;
  3779. len = -1;
  3780. dst[0] = '\0';
  3781. /* data is "var1=val1&var2=val2...". Find variable first */
  3782. for (p = data; p + name_len < e; p++) {
  3783. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3784. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3785. /* Point p to variable value */
  3786. p += name_len + 1;
  3787. /* Point s to the end of the value */
  3788. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3789. if (s == NULL) {
  3790. s = e;
  3791. }
  3792. /* assert(s >= p); */
  3793. if (s < p) {
  3794. return -3;
  3795. }
  3796. /* Decode variable into destination buffer */
  3797. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3798. /* Redirect error code from -1 to -2 (destination buffer too
  3799. * small). */
  3800. if (len == -1) {
  3801. len = -2;
  3802. }
  3803. break;
  3804. }
  3805. }
  3806. }
  3807. return len;
  3808. }
  3809. int
  3810. mg_get_cookie(const char *cookie_header,
  3811. const char *var_name,
  3812. char *dst,
  3813. size_t dst_size)
  3814. {
  3815. const char *s, *p, *end;
  3816. int name_len, len = -1;
  3817. if (dst == NULL || dst_size == 0) {
  3818. len = -2;
  3819. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3820. len = -1;
  3821. dst[0] = '\0';
  3822. } else {
  3823. name_len = (int)strlen(var_name);
  3824. end = s + strlen(s);
  3825. dst[0] = '\0';
  3826. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3827. if (s[name_len] == '=') {
  3828. s += name_len + 1;
  3829. if ((p = strchr(s, ' ')) == NULL) {
  3830. p = end;
  3831. }
  3832. if (p[-1] == ';') {
  3833. p--;
  3834. }
  3835. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3836. s++;
  3837. p--;
  3838. }
  3839. if ((size_t)(p - s) < dst_size) {
  3840. len = (int)(p - s);
  3841. mg_strlcpy(dst, s, (size_t)len + 1);
  3842. } else {
  3843. len = -3;
  3844. }
  3845. break;
  3846. }
  3847. }
  3848. }
  3849. return len;
  3850. }
  3851. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3852. static void
  3853. base64_encode(const unsigned char *src, int src_len, char *dst)
  3854. {
  3855. static const char *b64 =
  3856. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3857. int i, j, a, b, c;
  3858. for (i = j = 0; i < src_len; i += 3) {
  3859. a = src[i];
  3860. b = i + 1 >= src_len ? 0 : src[i + 1];
  3861. c = i + 2 >= src_len ? 0 : src[i + 2];
  3862. dst[j++] = b64[a >> 2];
  3863. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3864. if (i + 1 < src_len) {
  3865. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3866. }
  3867. if (i + 2 < src_len) {
  3868. dst[j++] = b64[c & 63];
  3869. }
  3870. }
  3871. while (j % 4 != 0) {
  3872. dst[j++] = '=';
  3873. }
  3874. dst[j++] = '\0';
  3875. }
  3876. #endif
  3877. #if defined(USE_LUA)
  3878. static unsigned char
  3879. b64reverse(char letter)
  3880. {
  3881. if (letter >= 'A' && letter <= 'Z') {
  3882. return letter - 'A';
  3883. }
  3884. if (letter >= 'a' && letter <= 'z') {
  3885. return letter - 'a' + 26;
  3886. }
  3887. if (letter >= '0' && letter <= '9') {
  3888. return letter - '0' + 52;
  3889. }
  3890. if (letter == '+') {
  3891. return 62;
  3892. }
  3893. if (letter == '/') {
  3894. return 63;
  3895. }
  3896. if (letter == '=') {
  3897. return 255; /* normal end */
  3898. }
  3899. return 254; /* error */
  3900. }
  3901. static int
  3902. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3903. {
  3904. int i;
  3905. unsigned char a, b, c, d;
  3906. *dst_len = 0;
  3907. for (i = 0; i < src_len; i += 4) {
  3908. a = b64reverse(src[i]);
  3909. if (a >= 254) {
  3910. return i;
  3911. }
  3912. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3913. if (b >= 254) {
  3914. return i + 1;
  3915. }
  3916. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3917. if (c == 254) {
  3918. return i + 2;
  3919. }
  3920. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3921. if (d == 254) {
  3922. return i + 3;
  3923. }
  3924. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3925. if (c != 255) {
  3926. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3927. if (d != 255) {
  3928. dst[(*dst_len)++] = (c << 6) + d;
  3929. }
  3930. }
  3931. }
  3932. return -1;
  3933. }
  3934. #endif
  3935. static int
  3936. is_put_or_delete_method(const struct mg_connection *conn)
  3937. {
  3938. if (conn) {
  3939. const char *s = conn->request_info.request_method;
  3940. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3941. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3942. }
  3943. return 0;
  3944. }
  3945. static void
  3946. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3947. char *filename, /* out: filename */
  3948. size_t filename_buf_len, /* in: size of filename buffer */
  3949. struct file *filep, /* out: file structure */
  3950. int *is_found, /* out: file is found (directly) */
  3951. int *is_script_resource, /* out: handled by a script? */
  3952. int *is_websocket_request, /* out: websocket connetion? */
  3953. int *is_put_or_delete_request /* out: put/delete a file? */
  3954. )
  3955. {
  3956. /* TODO (high): Restructure this function */
  3957. #if !defined(NO_FILES)
  3958. const char *uri = conn->request_info.local_uri;
  3959. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3960. const char *rewrite;
  3961. struct vec a, b;
  3962. int match_len;
  3963. char gz_path[PATH_MAX];
  3964. char const *accept_encoding;
  3965. int truncated;
  3966. #if !defined(NO_CGI) || defined(USE_LUA)
  3967. char *p;
  3968. #endif
  3969. #else
  3970. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3971. #endif
  3972. memset(filep, 0, sizeof(*filep));
  3973. *filename = 0;
  3974. *is_found = 0;
  3975. *is_script_resource = 0;
  3976. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3977. #if defined(USE_WEBSOCKET)
  3978. *is_websocket_request = is_websocket_protocol(conn);
  3979. #if !defined(NO_FILES)
  3980. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3981. root = conn->ctx->config[WEBSOCKET_ROOT];
  3982. }
  3983. #endif /* !NO_FILES */
  3984. #else /* USE_WEBSOCKET */
  3985. *is_websocket_request = 0;
  3986. #endif /* USE_WEBSOCKET */
  3987. #if !defined(NO_FILES)
  3988. /* Note that root == NULL is a regular use case here. This occurs,
  3989. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3990. * config is not required. */
  3991. if (root == NULL) {
  3992. /* all file related outputs have already been set to 0, just return
  3993. */
  3994. return;
  3995. }
  3996. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3997. * of the path one byte on the right.
  3998. * If document_root is NULL, leave the file empty. */
  3999. mg_snprintf(
  4000. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4001. if (truncated) {
  4002. goto interpret_cleanup;
  4003. }
  4004. rewrite = conn->ctx->config[REWRITE];
  4005. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4006. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4007. mg_snprintf(conn,
  4008. &truncated,
  4009. filename,
  4010. filename_buf_len - 1,
  4011. "%.*s%s",
  4012. (int)b.len,
  4013. b.ptr,
  4014. uri + match_len);
  4015. break;
  4016. }
  4017. }
  4018. if (truncated) {
  4019. goto interpret_cleanup;
  4020. }
  4021. /* Local file path and name, corresponding to requested URI
  4022. * is now stored in "filename" variable. */
  4023. if (mg_stat(conn, filename, filep)) {
  4024. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4025. /* File exists. Check if it is a script type. */
  4026. if (0
  4027. #if !defined(NO_CGI)
  4028. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4029. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4030. filename) > 0
  4031. #endif
  4032. #if defined(USE_LUA)
  4033. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4034. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4035. filename) > 0
  4036. #endif
  4037. #if defined(USE_DUKTAPE)
  4038. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4039. strlen(
  4040. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4041. filename) > 0
  4042. #endif
  4043. ) {
  4044. /* The request addresses a CGI script or a Lua script. The URI
  4045. * corresponds to the script itself (like /path/script.cgi),
  4046. * and there is no additional resource path
  4047. * (like /path/script.cgi/something).
  4048. * Requests that modify (replace or delete) a resource, like
  4049. * PUT and DELETE requests, should replace/delete the script
  4050. * file.
  4051. * Requests that read or write from/to a resource, like GET and
  4052. * POST requests, should call the script and return the
  4053. * generated response. */
  4054. *is_script_resource = !*is_put_or_delete_request;
  4055. }
  4056. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4057. *is_found = 1;
  4058. return;
  4059. }
  4060. /* If we can't find the actual file, look for the file
  4061. * with the same name but a .gz extension. If we find it,
  4062. * use that and set the gzipped flag in the file struct
  4063. * to indicate that the response need to have the content-
  4064. * encoding: gzip header.
  4065. * We can only do this if the browser declares support. */
  4066. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4067. if (strstr(accept_encoding, "gzip") != NULL) {
  4068. mg_snprintf(
  4069. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4070. if (truncated) {
  4071. goto interpret_cleanup;
  4072. }
  4073. if (mg_stat(conn, gz_path, filep)) {
  4074. if (filep) {
  4075. filep->gzipped = 1;
  4076. *is_found = 1;
  4077. }
  4078. /* Currently gz files can not be scripts. */
  4079. return;
  4080. }
  4081. }
  4082. }
  4083. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4084. /* Support PATH_INFO for CGI scripts. */
  4085. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4086. if (*p == '/') {
  4087. *p = '\0';
  4088. if ((0
  4089. #if !defined(NO_CGI)
  4090. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4091. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4092. filename) > 0
  4093. #endif
  4094. #if defined(USE_LUA)
  4095. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4096. strlen(
  4097. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4098. filename) > 0
  4099. #endif
  4100. #if defined(USE_DUKTAPE)
  4101. || match_prefix(
  4102. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4103. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4104. filename) > 0
  4105. #endif
  4106. ) && mg_stat(conn, filename, filep)) {
  4107. /* Shift PATH_INFO block one character right, e.g.
  4108. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4109. * conn->path_info is pointing to the local variable "path"
  4110. * declared in handle_request(), so PATH_INFO is not valid
  4111. * after handle_request returns. */
  4112. conn->path_info = p + 1;
  4113. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4114. * trailing \0 */
  4115. p[1] = '/';
  4116. *is_script_resource = 1;
  4117. break;
  4118. } else {
  4119. *p = '/';
  4120. }
  4121. }
  4122. }
  4123. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4124. #endif /* !defined(NO_FILES) */
  4125. return;
  4126. #if !defined(NO_FILES)
  4127. /* Reset all outputs */
  4128. interpret_cleanup:
  4129. memset(filep, 0, sizeof(*filep));
  4130. *filename = 0;
  4131. *is_found = 0;
  4132. *is_script_resource = 0;
  4133. *is_websocket_request = 0;
  4134. *is_put_or_delete_request = 0;
  4135. #endif /* !defined(NO_FILES) */
  4136. }
  4137. /* Check whether full request is buffered. Return:
  4138. * -1 if request is malformed
  4139. * 0 if request is not yet fully buffered
  4140. * >0 actual request length, including last \r\n\r\n */
  4141. static int
  4142. get_request_len(const char *buf, int buflen)
  4143. {
  4144. const char *s, *e;
  4145. int len = 0;
  4146. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4147. /* Control characters are not allowed but >=128 is. */
  4148. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4149. && *(const unsigned char *)s < 128) {
  4150. len = -1;
  4151. break; /* [i_a] abort scan as soon as one malformed character is
  4152. * found; */
  4153. /* don't let subsequent \r\n\r\n win us over anyhow */
  4154. } else if (s[0] == '\n' && s[1] == '\n') {
  4155. len = (int)(s - buf) + 2;
  4156. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4157. len = (int)(s - buf) + 3;
  4158. }
  4159. return len;
  4160. }
  4161. #if !defined(NO_CACHING)
  4162. /* Convert month to the month number. Return -1 on error, or month number */
  4163. static int
  4164. get_month_index(const char *s)
  4165. {
  4166. size_t i;
  4167. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4168. if (!strcmp(s, month_names[i])) {
  4169. return (int)i;
  4170. }
  4171. }
  4172. return -1;
  4173. }
  4174. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4175. static time_t
  4176. parse_date_string(const char *datetime)
  4177. {
  4178. char month_str[32] = {0};
  4179. int second, minute, hour, day, month, year;
  4180. time_t result = (time_t)0;
  4181. struct tm tm;
  4182. if ((sscanf(datetime,
  4183. "%d/%3s/%d %d:%d:%d",
  4184. &day,
  4185. month_str,
  4186. &year,
  4187. &hour,
  4188. &minute,
  4189. &second) == 6) || (sscanf(datetime,
  4190. "%d %3s %d %d:%d:%d",
  4191. &day,
  4192. month_str,
  4193. &year,
  4194. &hour,
  4195. &minute,
  4196. &second) == 6)
  4197. || (sscanf(datetime,
  4198. "%*3s, %d %3s %d %d:%d:%d",
  4199. &day,
  4200. month_str,
  4201. &year,
  4202. &hour,
  4203. &minute,
  4204. &second) == 6) || (sscanf(datetime,
  4205. "%d-%3s-%d %d:%d:%d",
  4206. &day,
  4207. month_str,
  4208. &year,
  4209. &hour,
  4210. &minute,
  4211. &second) == 6)) {
  4212. month = get_month_index(month_str);
  4213. if ((month >= 0) && (year >= 1970)) {
  4214. memset(&tm, 0, sizeof(tm));
  4215. tm.tm_year = year - 1900;
  4216. tm.tm_mon = month;
  4217. tm.tm_mday = day;
  4218. tm.tm_hour = hour;
  4219. tm.tm_min = minute;
  4220. tm.tm_sec = second;
  4221. result = timegm(&tm);
  4222. }
  4223. }
  4224. return result;
  4225. }
  4226. #endif /* !NO_CACHING */
  4227. /* Protect against directory disclosure attack by removing '..',
  4228. * excessive '/' and '\' characters */
  4229. static void
  4230. remove_double_dots_and_double_slashes(char *s)
  4231. {
  4232. char *p = s;
  4233. while (*s != '\0') {
  4234. *p++ = *s++;
  4235. if (s[-1] == '/' || s[-1] == '\\') {
  4236. /* Skip all following slashes, backslashes and double-dots */
  4237. while (s[0] != '\0') {
  4238. if (s[0] == '/' || s[0] == '\\') {
  4239. s++;
  4240. } else if (s[0] == '.' && s[1] == '.') {
  4241. s += 2;
  4242. } else {
  4243. break;
  4244. }
  4245. }
  4246. }
  4247. }
  4248. *p = '\0';
  4249. }
  4250. static const struct {
  4251. const char *extension;
  4252. size_t ext_len;
  4253. const char *mime_type;
  4254. } builtin_mime_types[] = {
  4255. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4256. * application types */
  4257. {".doc", 4, "application/msword"},
  4258. {".eps", 4, "application/postscript"},
  4259. {".exe", 4, "application/octet-stream"},
  4260. {".js", 3, "application/javascript"},
  4261. {".json", 5, "application/json"},
  4262. {".pdf", 4, "application/pdf"},
  4263. {".ps", 3, "application/postscript"},
  4264. {".rtf", 4, "application/rtf"},
  4265. {".xhtml", 6, "application/xhtml+xml"},
  4266. {".xsl", 4, "application/xml"},
  4267. {".xslt", 5, "application/xml"},
  4268. /* fonts */
  4269. {".ttf", 4, "application/font-sfnt"},
  4270. {".cff", 4, "application/font-sfnt"},
  4271. {".otf", 4, "application/font-sfnt"},
  4272. {".aat", 4, "application/font-sfnt"},
  4273. {".sil", 4, "application/font-sfnt"},
  4274. {".pfr", 4, "application/font-tdpfr"},
  4275. {".woff", 5, "application/font-woff"},
  4276. /* audio */
  4277. {".mp3", 4, "audio/mpeg"},
  4278. {".oga", 4, "audio/ogg"},
  4279. {".ogg", 4, "audio/ogg"},
  4280. /* image */
  4281. {".gif", 4, "image/gif"},
  4282. {".ief", 4, "image/ief"},
  4283. {".jpeg", 5, "image/jpeg"},
  4284. {".jpg", 4, "image/jpeg"},
  4285. {".jpm", 4, "image/jpm"},
  4286. {".jpx", 4, "image/jpx"},
  4287. {".png", 4, "image/png"},
  4288. {".svg", 4, "image/svg+xml"},
  4289. {".tif", 4, "image/tiff"},
  4290. {".tiff", 5, "image/tiff"},
  4291. /* model */
  4292. {".wrl", 4, "model/vrml"},
  4293. /* text */
  4294. {".css", 4, "text/css"},
  4295. {".csv", 4, "text/csv"},
  4296. {".htm", 4, "text/html"},
  4297. {".html", 5, "text/html"},
  4298. {".sgm", 4, "text/sgml"},
  4299. {".shtm", 5, "text/html"},
  4300. {".shtml", 6, "text/html"},
  4301. {".txt", 4, "text/plain"},
  4302. {".xml", 4, "text/xml"},
  4303. /* video */
  4304. {".mov", 4, "video/quicktime"},
  4305. {".mp4", 4, "video/mp4"},
  4306. {".mpeg", 5, "video/mpeg"},
  4307. {".mpg", 4, "video/mpeg"},
  4308. {".ogv", 4, "video/ogg"},
  4309. {".qt", 3, "video/quicktime"},
  4310. /* not registered types
  4311. * (http://reference.sitepoint.com/html/mime-types-full,
  4312. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4313. {".arj", 4, "application/x-arj-compressed"},
  4314. {".gz", 3, "application/x-gunzip"},
  4315. {".rar", 4, "application/x-arj-compressed"},
  4316. {".swf", 4, "application/x-shockwave-flash"},
  4317. {".tar", 4, "application/x-tar"},
  4318. {".tgz", 4, "application/x-tar-gz"},
  4319. {".torrent", 8, "application/x-bittorrent"},
  4320. {".ppt", 4, "application/x-mspowerpoint"},
  4321. {".xls", 4, "application/x-msexcel"},
  4322. {".zip", 4, "application/x-zip-compressed"},
  4323. {".aac",
  4324. 4,
  4325. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4326. {".aif", 4, "audio/x-aif"},
  4327. {".m3u", 4, "audio/x-mpegurl"},
  4328. {".mid", 4, "audio/x-midi"},
  4329. {".ra", 3, "audio/x-pn-realaudio"},
  4330. {".ram", 4, "audio/x-pn-realaudio"},
  4331. {".wav", 4, "audio/x-wav"},
  4332. {".bmp", 4, "image/bmp"},
  4333. {".ico", 4, "image/x-icon"},
  4334. {".pct", 4, "image/x-pct"},
  4335. {".pict", 5, "image/pict"},
  4336. {".rgb", 4, "image/x-rgb"},
  4337. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4338. {".asf", 4, "video/x-ms-asf"},
  4339. {".avi", 4, "video/x-msvideo"},
  4340. {".m4v", 4, "video/x-m4v"},
  4341. {NULL, 0, NULL}};
  4342. const char *
  4343. mg_get_builtin_mime_type(const char *path)
  4344. {
  4345. const char *ext;
  4346. size_t i, path_len;
  4347. path_len = strlen(path);
  4348. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4349. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4350. if (path_len > builtin_mime_types[i].ext_len
  4351. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4352. return builtin_mime_types[i].mime_type;
  4353. }
  4354. }
  4355. return "text/plain";
  4356. }
  4357. /* Look at the "path" extension and figure what mime type it has.
  4358. * Store mime type in the vector. */
  4359. static void
  4360. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4361. {
  4362. struct vec ext_vec, mime_vec;
  4363. const char *list, *ext;
  4364. size_t path_len;
  4365. path_len = strlen(path);
  4366. if (ctx == NULL || vec == NULL) {
  4367. return;
  4368. }
  4369. /* Scan user-defined mime types first, in case user wants to
  4370. * override default mime types. */
  4371. list = ctx->config[EXTRA_MIME_TYPES];
  4372. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4373. /* ext now points to the path suffix */
  4374. ext = path + path_len - ext_vec.len;
  4375. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4376. *vec = mime_vec;
  4377. return;
  4378. }
  4379. }
  4380. vec->ptr = mg_get_builtin_mime_type(path);
  4381. vec->len = strlen(vec->ptr);
  4382. }
  4383. /* Stringify binary data. Output buffer must be twice as big as input,
  4384. * because each byte takes 2 bytes in string representation */
  4385. static void
  4386. bin2str(char *to, const unsigned char *p, size_t len)
  4387. {
  4388. static const char *hex = "0123456789abcdef";
  4389. for (; len--; p++) {
  4390. *to++ = hex[p[0] >> 4];
  4391. *to++ = hex[p[0] & 0x0f];
  4392. }
  4393. *to = '\0';
  4394. }
  4395. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4396. char *
  4397. mg_md5(char buf[33], ...)
  4398. {
  4399. md5_byte_t hash[16];
  4400. const char *p;
  4401. va_list ap;
  4402. md5_state_t ctx;
  4403. md5_init(&ctx);
  4404. va_start(ap, buf);
  4405. while ((p = va_arg(ap, const char *)) != NULL) {
  4406. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4407. }
  4408. va_end(ap);
  4409. md5_finish(&ctx, hash);
  4410. bin2str(buf, hash, sizeof(hash));
  4411. return buf;
  4412. }
  4413. /* Check the user's password, return 1 if OK */
  4414. static int
  4415. check_password(const char *method,
  4416. const char *ha1,
  4417. const char *uri,
  4418. const char *nonce,
  4419. const char *nc,
  4420. const char *cnonce,
  4421. const char *qop,
  4422. const char *response)
  4423. {
  4424. char ha2[32 + 1], expected_response[32 + 1];
  4425. /* Some of the parameters may be NULL */
  4426. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4427. || qop == NULL
  4428. || response == NULL) {
  4429. return 0;
  4430. }
  4431. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4432. if (strlen(response) != 32) {
  4433. return 0;
  4434. }
  4435. mg_md5(ha2, method, ":", uri, NULL);
  4436. mg_md5(expected_response,
  4437. ha1,
  4438. ":",
  4439. nonce,
  4440. ":",
  4441. nc,
  4442. ":",
  4443. cnonce,
  4444. ":",
  4445. qop,
  4446. ":",
  4447. ha2,
  4448. NULL);
  4449. return mg_strcasecmp(response, expected_response) == 0;
  4450. }
  4451. /* Use the global passwords file, if specified by auth_gpass option,
  4452. * or search for .htpasswd in the requested directory. */
  4453. static void
  4454. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4455. {
  4456. if (conn != NULL && conn->ctx != NULL) {
  4457. char name[PATH_MAX];
  4458. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4459. struct file file = STRUCT_FILE_INITIALIZER;
  4460. int truncated;
  4461. if (gpass != NULL) {
  4462. /* Use global passwords file */
  4463. if (!mg_fopen(conn, gpass, "r", filep)) {
  4464. #ifdef DEBUG
  4465. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4466. #endif
  4467. }
  4468. /* Important: using local struct file to test path for is_directory
  4469. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4470. * was opened. */
  4471. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4472. mg_snprintf(conn,
  4473. &truncated,
  4474. name,
  4475. sizeof(name),
  4476. "%s/%s",
  4477. path,
  4478. PASSWORDS_FILE_NAME);
  4479. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4480. #ifdef DEBUG
  4481. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4482. #endif
  4483. }
  4484. } else {
  4485. /* Try to find .htpasswd in requested directory. */
  4486. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4487. if (e[0] == '/') {
  4488. break;
  4489. }
  4490. }
  4491. mg_snprintf(conn,
  4492. &truncated,
  4493. name,
  4494. sizeof(name),
  4495. "%.*s%s",
  4496. (int)(e - p),
  4497. p,
  4498. PASSWORDS_FILE_NAME);
  4499. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4500. #ifdef DEBUG
  4501. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4502. #endif
  4503. }
  4504. }
  4505. }
  4506. }
  4507. /* Parsed Authorization header */
  4508. struct ah {
  4509. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4510. };
  4511. /* Return 1 on success. Always initializes the ah structure. */
  4512. static int
  4513. parse_auth_header(struct mg_connection *conn,
  4514. char *buf,
  4515. size_t buf_size,
  4516. struct ah *ah)
  4517. {
  4518. char *name, *value, *s;
  4519. const char *auth_header;
  4520. uint64_t nonce;
  4521. if (!ah || !conn) {
  4522. return 0;
  4523. }
  4524. (void)memset(ah, 0, sizeof(*ah));
  4525. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4526. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4527. return 0;
  4528. }
  4529. /* Make modifiable copy of the auth header */
  4530. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4531. s = buf;
  4532. /* Parse authorization header */
  4533. for (;;) {
  4534. /* Gobble initial spaces */
  4535. while (isspace(*(unsigned char *)s)) {
  4536. s++;
  4537. }
  4538. name = skip_quoted(&s, "=", " ", 0);
  4539. /* Value is either quote-delimited, or ends at first comma or space. */
  4540. if (s[0] == '\"') {
  4541. s++;
  4542. value = skip_quoted(&s, "\"", " ", '\\');
  4543. if (s[0] == ',') {
  4544. s++;
  4545. }
  4546. } else {
  4547. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4548. * spaces */
  4549. }
  4550. if (*name == '\0') {
  4551. break;
  4552. }
  4553. if (!strcmp(name, "username")) {
  4554. ah->user = value;
  4555. } else if (!strcmp(name, "cnonce")) {
  4556. ah->cnonce = value;
  4557. } else if (!strcmp(name, "response")) {
  4558. ah->response = value;
  4559. } else if (!strcmp(name, "uri")) {
  4560. ah->uri = value;
  4561. } else if (!strcmp(name, "qop")) {
  4562. ah->qop = value;
  4563. } else if (!strcmp(name, "nc")) {
  4564. ah->nc = value;
  4565. } else if (!strcmp(name, "nonce")) {
  4566. ah->nonce = value;
  4567. }
  4568. }
  4569. #ifndef NO_NONCE_CHECK
  4570. /* Read the nonce from the response. */
  4571. if (ah->nonce == NULL) {
  4572. return 0;
  4573. }
  4574. s = NULL;
  4575. nonce = strtoull(ah->nonce, &s, 10);
  4576. if ((s == NULL) || (*s != 0)) {
  4577. return 0;
  4578. }
  4579. /* Convert the nonce from the client to a number. */
  4580. nonce ^= conn->ctx->auth_nonce_mask;
  4581. /* The converted number corresponds to the time the nounce has been
  4582. * created. This should not be earlier than the server start. */
  4583. /* Server side nonce check is valuable in all situations but one:
  4584. * if the server restarts frequently, but the client should not see
  4585. * that, so the server should accept nonces from previous starts. */
  4586. /* However, the reasonable default is to not accept a nonce from a
  4587. * previous start, so if anyone changed the access rights between
  4588. * two restarts, a new login is required. */
  4589. if (nonce < (uint64_t)conn->ctx->start_time) {
  4590. /* nonce is from a previous start of the server and no longer valid
  4591. * (replay attack?) */
  4592. return 0;
  4593. }
  4594. /* Check if the nonce is too high, so it has not (yet) been used by the
  4595. * server. */
  4596. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4597. return 0;
  4598. }
  4599. #endif
  4600. /* CGI needs it as REMOTE_USER */
  4601. if (ah->user != NULL) {
  4602. conn->request_info.remote_user = mg_strdup(ah->user);
  4603. } else {
  4604. return 0;
  4605. }
  4606. return 1;
  4607. }
  4608. static const char *
  4609. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4610. {
  4611. const char *eof;
  4612. size_t len;
  4613. const char *memend;
  4614. if (!filep) {
  4615. return NULL;
  4616. }
  4617. if (filep->membuf != NULL && *p != NULL) {
  4618. memend = (const char *)&filep->membuf[filep->size];
  4619. /* Search for \n from p till the end of stream */
  4620. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4621. if (eof != NULL) {
  4622. eof += 1; /* Include \n */
  4623. } else {
  4624. eof = memend; /* Copy remaining data */
  4625. }
  4626. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4627. memcpy(buf, *p, len);
  4628. buf[len] = '\0';
  4629. *p += len;
  4630. return len ? eof : NULL;
  4631. } else if (filep->fp != NULL) {
  4632. return fgets(buf, (int)size, filep->fp);
  4633. } else {
  4634. return NULL;
  4635. }
  4636. }
  4637. struct read_auth_file_struct {
  4638. struct mg_connection *conn;
  4639. struct ah ah;
  4640. char *domain;
  4641. char buf[256 + 256 + 40];
  4642. char *f_user;
  4643. char *f_domain;
  4644. char *f_ha1;
  4645. };
  4646. static int
  4647. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4648. {
  4649. char *p;
  4650. int is_authorized = 0;
  4651. struct file fp;
  4652. size_t l;
  4653. if (!filep || !workdata) {
  4654. return 0;
  4655. }
  4656. /* Loop over passwords file */
  4657. p = (char *)filep->membuf;
  4658. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4659. l = strlen(workdata->buf);
  4660. while (l > 0) {
  4661. if (isspace(workdata->buf[l - 1])
  4662. || iscntrl(workdata->buf[l - 1])) {
  4663. l--;
  4664. workdata->buf[l] = 0;
  4665. } else
  4666. break;
  4667. }
  4668. if (l < 1) {
  4669. continue;
  4670. }
  4671. workdata->f_user = workdata->buf;
  4672. if (workdata->f_user[0] == ':') {
  4673. /* user names may not contain a ':' and may not be empty,
  4674. * so lines starting with ':' may be used for a special purpose */
  4675. if (workdata->f_user[1] == '#') {
  4676. /* :# is a comment */
  4677. continue;
  4678. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4679. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4680. is_authorized = read_auth_file(&fp, workdata);
  4681. mg_fclose(&fp);
  4682. } else {
  4683. mg_cry(workdata->conn,
  4684. "%s: cannot open authorization file: %s",
  4685. __func__,
  4686. workdata->buf);
  4687. }
  4688. continue;
  4689. }
  4690. /* everything is invalid for the moment (might change in the
  4691. * future) */
  4692. mg_cry(workdata->conn,
  4693. "%s: syntax error in authorization file: %s",
  4694. __func__,
  4695. workdata->buf);
  4696. continue;
  4697. }
  4698. workdata->f_domain = strchr(workdata->f_user, ':');
  4699. if (workdata->f_domain == NULL) {
  4700. mg_cry(workdata->conn,
  4701. "%s: syntax error in authorization file: %s",
  4702. __func__,
  4703. workdata->buf);
  4704. continue;
  4705. }
  4706. *(workdata->f_domain) = 0;
  4707. (workdata->f_domain)++;
  4708. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4709. if (workdata->f_ha1 == NULL) {
  4710. mg_cry(workdata->conn,
  4711. "%s: syntax error in authorization file: %s",
  4712. __func__,
  4713. workdata->buf);
  4714. continue;
  4715. }
  4716. *(workdata->f_ha1) = 0;
  4717. (workdata->f_ha1)++;
  4718. if (!strcmp(workdata->ah.user, workdata->f_user)
  4719. && !strcmp(workdata->domain, workdata->f_domain)) {
  4720. return check_password(workdata->conn->request_info.request_method,
  4721. workdata->f_ha1,
  4722. workdata->ah.uri,
  4723. workdata->ah.nonce,
  4724. workdata->ah.nc,
  4725. workdata->ah.cnonce,
  4726. workdata->ah.qop,
  4727. workdata->ah.response);
  4728. }
  4729. }
  4730. return is_authorized;
  4731. }
  4732. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4733. static int
  4734. authorize(struct mg_connection *conn, struct file *filep)
  4735. {
  4736. struct read_auth_file_struct workdata;
  4737. char buf[MG_BUF_LEN];
  4738. if (!conn || !conn->ctx) {
  4739. return 0;
  4740. }
  4741. memset(&workdata, 0, sizeof(workdata));
  4742. workdata.conn = conn;
  4743. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4744. return 0;
  4745. }
  4746. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4747. return read_auth_file(filep, &workdata);
  4748. }
  4749. /* Return 1 if request is authorised, 0 otherwise. */
  4750. static int
  4751. check_authorization(struct mg_connection *conn, const char *path)
  4752. {
  4753. char fname[PATH_MAX];
  4754. struct vec uri_vec, filename_vec;
  4755. const char *list;
  4756. struct file file = STRUCT_FILE_INITIALIZER;
  4757. int authorized = 1, truncated;
  4758. if (!conn || !conn->ctx) {
  4759. return 0;
  4760. }
  4761. list = conn->ctx->config[PROTECT_URI];
  4762. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4763. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4764. mg_snprintf(conn,
  4765. &truncated,
  4766. fname,
  4767. sizeof(fname),
  4768. "%.*s",
  4769. (int)filename_vec.len,
  4770. filename_vec.ptr);
  4771. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4772. mg_cry(conn,
  4773. "%s: cannot open %s: %s",
  4774. __func__,
  4775. fname,
  4776. strerror(errno));
  4777. }
  4778. break;
  4779. }
  4780. }
  4781. if (!is_file_opened(&file)) {
  4782. open_auth_file(conn, path, &file);
  4783. }
  4784. if (is_file_opened(&file)) {
  4785. authorized = authorize(conn, &file);
  4786. mg_fclose(&file);
  4787. }
  4788. return authorized;
  4789. }
  4790. static void
  4791. send_authorization_request(struct mg_connection *conn)
  4792. {
  4793. char date[64];
  4794. time_t curtime = time(NULL);
  4795. if (conn && conn->ctx) {
  4796. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4797. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4798. nonce += conn->ctx->nonce_count;
  4799. ++conn->ctx->nonce_count;
  4800. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4801. nonce ^= conn->ctx->auth_nonce_mask;
  4802. conn->status_code = 401;
  4803. conn->must_close = 1;
  4804. gmt_time_string(date, sizeof(date), &curtime);
  4805. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4806. send_no_cache_header(conn);
  4807. mg_printf(conn,
  4808. "Date: %s\r\n"
  4809. "Connection: %s\r\n"
  4810. "Content-Length: 0\r\n"
  4811. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4812. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4813. date,
  4814. suggest_connection_header(conn),
  4815. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4816. nonce);
  4817. }
  4818. }
  4819. #if !defined(NO_FILES)
  4820. static int
  4821. is_authorized_for_put(struct mg_connection *conn)
  4822. {
  4823. if (conn) {
  4824. struct file file = STRUCT_FILE_INITIALIZER;
  4825. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4826. int ret = 0;
  4827. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4828. ret = authorize(conn, &file);
  4829. mg_fclose(&file);
  4830. }
  4831. return ret;
  4832. }
  4833. return 0;
  4834. }
  4835. #endif
  4836. int
  4837. mg_modify_passwords_file(const char *fname,
  4838. const char *domain,
  4839. const char *user,
  4840. const char *pass)
  4841. {
  4842. int found, i;
  4843. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4844. FILE *fp, *fp2;
  4845. found = 0;
  4846. fp = fp2 = NULL;
  4847. /* Regard empty password as no password - remove user record. */
  4848. if (pass != NULL && pass[0] == '\0') {
  4849. pass = NULL;
  4850. }
  4851. /* Other arguments must not be empty */
  4852. if (fname == NULL || domain == NULL || user == NULL) {
  4853. return 0;
  4854. }
  4855. /* Using the given file format, user name and domain must not contain ':'
  4856. */
  4857. if (strchr(user, ':') != NULL) {
  4858. return 0;
  4859. }
  4860. if (strchr(domain, ':') != NULL) {
  4861. return 0;
  4862. }
  4863. /* Do not allow control characters like newline in user name and domain.
  4864. * Do not allow excessively long names either. */
  4865. for (i = 0; i < 255 && user[i] != 0; i++) {
  4866. if (iscntrl(user[i])) {
  4867. return 0;
  4868. }
  4869. }
  4870. if (user[i]) {
  4871. return 0;
  4872. }
  4873. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4874. if (iscntrl(domain[i])) {
  4875. return 0;
  4876. }
  4877. }
  4878. if (domain[i]) {
  4879. return 0;
  4880. }
  4881. /* The maximum length of the path to the password file is limited */
  4882. if ((strlen(fname) + 4) >= PATH_MAX) {
  4883. return 0;
  4884. }
  4885. /* Create a temporary file name. Length has been checked before. */
  4886. strcpy(tmp, fname);
  4887. strcat(tmp, ".tmp");
  4888. /* Create the file if does not exist */
  4889. /* Use of fopen here is OK, since fname is only ASCII */
  4890. if ((fp = fopen(fname, "a+")) != NULL) {
  4891. (void)fclose(fp);
  4892. }
  4893. /* Open the given file and temporary file */
  4894. if ((fp = fopen(fname, "r")) == NULL) {
  4895. return 0;
  4896. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4897. fclose(fp);
  4898. return 0;
  4899. }
  4900. /* Copy the stuff to temporary file */
  4901. while (fgets(line, sizeof(line), fp) != NULL) {
  4902. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4903. continue;
  4904. }
  4905. u[255] = 0;
  4906. d[255] = 0;
  4907. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4908. found++;
  4909. if (pass != NULL) {
  4910. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4911. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4912. }
  4913. } else {
  4914. fprintf(fp2, "%s", line);
  4915. }
  4916. }
  4917. /* If new user, just add it */
  4918. if (!found && pass != NULL) {
  4919. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4920. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4921. }
  4922. /* Close files */
  4923. fclose(fp);
  4924. fclose(fp2);
  4925. /* Put the temp file in place of real file */
  4926. IGNORE_UNUSED_RESULT(remove(fname));
  4927. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4928. return 1;
  4929. }
  4930. static int
  4931. is_valid_port(unsigned long port)
  4932. {
  4933. return port < 0xffff;
  4934. }
  4935. static int
  4936. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4937. {
  4938. struct addrinfo hints, *res, *ressave;
  4939. int ret = 0;
  4940. memset(&hints, 0, sizeof(struct addrinfo));
  4941. hints.ai_family = af;
  4942. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4943. /* bad src string or bad address family */
  4944. return 0;
  4945. }
  4946. ressave = res;
  4947. while (res) {
  4948. if (dstlen >= res->ai_addrlen) {
  4949. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4950. ret = 1;
  4951. }
  4952. res = res->ai_next;
  4953. }
  4954. freeaddrinfo(ressave);
  4955. return ret;
  4956. }
  4957. static int
  4958. connect_socket(struct mg_context *ctx /* may be NULL */,
  4959. const char *host,
  4960. int port,
  4961. int use_ssl,
  4962. char *ebuf,
  4963. size_t ebuf_len,
  4964. SOCKET *sock /* output: socket, must not be NULL */,
  4965. union usa *sa /* output: socket address, must not be NULL */
  4966. )
  4967. {
  4968. int ip_ver = 0;
  4969. *sock = INVALID_SOCKET;
  4970. memset(sa, 0, sizeof(*sa));
  4971. if (ebuf_len > 0) {
  4972. *ebuf = 0;
  4973. }
  4974. if (host == NULL) {
  4975. mg_snprintf(NULL,
  4976. NULL, /* No truncation check for ebuf */
  4977. ebuf,
  4978. ebuf_len,
  4979. "%s",
  4980. "NULL host");
  4981. return 0;
  4982. }
  4983. if (port < 0 || !is_valid_port((unsigned)port)) {
  4984. mg_snprintf(NULL,
  4985. NULL, /* No truncation check for ebuf */
  4986. ebuf,
  4987. ebuf_len,
  4988. "%s",
  4989. "invalid port");
  4990. return 0;
  4991. }
  4992. if (use_ssl && (SSLv23_client_method == NULL)) {
  4993. mg_snprintf(NULL,
  4994. NULL, /* No truncation check for ebuf */
  4995. ebuf,
  4996. ebuf_len,
  4997. "%s",
  4998. "SSL is not initialized");
  4999. return 0;
  5000. }
  5001. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5002. sa->sin.sin_port = htons((uint16_t)port);
  5003. ip_ver = 4;
  5004. #ifdef USE_IPV6
  5005. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5006. sa->sin6.sin6_port = htons((uint16_t)port);
  5007. ip_ver = 6;
  5008. } else if (host[0] == '[') {
  5009. /* While getaddrinfo on Windows will work with [::1],
  5010. * getaddrinfo on Linux only works with ::1 (without []). */
  5011. size_t l = strlen(host + 1);
  5012. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  5013. if (h) {
  5014. h[l - 1] = 0;
  5015. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5016. sa->sin6.sin6_port = htons((uint16_t)port);
  5017. ip_ver = 6;
  5018. }
  5019. mg_free(h);
  5020. }
  5021. #endif
  5022. }
  5023. if (ip_ver == 0) {
  5024. mg_snprintf(NULL,
  5025. NULL, /* No truncation check for ebuf */
  5026. ebuf,
  5027. ebuf_len,
  5028. "%s",
  5029. "host not found");
  5030. return 0;
  5031. }
  5032. if (ip_ver == 4) {
  5033. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5034. }
  5035. #ifdef USE_IPV6
  5036. else if (ip_ver == 6) {
  5037. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5038. }
  5039. #endif
  5040. if (*sock == INVALID_SOCKET) {
  5041. mg_snprintf(NULL,
  5042. NULL, /* No truncation check for ebuf */
  5043. ebuf,
  5044. ebuf_len,
  5045. "socket(): %s",
  5046. strerror(ERRNO));
  5047. return 0;
  5048. }
  5049. set_close_on_exec(*sock, fc(ctx));
  5050. if ((ip_ver == 4)
  5051. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5052. == 0)) {
  5053. /* connected with IPv4 */
  5054. return 1;
  5055. }
  5056. #ifdef USE_IPV6
  5057. if ((ip_ver == 6)
  5058. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5059. == 0)) {
  5060. /* connected with IPv6 */
  5061. return 1;
  5062. }
  5063. #endif
  5064. /* Not connected */
  5065. mg_snprintf(NULL,
  5066. NULL, /* No truncation check for ebuf */
  5067. ebuf,
  5068. ebuf_len,
  5069. "connect(%s:%d): %s",
  5070. host,
  5071. port,
  5072. strerror(ERRNO));
  5073. closesocket(*sock);
  5074. *sock = INVALID_SOCKET;
  5075. return 0;
  5076. }
  5077. int
  5078. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5079. {
  5080. static const char *dont_escape = "._-$,;~()";
  5081. static const char *hex = "0123456789abcdef";
  5082. char *pos = dst;
  5083. const char *end = dst + dst_len - 1;
  5084. for (; *src != '\0' && pos < end; src++, pos++) {
  5085. if (isalnum(*(const unsigned char *)src)
  5086. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5087. *pos = *src;
  5088. } else if (pos + 2 < end) {
  5089. pos[0] = '%';
  5090. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5091. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5092. pos += 2;
  5093. } else {
  5094. break;
  5095. }
  5096. }
  5097. *pos = '\0';
  5098. return (*src == '\0') ? (int)(pos - dst) : -1;
  5099. }
  5100. static void
  5101. print_dir_entry(struct de *de)
  5102. {
  5103. char size[64], mod[64], href[PATH_MAX];
  5104. struct tm *tm;
  5105. if (de->file.is_directory) {
  5106. mg_snprintf(de->conn,
  5107. NULL, /* Buffer is big enough */
  5108. size,
  5109. sizeof(size),
  5110. "%s",
  5111. "[DIRECTORY]");
  5112. } else {
  5113. /* We use (signed) cast below because MSVC 6 compiler cannot
  5114. * convert unsigned __int64 to double. Sigh. */
  5115. if (de->file.size < 1024) {
  5116. mg_snprintf(de->conn,
  5117. NULL, /* Buffer is big enough */
  5118. size,
  5119. sizeof(size),
  5120. "%d",
  5121. (int)de->file.size);
  5122. } else if (de->file.size < 0x100000) {
  5123. mg_snprintf(de->conn,
  5124. NULL, /* Buffer is big enough */
  5125. size,
  5126. sizeof(size),
  5127. "%.1fk",
  5128. (double)de->file.size / 1024.0);
  5129. } else if (de->file.size < 0x40000000) {
  5130. mg_snprintf(de->conn,
  5131. NULL, /* Buffer is big enough */
  5132. size,
  5133. sizeof(size),
  5134. "%.1fM",
  5135. (double)de->file.size / 1048576);
  5136. } else {
  5137. mg_snprintf(de->conn,
  5138. NULL, /* Buffer is big enough */
  5139. size,
  5140. sizeof(size),
  5141. "%.1fG",
  5142. (double)de->file.size / 1073741824);
  5143. }
  5144. }
  5145. /* Note: mg_snprintf will not cause a buffer overflow above.
  5146. * So, string truncation checks are not required here. */
  5147. tm = localtime(&de->file.last_modified);
  5148. if (tm != NULL) {
  5149. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5150. } else {
  5151. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5152. mod[sizeof(mod) - 1] = '\0';
  5153. }
  5154. mg_url_encode(de->file_name, href, sizeof(href));
  5155. de->conn->num_bytes_sent +=
  5156. mg_printf(de->conn,
  5157. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5158. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5159. de->conn->request_info.local_uri,
  5160. href,
  5161. de->file.is_directory ? "/" : "",
  5162. de->file_name,
  5163. de->file.is_directory ? "/" : "",
  5164. mod,
  5165. size);
  5166. }
  5167. /* This function is called from send_directory() and used for
  5168. * sorting directory entries by size, or name, or modification time.
  5169. * On windows, __cdecl specification is needed in case if project is built
  5170. * with __stdcall convention. qsort always requires __cdels callback. */
  5171. static int WINCDECL
  5172. compare_dir_entries(const void *p1, const void *p2)
  5173. {
  5174. if (p1 && p2) {
  5175. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5176. const char *query_string = a->conn->request_info.query_string;
  5177. int cmp_result = 0;
  5178. if (query_string == NULL) {
  5179. query_string = "na";
  5180. }
  5181. if (a->file.is_directory && !b->file.is_directory) {
  5182. return -1; /* Always put directories on top */
  5183. } else if (!a->file.is_directory && b->file.is_directory) {
  5184. return 1; /* Always put directories on top */
  5185. } else if (*query_string == 'n') {
  5186. cmp_result = strcmp(a->file_name, b->file_name);
  5187. } else if (*query_string == 's') {
  5188. cmp_result = a->file.size == b->file.size
  5189. ? 0
  5190. : a->file.size > b->file.size ? 1 : -1;
  5191. } else if (*query_string == 'd') {
  5192. cmp_result =
  5193. (a->file.last_modified == b->file.last_modified)
  5194. ? 0
  5195. : ((a->file.last_modified > b->file.last_modified) ? 1
  5196. : -1);
  5197. }
  5198. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5199. }
  5200. return 0;
  5201. }
  5202. static int
  5203. must_hide_file(struct mg_connection *conn, const char *path)
  5204. {
  5205. if (conn && conn->ctx) {
  5206. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5207. const char *pattern = conn->ctx->config[HIDE_FILES];
  5208. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5209. || (pattern != NULL
  5210. && match_prefix(pattern, strlen(pattern), path) > 0);
  5211. }
  5212. return 0;
  5213. }
  5214. static int
  5215. scan_directory(struct mg_connection *conn,
  5216. const char *dir,
  5217. void *data,
  5218. void (*cb)(struct de *, void *))
  5219. {
  5220. char path[PATH_MAX];
  5221. struct dirent *dp;
  5222. DIR *dirp;
  5223. struct de de;
  5224. int truncated;
  5225. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5226. return 0;
  5227. } else {
  5228. de.conn = conn;
  5229. while ((dp = mg_readdir(dirp)) != NULL) {
  5230. /* Do not show current dir and hidden files */
  5231. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5232. || must_hide_file(conn, dp->d_name)) {
  5233. continue;
  5234. }
  5235. mg_snprintf(
  5236. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5237. /* If we don't memset stat structure to zero, mtime will have
  5238. * garbage and strftime() will segfault later on in
  5239. * print_dir_entry(). memset is required only if mg_stat()
  5240. * fails. For more details, see
  5241. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5242. memset(&de.file, 0, sizeof(de.file));
  5243. if (truncated) {
  5244. /* If the path is not complete, skip processing. */
  5245. continue;
  5246. }
  5247. if (!mg_stat(conn, path, &de.file)) {
  5248. mg_cry(conn,
  5249. "%s: mg_stat(%s) failed: %s",
  5250. __func__,
  5251. path,
  5252. strerror(ERRNO));
  5253. }
  5254. de.file_name = dp->d_name;
  5255. cb(&de, data);
  5256. }
  5257. (void)mg_closedir(dirp);
  5258. }
  5259. return 1;
  5260. }
  5261. #if !defined(NO_FILES)
  5262. static int
  5263. remove_directory(struct mg_connection *conn, const char *dir)
  5264. {
  5265. char path[PATH_MAX];
  5266. struct dirent *dp;
  5267. DIR *dirp;
  5268. struct de de;
  5269. int truncated;
  5270. int ok = 1;
  5271. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5272. return 0;
  5273. } else {
  5274. de.conn = conn;
  5275. while ((dp = mg_readdir(dirp)) != NULL) {
  5276. /* Do not show current dir (but show hidden files as they will
  5277. * also be removed) */
  5278. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5279. continue;
  5280. }
  5281. mg_snprintf(
  5282. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5283. /* If we don't memset stat structure to zero, mtime will have
  5284. * garbage and strftime() will segfault later on in
  5285. * print_dir_entry(). memset is required only if mg_stat()
  5286. * fails. For more details, see
  5287. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5288. memset(&de.file, 0, sizeof(de.file));
  5289. if (truncated) {
  5290. /* Do not delete anything shorter */
  5291. ok = 0;
  5292. continue;
  5293. }
  5294. if (!mg_stat(conn, path, &de.file)) {
  5295. mg_cry(conn,
  5296. "%s: mg_stat(%s) failed: %s",
  5297. __func__,
  5298. path,
  5299. strerror(ERRNO));
  5300. ok = 0;
  5301. }
  5302. if (de.file.membuf == NULL) {
  5303. /* file is not in memory */
  5304. if (de.file.is_directory) {
  5305. if (remove_directory(conn, path) == 0) {
  5306. ok = 0;
  5307. }
  5308. } else {
  5309. if (mg_remove(conn, path) == 0) {
  5310. ok = 0;
  5311. }
  5312. }
  5313. } else {
  5314. /* file is in memory. It can not be deleted. */
  5315. ok = 0;
  5316. }
  5317. }
  5318. (void)mg_closedir(dirp);
  5319. IGNORE_UNUSED_RESULT(rmdir(dir));
  5320. }
  5321. return ok;
  5322. }
  5323. #endif
  5324. struct dir_scan_data {
  5325. struct de *entries;
  5326. unsigned int num_entries;
  5327. unsigned int arr_size;
  5328. };
  5329. /* Behaves like realloc(), but frees original pointer on failure */
  5330. static void *
  5331. realloc2(void *ptr, size_t size)
  5332. {
  5333. void *new_ptr = mg_realloc(ptr, size);
  5334. if (new_ptr == NULL) {
  5335. mg_free(ptr);
  5336. }
  5337. return new_ptr;
  5338. }
  5339. static void
  5340. dir_scan_callback(struct de *de, void *data)
  5341. {
  5342. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5343. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5344. dsd->arr_size *= 2;
  5345. dsd->entries =
  5346. (struct de *)realloc2(dsd->entries,
  5347. dsd->arr_size * sizeof(dsd->entries[0]));
  5348. }
  5349. if (dsd->entries == NULL) {
  5350. /* TODO(lsm, low): propagate an error to the caller */
  5351. dsd->num_entries = 0;
  5352. } else {
  5353. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5354. dsd->entries[dsd->num_entries].file = de->file;
  5355. dsd->entries[dsd->num_entries].conn = de->conn;
  5356. dsd->num_entries++;
  5357. }
  5358. }
  5359. static void
  5360. handle_directory_request(struct mg_connection *conn, const char *dir)
  5361. {
  5362. unsigned int i;
  5363. int sort_direction;
  5364. struct dir_scan_data data = {NULL, 0, 128};
  5365. char date[64];
  5366. time_t curtime = time(NULL);
  5367. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5368. send_http_error(conn,
  5369. 500,
  5370. "Error: Cannot open directory\nopendir(%s): %s",
  5371. dir,
  5372. strerror(ERRNO));
  5373. return;
  5374. }
  5375. gmt_time_string(date, sizeof(date), &curtime);
  5376. if (!conn) {
  5377. return;
  5378. }
  5379. sort_direction = conn->request_info.query_string != NULL
  5380. && conn->request_info.query_string[1] == 'd'
  5381. ? 'a'
  5382. : 'd';
  5383. conn->must_close = 1;
  5384. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5385. send_static_cache_header(conn);
  5386. mg_printf(conn,
  5387. "Date: %s\r\n"
  5388. "Connection: close\r\n"
  5389. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5390. date);
  5391. conn->num_bytes_sent +=
  5392. mg_printf(conn,
  5393. "<html><head><title>Index of %s</title>"
  5394. "<style>th {text-align: left;}</style></head>"
  5395. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5396. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5397. "<th><a href=\"?d%c\">Modified</a></th>"
  5398. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5399. "<tr><td colspan=\"3\"><hr></td></tr>",
  5400. conn->request_info.local_uri,
  5401. conn->request_info.local_uri,
  5402. sort_direction,
  5403. sort_direction,
  5404. sort_direction);
  5405. /* Print first entry - link to a parent directory */
  5406. conn->num_bytes_sent +=
  5407. mg_printf(conn,
  5408. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5409. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5410. conn->request_info.local_uri,
  5411. "..",
  5412. "Parent directory",
  5413. "-",
  5414. "-");
  5415. /* Sort and print directory entries */
  5416. if (data.entries != NULL) {
  5417. qsort(data.entries,
  5418. (size_t)data.num_entries,
  5419. sizeof(data.entries[0]),
  5420. compare_dir_entries);
  5421. for (i = 0; i < data.num_entries; i++) {
  5422. print_dir_entry(&data.entries[i]);
  5423. mg_free(data.entries[i].file_name);
  5424. }
  5425. mg_free(data.entries);
  5426. }
  5427. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5428. conn->status_code = 200;
  5429. }
  5430. /* Send len bytes from the opened file to the client. */
  5431. static void
  5432. send_file_data(struct mg_connection *conn,
  5433. struct file *filep,
  5434. int64_t offset,
  5435. int64_t len)
  5436. {
  5437. char buf[MG_BUF_LEN];
  5438. int to_read, num_read, num_written;
  5439. int64_t size;
  5440. if (!filep || !conn) {
  5441. return;
  5442. }
  5443. /* Sanity check the offset */
  5444. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5445. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5446. if (len > 0 && filep->membuf != NULL && size > 0) {
  5447. /* file stored in memory */
  5448. if (len > size - offset) {
  5449. len = size - offset;
  5450. }
  5451. mg_write(conn, filep->membuf + offset, (size_t)len);
  5452. } else if (len > 0 && filep->fp != NULL) {
  5453. /* file stored on disk */
  5454. #if defined(__linux__)
  5455. /* sendfile is only available for Linux */
  5456. if (conn->throttle == 0 && conn->ssl == 0) {
  5457. off_t sf_offs = (off_t)offset;
  5458. ssize_t sf_sent;
  5459. int sf_file = fileno(filep->fp);
  5460. int loop_cnt = 0;
  5461. do {
  5462. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5463. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5464. size_t sf_tosend =
  5465. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5466. sf_sent =
  5467. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5468. if (sf_sent > 0) {
  5469. conn->num_bytes_sent += sf_sent;
  5470. len -= sf_sent;
  5471. offset += sf_sent;
  5472. } else if (loop_cnt == 0) {
  5473. /* This file can not be sent using sendfile.
  5474. * This might be the case for pseudo-files in the
  5475. * /sys/ and /proc/ file system.
  5476. * Use the regular user mode copy code instead. */
  5477. break;
  5478. } else if (sf_sent == 0) {
  5479. /* No error, but 0 bytes sent. May be EOF? */
  5480. return;
  5481. }
  5482. loop_cnt++;
  5483. } while ((len > 0) && (sf_sent >= 0));
  5484. if (sf_sent > 0) {
  5485. return; /* OK */
  5486. }
  5487. /* sf_sent<0 means error, thus fall back to the classic way */
  5488. /* This is always the case, if sf_file is not a "normal" file,
  5489. * e.g., for sending data from the output of a CGI process. */
  5490. offset = (int64_t)sf_offs;
  5491. }
  5492. #endif
  5493. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5494. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5495. send_http_error(
  5496. conn,
  5497. 500,
  5498. "%s",
  5499. "Error: Unable to access file at requested position.");
  5500. } else {
  5501. while (len > 0) {
  5502. /* Calculate how much to read from the file in the buffer */
  5503. to_read = sizeof(buf);
  5504. if ((int64_t)to_read > len) {
  5505. to_read = (int)len;
  5506. }
  5507. /* Read from file, exit the loop on error */
  5508. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5509. <= 0) {
  5510. break;
  5511. }
  5512. /* Send read bytes to the client, exit the loop on error */
  5513. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5514. != num_read) {
  5515. break;
  5516. }
  5517. /* Both read and were successful, adjust counters */
  5518. conn->num_bytes_sent += num_written;
  5519. len -= num_written;
  5520. }
  5521. }
  5522. }
  5523. }
  5524. static int
  5525. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5526. {
  5527. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5528. }
  5529. static void
  5530. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5531. {
  5532. if (filep != NULL && buf != NULL) {
  5533. mg_snprintf(NULL,
  5534. NULL, /* All calls to construct_etag use 64 byte buffer */
  5535. buf,
  5536. buf_len,
  5537. "\"%lx.%" INT64_FMT "\"",
  5538. (unsigned long)filep->last_modified,
  5539. filep->size);
  5540. }
  5541. }
  5542. static void
  5543. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5544. {
  5545. if (filep != NULL && filep->fp != NULL) {
  5546. #ifdef _WIN32
  5547. (void)conn; /* Unused. */
  5548. #else
  5549. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5550. mg_cry(conn,
  5551. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5552. __func__,
  5553. strerror(ERRNO));
  5554. }
  5555. #endif
  5556. }
  5557. }
  5558. static void
  5559. handle_static_file_request(struct mg_connection *conn,
  5560. const char *path,
  5561. struct file *filep,
  5562. const char *mime_type)
  5563. {
  5564. char date[64], lm[64], etag[64];
  5565. char range[128]; /* large enough, so there will be no overflow */
  5566. const char *msg = "OK", *hdr;
  5567. time_t curtime = time(NULL);
  5568. int64_t cl, r1, r2;
  5569. struct vec mime_vec;
  5570. int n, truncated;
  5571. char gz_path[PATH_MAX];
  5572. const char *encoding = "";
  5573. const char *cors1, *cors2, *cors3;
  5574. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5575. return;
  5576. }
  5577. if (mime_type == NULL) {
  5578. get_mime_type(conn->ctx, path, &mime_vec);
  5579. } else {
  5580. mime_vec.ptr = mime_type;
  5581. mime_vec.len = strlen(mime_type);
  5582. }
  5583. if (filep->size > INT64_MAX) {
  5584. send_http_error(conn,
  5585. 500,
  5586. "Error: File size is too large to send\n%" INT64_FMT,
  5587. filep->size);
  5588. }
  5589. cl = (int64_t)filep->size;
  5590. conn->status_code = 200;
  5591. range[0] = '\0';
  5592. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5593. * it's important to rewrite the filename after resolving
  5594. * the mime type from it, to preserve the actual file's type */
  5595. if (filep->gzipped) {
  5596. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5597. if (truncated) {
  5598. send_http_error(conn,
  5599. 500,
  5600. "Error: Path of zipped file too long (%s)",
  5601. path);
  5602. return;
  5603. }
  5604. path = gz_path;
  5605. encoding = "Content-Encoding: gzip\r\n";
  5606. }
  5607. if (!mg_fopen(conn, path, "rb", filep)) {
  5608. send_http_error(conn,
  5609. 500,
  5610. "Error: Cannot open file\nfopen(%s): %s",
  5611. path,
  5612. strerror(ERRNO));
  5613. return;
  5614. }
  5615. fclose_on_exec(filep, conn);
  5616. /* If Range: header specified, act accordingly */
  5617. r1 = r2 = 0;
  5618. hdr = mg_get_header(conn, "Range");
  5619. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5620. && r2 >= 0) {
  5621. /* actually, range requests don't play well with a pre-gzipped
  5622. * file (since the range is specified in the uncompressed space) */
  5623. if (filep->gzipped) {
  5624. send_http_error(
  5625. conn,
  5626. 501,
  5627. "%s",
  5628. "Error: Range requests in gzipped files are not supported");
  5629. mg_fclose(filep);
  5630. return;
  5631. }
  5632. conn->status_code = 206;
  5633. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5634. mg_snprintf(conn,
  5635. NULL, /* range buffer is big enough */
  5636. range,
  5637. sizeof(range),
  5638. "Content-Range: bytes "
  5639. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5640. r1,
  5641. r1 + cl - 1,
  5642. filep->size);
  5643. msg = "Partial Content";
  5644. }
  5645. hdr = mg_get_header(conn, "Origin");
  5646. if (hdr) {
  5647. /* Cross-origin resource sharing (CORS), see
  5648. * http://www.html5rocks.com/en/tutorials/cors/,
  5649. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5650. * preflight is not supported for files. */
  5651. cors1 = "Access-Control-Allow-Origin: ";
  5652. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5653. cors3 = "\r\n";
  5654. } else {
  5655. cors1 = cors2 = cors3 = "";
  5656. }
  5657. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5658. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5659. gmt_time_string(date, sizeof(date), &curtime);
  5660. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5661. construct_etag(etag, sizeof(etag), filep);
  5662. (void)mg_printf(conn,
  5663. "HTTP/1.1 %d %s\r\n"
  5664. "%s%s%s"
  5665. "Date: %s\r\n",
  5666. conn->status_code,
  5667. msg,
  5668. cors1,
  5669. cors2,
  5670. cors3,
  5671. date);
  5672. send_static_cache_header(conn);
  5673. (void)mg_printf(conn,
  5674. "Last-Modified: %s\r\n"
  5675. "Etag: %s\r\n"
  5676. "Content-Type: %.*s\r\n"
  5677. "Content-Length: %" INT64_FMT "\r\n"
  5678. "Connection: %s\r\n"
  5679. "Accept-Ranges: bytes\r\n"
  5680. "%s%s\r\n",
  5681. lm,
  5682. etag,
  5683. (int)mime_vec.len,
  5684. mime_vec.ptr,
  5685. cl,
  5686. suggest_connection_header(conn),
  5687. range,
  5688. encoding);
  5689. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5690. send_file_data(conn, filep, r1, cl);
  5691. }
  5692. mg_fclose(filep);
  5693. }
  5694. void
  5695. mg_send_file(struct mg_connection *conn, const char *path)
  5696. {
  5697. mg_send_mime_file(conn, path, NULL);
  5698. }
  5699. void
  5700. mg_send_mime_file(struct mg_connection *conn,
  5701. const char *path,
  5702. const char *mime_type)
  5703. {
  5704. struct file file = STRUCT_FILE_INITIALIZER;
  5705. if (mg_stat(conn, path, &file)) {
  5706. if (file.is_directory) {
  5707. if (!conn) {
  5708. return;
  5709. }
  5710. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5711. "yes")) {
  5712. handle_directory_request(conn, path);
  5713. } else {
  5714. send_http_error(conn,
  5715. 403,
  5716. "%s",
  5717. "Error: Directory listing denied");
  5718. }
  5719. } else {
  5720. handle_static_file_request(conn, path, &file, mime_type);
  5721. }
  5722. } else {
  5723. send_http_error(conn, 404, "%s", "Error: File not found");
  5724. }
  5725. }
  5726. /* For a given PUT path, create all intermediate subdirectories.
  5727. * Return 0 if the path itself is a directory.
  5728. * Return 1 if the path leads to a file.
  5729. * Return -1 for if the path is too long.
  5730. * Return -2 if path can not be created.
  5731. */
  5732. static int
  5733. put_dir(struct mg_connection *conn, const char *path)
  5734. {
  5735. char buf[PATH_MAX];
  5736. const char *s, *p;
  5737. struct file file = STRUCT_FILE_INITIALIZER;
  5738. size_t len;
  5739. int res = 1;
  5740. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5741. len = (size_t)(p - path);
  5742. if (len >= sizeof(buf)) {
  5743. /* path too long */
  5744. res = -1;
  5745. break;
  5746. }
  5747. memcpy(buf, path, len);
  5748. buf[len] = '\0';
  5749. /* Try to create intermediate directory */
  5750. DEBUG_TRACE("mkdir(%s)", buf);
  5751. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  5752. /* path does not exixt and can not be created */
  5753. res = -2;
  5754. break;
  5755. }
  5756. /* Is path itself a directory? */
  5757. if (p[1] == '\0') {
  5758. res = 0;
  5759. }
  5760. }
  5761. return res;
  5762. }
  5763. static void
  5764. remove_bad_file(const struct mg_connection *conn, const char *path)
  5765. {
  5766. int r = mg_remove(conn, path);
  5767. if (r != 0) {
  5768. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5769. }
  5770. }
  5771. long long
  5772. mg_store_body(struct mg_connection *conn, const char *path)
  5773. {
  5774. char buf[MG_BUF_LEN];
  5775. long long len = 0;
  5776. int ret, n;
  5777. struct file fi;
  5778. if (conn->consumed_content != 0) {
  5779. mg_cry(conn, "%s: Contents already consumed", __func__);
  5780. return -11;
  5781. }
  5782. ret = put_dir(conn, path);
  5783. if (ret < 0) {
  5784. /* -1 for path too long,
  5785. * -2 for path can not be created. */
  5786. return ret;
  5787. }
  5788. if (ret != 1) {
  5789. /* Return 0 means, path itself is a directory. */
  5790. return 0;
  5791. }
  5792. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5793. return -12;
  5794. }
  5795. ret = mg_read(conn, buf, sizeof(buf));
  5796. while (ret > 0) {
  5797. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5798. if (n != ret) {
  5799. mg_fclose(&fi);
  5800. remove_bad_file(conn, path);
  5801. return -13;
  5802. }
  5803. ret = mg_read(conn, buf, sizeof(buf));
  5804. }
  5805. /* TODO: mg_fclose should return an error,
  5806. * and every caller should check and handle it. */
  5807. if (fclose(fi.fp) != 0) {
  5808. remove_bad_file(conn, path);
  5809. return -14;
  5810. }
  5811. return len;
  5812. }
  5813. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5814. * where parsing stopped. */
  5815. static void
  5816. parse_http_headers(char **buf, struct mg_request_info *ri)
  5817. {
  5818. int i;
  5819. if (!ri) {
  5820. return;
  5821. }
  5822. ri->num_headers = 0;
  5823. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5824. char *dp = *buf;
  5825. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5826. dp++;
  5827. }
  5828. if (!*dp) {
  5829. /* neither : nor \r\n. This is not a valid field. */
  5830. break;
  5831. }
  5832. if (*dp == '\r') {
  5833. if (dp[1] == '\n') {
  5834. /* \r\n */
  5835. ri->http_headers[i].name = *buf;
  5836. ri->http_headers[i].value = 0;
  5837. *buf = dp;
  5838. } else {
  5839. /* stray \r. This is not valid. */
  5840. break;
  5841. }
  5842. } else {
  5843. /* (*dp == ':') */
  5844. *dp = 0;
  5845. ri->http_headers[i].name = *buf;
  5846. do {
  5847. dp++;
  5848. } while (*dp == ' ');
  5849. ri->http_headers[i].value = dp;
  5850. *buf = strstr(dp, "\r\n");
  5851. }
  5852. ri->num_headers = i + 1;
  5853. if (*buf) {
  5854. (*buf)[0] = 0;
  5855. (*buf)[1] = 0;
  5856. *buf += 2;
  5857. } else {
  5858. *buf = dp;
  5859. break;
  5860. }
  5861. if (*buf[0] == '\r') {
  5862. /* This is the end of the header */
  5863. break;
  5864. }
  5865. }
  5866. }
  5867. static int
  5868. is_valid_http_method(const char *method)
  5869. {
  5870. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5871. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5872. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5873. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5874. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5875. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5876. /* TRACE method (RFC 2616) is not supported for security reasons */
  5877. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5878. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5879. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5880. /* Unsupported WEBDAV Methods: */
  5881. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5882. /* + 11 methods from RFC 3253 */
  5883. /* ORDERPATCH (RFC 3648) */
  5884. /* ACL (RFC 3744) */
  5885. /* SEARCH (RFC 5323) */
  5886. /* + MicroSoft extensions
  5887. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5888. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5889. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5890. }
  5891. /* Parse HTTP request, fill in mg_request_info structure.
  5892. * This function modifies the buffer by NUL-terminating
  5893. * HTTP request components, header names and header values. */
  5894. static int
  5895. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5896. {
  5897. int is_request, request_length;
  5898. if (!ri) {
  5899. return 0;
  5900. }
  5901. request_length = get_request_len(buf, len);
  5902. if (request_length > 0) {
  5903. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5904. * remote_port */
  5905. ri->remote_user = ri->request_method = ri->request_uri =
  5906. ri->http_version = NULL;
  5907. ri->num_headers = 0;
  5908. buf[request_length - 1] = '\0';
  5909. /* RFC says that all initial whitespaces should be ingored */
  5910. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5911. buf++;
  5912. }
  5913. ri->request_method = skip(&buf, " ");
  5914. ri->request_uri = skip(&buf, " ");
  5915. ri->http_version = skip(&buf, "\r\n");
  5916. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5917. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5918. is_request = is_valid_http_method(ri->request_method);
  5919. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5920. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5921. request_length = -1;
  5922. } else {
  5923. if (is_request) {
  5924. ri->http_version += 5;
  5925. }
  5926. parse_http_headers(&buf, ri);
  5927. }
  5928. }
  5929. return request_length;
  5930. }
  5931. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5932. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5933. * buffer (which marks the end of HTTP request). Buffer buf may already
  5934. * have some data. The length of the data is stored in nread.
  5935. * Upon every read operation, increase nread by the number of bytes read. */
  5936. static int
  5937. read_request(FILE *fp,
  5938. struct mg_connection *conn,
  5939. char *buf,
  5940. int bufsiz,
  5941. int *nread)
  5942. {
  5943. int request_len, n = 0;
  5944. struct timespec last_action_time;
  5945. double request_timeout;
  5946. if (!conn) {
  5947. return 0;
  5948. }
  5949. memset(&last_action_time, 0, sizeof(last_action_time));
  5950. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5951. /* value of request_timeout is in seconds, config in milliseconds */
  5952. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5953. } else {
  5954. request_timeout = -1.0;
  5955. }
  5956. request_len = get_request_len(buf, *nread);
  5957. /* first time reading from this connection */
  5958. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5959. while (
  5960. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5961. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5962. <= request_timeout) || (request_timeout < 0))
  5963. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5964. > 0)) {
  5965. *nread += n;
  5966. /* assert(*nread <= bufsiz); */
  5967. if (*nread > bufsiz) {
  5968. return -2;
  5969. }
  5970. request_len = get_request_len(buf, *nread);
  5971. if (request_timeout > 0.0) {
  5972. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5973. }
  5974. }
  5975. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5976. }
  5977. #if !defined(NO_FILES)
  5978. /* For given directory path, substitute it to valid index file.
  5979. * Return 1 if index file has been found, 0 if not found.
  5980. * If the file is found, it's stats is returned in stp. */
  5981. static int
  5982. substitute_index_file(struct mg_connection *conn,
  5983. char *path,
  5984. size_t path_len,
  5985. struct file *filep)
  5986. {
  5987. if (conn && conn->ctx) {
  5988. const char *list = conn->ctx->config[INDEX_FILES];
  5989. struct file file = STRUCT_FILE_INITIALIZER;
  5990. struct vec filename_vec;
  5991. size_t n = strlen(path);
  5992. int found = 0;
  5993. /* The 'path' given to us points to the directory. Remove all trailing
  5994. * directory separator characters from the end of the path, and
  5995. * then append single directory separator character. */
  5996. while (n > 0 && path[n - 1] == '/') {
  5997. n--;
  5998. }
  5999. path[n] = '/';
  6000. /* Traverse index files list. For each entry, append it to the given
  6001. * path and see if the file exists. If it exists, break the loop */
  6002. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6003. /* Ignore too long entries that may overflow path buffer */
  6004. if (filename_vec.len > path_len - (n + 2)) {
  6005. continue;
  6006. }
  6007. /* Prepare full path to the index file */
  6008. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6009. /* Does it exist? */
  6010. if (mg_stat(conn, path, &file)) {
  6011. /* Yes it does, break the loop */
  6012. *filep = file;
  6013. found = 1;
  6014. break;
  6015. }
  6016. }
  6017. /* If no index file exists, restore directory path */
  6018. if (!found) {
  6019. path[n] = '\0';
  6020. }
  6021. return found;
  6022. }
  6023. return 0;
  6024. }
  6025. #endif
  6026. #if !defined(NO_CACHING)
  6027. /* Return True if we should reply 304 Not Modified. */
  6028. static int
  6029. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6030. {
  6031. char etag[64];
  6032. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6033. const char *inm = mg_get_header(conn, "If-None-Match");
  6034. construct_etag(etag, sizeof(etag), filep);
  6035. if (!filep) {
  6036. return 0;
  6037. }
  6038. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6039. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6040. }
  6041. #endif /* !NO_CACHING */
  6042. #if !defined(NO_CGI) || !defined(NO_FILES)
  6043. static int
  6044. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6045. {
  6046. const char *expect, *body;
  6047. char buf[MG_BUF_LEN];
  6048. int to_read, nread, success = 0;
  6049. int64_t buffered_len;
  6050. double timeout = -1.0;
  6051. if (!conn) {
  6052. return 0;
  6053. }
  6054. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6055. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6056. }
  6057. expect = mg_get_header(conn, "Expect");
  6058. /* assert(fp != NULL); */
  6059. if (!fp) {
  6060. send_http_error(conn, 500, "%s", "Error: NULL File");
  6061. return 0;
  6062. }
  6063. if (conn->content_len == -1 && !conn->is_chunked) {
  6064. /* Content length is not specified by the client. */
  6065. send_http_error(conn,
  6066. 411,
  6067. "%s",
  6068. "Error: Client did not specify content length");
  6069. } else if ((expect != NULL)
  6070. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6071. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6072. send_http_error(conn,
  6073. 417,
  6074. "Error: Can not fulfill expectation %s",
  6075. expect);
  6076. } else {
  6077. if (expect != NULL) {
  6078. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6079. conn->status_code = 100;
  6080. } else {
  6081. conn->status_code = 200;
  6082. }
  6083. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6084. - conn->consumed_content;
  6085. /* assert(buffered_len >= 0); */
  6086. /* assert(conn->consumed_content == 0); */
  6087. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6088. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6089. return 0;
  6090. }
  6091. if (buffered_len > 0) {
  6092. if ((int64_t)buffered_len > conn->content_len) {
  6093. buffered_len = (int)conn->content_len;
  6094. }
  6095. body = conn->buf + conn->request_len + conn->consumed_content;
  6096. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6097. conn->consumed_content += buffered_len;
  6098. }
  6099. nread = 0;
  6100. while (conn->consumed_content < conn->content_len) {
  6101. to_read = sizeof(buf);
  6102. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6103. to_read = (int)(conn->content_len - conn->consumed_content);
  6104. }
  6105. nread = pull(NULL, conn, buf, to_read, timeout);
  6106. if (nread <= 0
  6107. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6108. break;
  6109. }
  6110. conn->consumed_content += nread;
  6111. }
  6112. if (conn->consumed_content == conn->content_len) {
  6113. success = (nread >= 0);
  6114. }
  6115. /* Each error code path in this function must send an error */
  6116. if (!success) {
  6117. /* NOTE: Maybe some data has already been sent. */
  6118. /* TODO (low): If some data has been sent, a correct error
  6119. * reply can no longer be sent, so just close the connection */
  6120. send_http_error(conn, 500, "%s", "");
  6121. }
  6122. }
  6123. return success;
  6124. }
  6125. #endif
  6126. #if !defined(NO_CGI)
  6127. /* This structure helps to create an environment for the spawned CGI program.
  6128. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6129. * last element must be NULL.
  6130. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6131. * strings must reside in a contiguous buffer. The end of the buffer is
  6132. * marked by two '\0' characters.
  6133. * We satisfy both worlds: we create an envp array (which is vars), all
  6134. * entries are actually pointers inside buf. */
  6135. struct cgi_environment {
  6136. struct mg_connection *conn;
  6137. /* Data block */
  6138. char *buf; /* Environment buffer */
  6139. size_t buflen; /* Space available in buf */
  6140. size_t bufused; /* Space taken in buf */
  6141. /* Index block */
  6142. char **var; /* char **envp */
  6143. size_t varlen; /* Number of variables available in var */
  6144. size_t varused; /* Number of variables stored in var */
  6145. };
  6146. static void addenv(struct cgi_environment *env,
  6147. PRINTF_FORMAT_STRING(const char *fmt),
  6148. ...) PRINTF_ARGS(2, 3);
  6149. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6150. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6151. static void
  6152. addenv(struct cgi_environment *env, const char *fmt, ...)
  6153. {
  6154. size_t n, space;
  6155. int truncated;
  6156. char *added;
  6157. va_list ap;
  6158. /* Calculate how much space is left in the buffer */
  6159. space = (env->buflen - env->bufused);
  6160. /* Calculate an estimate for the required space */
  6161. n = strlen(fmt) + 2 + 128;
  6162. do {
  6163. if (space <= n) {
  6164. /* Allocate new buffer */
  6165. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6166. added = (char *)mg_realloc(env->buf, n);
  6167. if (!added) {
  6168. /* Out of memory */
  6169. mg_cry(env->conn,
  6170. "%s: Cannot allocate memory for CGI variable [%s]",
  6171. __func__,
  6172. fmt);
  6173. return;
  6174. }
  6175. env->buf = added;
  6176. env->buflen = n;
  6177. space = (env->buflen - env->bufused);
  6178. }
  6179. /* Make a pointer to the free space int the buffer */
  6180. added = env->buf + env->bufused;
  6181. /* Copy VARIABLE=VALUE\0 string into the free space */
  6182. va_start(ap, fmt);
  6183. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6184. va_end(ap);
  6185. /* Do not add truncated strings to the environment */
  6186. if (truncated) {
  6187. /* Reallocate the buffer */
  6188. space = 0;
  6189. n = 1;
  6190. }
  6191. } while (truncated);
  6192. /* Calculate number of bytes added to the environment */
  6193. n = strlen(added) + 1;
  6194. env->bufused += n;
  6195. /* Now update the variable index */
  6196. space = (env->varlen - env->varused);
  6197. if (space < 2) {
  6198. mg_cry(env->conn,
  6199. "%s: Cannot register CGI variable [%s]",
  6200. __func__,
  6201. fmt);
  6202. return;
  6203. }
  6204. /* Append a pointer to the added string into the envp array */
  6205. env->var[env->varused] = added;
  6206. env->varused++;
  6207. }
  6208. static void
  6209. prepare_cgi_environment(struct mg_connection *conn,
  6210. const char *prog,
  6211. struct cgi_environment *env)
  6212. {
  6213. const char *s;
  6214. struct vec var_vec;
  6215. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6216. int i, truncated;
  6217. if (conn == NULL || prog == NULL || env == NULL) {
  6218. return;
  6219. }
  6220. env->conn = conn;
  6221. env->buflen = CGI_ENVIRONMENT_SIZE;
  6222. env->bufused = 0;
  6223. env->buf = (char *)mg_malloc(env->buflen);
  6224. env->varlen = MAX_CGI_ENVIR_VARS;
  6225. env->varused = 0;
  6226. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6227. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6228. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6229. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6230. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6231. /* Prepare the environment block */
  6232. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6233. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6234. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6235. #if defined(USE_IPV6)
  6236. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6237. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6238. } else
  6239. #endif
  6240. {
  6241. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6242. }
  6243. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6244. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6245. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6246. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6247. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6248. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6249. /* SCRIPT_NAME */
  6250. addenv(env,
  6251. "SCRIPT_NAME=%.*s",
  6252. (int)strlen(conn->request_info.local_uri)
  6253. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6254. conn->request_info.local_uri);
  6255. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6256. if (conn->path_info == NULL) {
  6257. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6258. } else {
  6259. addenv(env,
  6260. "PATH_TRANSLATED=%s%s",
  6261. conn->ctx->config[DOCUMENT_ROOT],
  6262. conn->path_info);
  6263. }
  6264. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6265. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6266. addenv(env, "CONTENT_TYPE=%s", s);
  6267. }
  6268. if (conn->request_info.query_string != NULL) {
  6269. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6270. }
  6271. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6272. addenv(env, "CONTENT_LENGTH=%s", s);
  6273. }
  6274. if ((s = getenv("PATH")) != NULL) {
  6275. addenv(env, "PATH=%s", s);
  6276. }
  6277. if (conn->path_info != NULL) {
  6278. addenv(env, "PATH_INFO=%s", conn->path_info);
  6279. }
  6280. if (conn->status_code > 0) {
  6281. /* CGI error handler should show the status code */
  6282. addenv(env, "STATUS=%d", conn->status_code);
  6283. }
  6284. #if defined(_WIN32)
  6285. if ((s = getenv("COMSPEC")) != NULL) {
  6286. addenv(env, "COMSPEC=%s", s);
  6287. }
  6288. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6289. addenv(env, "SYSTEMROOT=%s", s);
  6290. }
  6291. if ((s = getenv("SystemDrive")) != NULL) {
  6292. addenv(env, "SystemDrive=%s", s);
  6293. }
  6294. if ((s = getenv("ProgramFiles")) != NULL) {
  6295. addenv(env, "ProgramFiles=%s", s);
  6296. }
  6297. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6298. addenv(env, "ProgramFiles(x86)=%s", s);
  6299. }
  6300. #else
  6301. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6302. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6303. }
  6304. #endif /* _WIN32 */
  6305. if ((s = getenv("PERLLIB")) != NULL) {
  6306. addenv(env, "PERLLIB=%s", s);
  6307. }
  6308. if (conn->request_info.remote_user != NULL) {
  6309. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6310. addenv(env, "%s", "AUTH_TYPE=Digest");
  6311. }
  6312. /* Add all headers as HTTP_* variables */
  6313. for (i = 0; i < conn->request_info.num_headers; i++) {
  6314. (void)mg_snprintf(conn,
  6315. &truncated,
  6316. http_var_name,
  6317. sizeof(http_var_name),
  6318. "HTTP_%s",
  6319. conn->request_info.http_headers[i].name);
  6320. if (truncated) {
  6321. mg_cry(conn,
  6322. "%s: HTTP header variable too long [%s]",
  6323. __func__,
  6324. conn->request_info.http_headers[i].name);
  6325. continue;
  6326. }
  6327. /* Convert variable name into uppercase, and change - to _ */
  6328. for (p = http_var_name; *p != '\0'; p++) {
  6329. if (*p == '-') {
  6330. *p = '_';
  6331. }
  6332. *p = (char)toupper(*(unsigned char *)p);
  6333. }
  6334. addenv(env,
  6335. "%s=%s",
  6336. http_var_name,
  6337. conn->request_info.http_headers[i].value);
  6338. }
  6339. /* Add user-specified variables */
  6340. s = conn->ctx->config[CGI_ENVIRONMENT];
  6341. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6342. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6343. }
  6344. env->var[env->varused] = NULL;
  6345. env->buf[env->bufused] = '\0';
  6346. }
  6347. static void
  6348. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6349. {
  6350. char *buf;
  6351. size_t buflen;
  6352. int headers_len, data_len, i, truncated;
  6353. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6354. const char *status, *status_text, *connection_state;
  6355. char *pbuf, dir[PATH_MAX], *p;
  6356. struct mg_request_info ri;
  6357. struct cgi_environment blk;
  6358. FILE *in = NULL, *out = NULL, *err = NULL;
  6359. struct file fout = STRUCT_FILE_INITIALIZER;
  6360. pid_t pid = (pid_t)-1;
  6361. if (conn == NULL) {
  6362. return;
  6363. }
  6364. buf = NULL;
  6365. buflen = 16384;
  6366. prepare_cgi_environment(conn, prog, &blk);
  6367. /* CGI must be executed in its own directory. 'dir' must point to the
  6368. * directory containing executable program, 'p' must point to the
  6369. * executable program name relative to 'dir'. */
  6370. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6371. if (truncated) {
  6372. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6373. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6374. goto done;
  6375. }
  6376. if ((p = strrchr(dir, '/')) != NULL) {
  6377. *p++ = '\0';
  6378. } else {
  6379. dir[0] = '.', dir[1] = '\0';
  6380. p = (char *)prog;
  6381. }
  6382. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6383. status = strerror(ERRNO);
  6384. mg_cry(conn,
  6385. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6386. prog,
  6387. status);
  6388. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6389. goto done;
  6390. }
  6391. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6392. if (pid == (pid_t)-1) {
  6393. status = strerror(ERRNO);
  6394. mg_cry(conn,
  6395. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6396. prog,
  6397. status);
  6398. send_http_error(conn,
  6399. 500,
  6400. "Error: Cannot spawn CGI process [%s]: %s",
  6401. prog,
  6402. status);
  6403. goto done;
  6404. }
  6405. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6406. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6407. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6408. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6409. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6410. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6411. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6412. /* Parent closes only one side of the pipes.
  6413. * If we don't mark them as closed, close() attempt before
  6414. * return from this function throws an exception on Windows.
  6415. * Windows does not like when closed descriptor is closed again. */
  6416. (void)close(fdin[0]);
  6417. (void)close(fdout[1]);
  6418. (void)close(fderr[1]);
  6419. fdin[0] = fdout[1] = fderr[1] = -1;
  6420. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6421. status = strerror(ERRNO);
  6422. mg_cry(conn,
  6423. "Error: CGI program \"%s\": Can not open stdin: %s",
  6424. prog,
  6425. status);
  6426. send_http_error(conn,
  6427. 500,
  6428. "Error: CGI can not open fdin\nfopen: %s",
  6429. status);
  6430. goto done;
  6431. }
  6432. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6433. status = strerror(ERRNO);
  6434. mg_cry(conn,
  6435. "Error: CGI program \"%s\": Can not open stdout: %s",
  6436. prog,
  6437. status);
  6438. send_http_error(conn,
  6439. 500,
  6440. "Error: CGI can not open fdout\nfopen: %s",
  6441. status);
  6442. goto done;
  6443. }
  6444. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6445. status = strerror(ERRNO);
  6446. mg_cry(conn,
  6447. "Error: CGI program \"%s\": Can not open stderr: %s",
  6448. prog,
  6449. status);
  6450. send_http_error(conn,
  6451. 500,
  6452. "Error: CGI can not open fdout\nfopen: %s",
  6453. status);
  6454. goto done;
  6455. }
  6456. setbuf(in, NULL);
  6457. setbuf(out, NULL);
  6458. setbuf(err, NULL);
  6459. fout.fp = out;
  6460. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6461. /* This is a POST/PUT request, or another request with body data. */
  6462. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6463. /* Error sending the body data */
  6464. mg_cry(conn,
  6465. "Error: CGI program \"%s\": Forward body data failed",
  6466. prog);
  6467. goto done;
  6468. }
  6469. }
  6470. /* Close so child gets an EOF. */
  6471. fclose(in);
  6472. in = NULL;
  6473. fdin[1] = -1;
  6474. /* Now read CGI reply into a buffer. We need to set correct
  6475. * status code, thus we need to see all HTTP headers first.
  6476. * Do not send anything back to client, until we buffer in all
  6477. * HTTP headers. */
  6478. data_len = 0;
  6479. buf = (char *)mg_malloc(buflen);
  6480. if (buf == NULL) {
  6481. send_http_error(conn,
  6482. 500,
  6483. "Error: Not enough memory for CGI buffer (%u bytes)",
  6484. (unsigned int)buflen);
  6485. mg_cry(conn,
  6486. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6487. "bytes)",
  6488. prog,
  6489. (unsigned int)buflen);
  6490. goto done;
  6491. }
  6492. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6493. if (headers_len <= 0) {
  6494. /* Could not parse the CGI response. Check if some error message on
  6495. * stderr. */
  6496. i = pull_all(err, conn, buf, (int)buflen);
  6497. if (i > 0) {
  6498. mg_cry(conn,
  6499. "Error: CGI program \"%s\" sent error "
  6500. "message: [%.*s]",
  6501. prog,
  6502. i,
  6503. buf);
  6504. send_http_error(conn,
  6505. 500,
  6506. "Error: CGI program \"%s\" sent error "
  6507. "message: [%.*s]",
  6508. prog,
  6509. i,
  6510. buf);
  6511. } else {
  6512. mg_cry(conn,
  6513. "Error: CGI program sent malformed or too big "
  6514. "(>%u bytes) HTTP headers: [%.*s]",
  6515. (unsigned)buflen,
  6516. data_len,
  6517. buf);
  6518. send_http_error(conn,
  6519. 500,
  6520. "Error: CGI program sent malformed or too big "
  6521. "(>%u bytes) HTTP headers: [%.*s]",
  6522. (unsigned)buflen,
  6523. data_len,
  6524. buf);
  6525. }
  6526. goto done;
  6527. }
  6528. pbuf = buf;
  6529. buf[headers_len - 1] = '\0';
  6530. parse_http_headers(&pbuf, &ri);
  6531. /* Make up and send the status line */
  6532. status_text = "OK";
  6533. if ((status = get_header(&ri, "Status")) != NULL) {
  6534. conn->status_code = atoi(status);
  6535. status_text = status;
  6536. while (isdigit(*(const unsigned char *)status_text)
  6537. || *status_text == ' ') {
  6538. status_text++;
  6539. }
  6540. } else if (get_header(&ri, "Location") != NULL) {
  6541. conn->status_code = 302;
  6542. } else {
  6543. conn->status_code = 200;
  6544. }
  6545. connection_state = get_header(&ri, "Connection");
  6546. if (!header_has_option(connection_state, "keep-alive")) {
  6547. conn->must_close = 1;
  6548. }
  6549. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6550. /* Send headers */
  6551. for (i = 0; i < ri.num_headers; i++) {
  6552. mg_printf(conn,
  6553. "%s: %s\r\n",
  6554. ri.http_headers[i].name,
  6555. ri.http_headers[i].value);
  6556. }
  6557. mg_write(conn, "\r\n", 2);
  6558. /* Send chunk of data that may have been read after the headers */
  6559. conn->num_bytes_sent +=
  6560. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6561. /* Read the rest of CGI output and send to the client */
  6562. send_file_data(conn, &fout, 0, INT64_MAX);
  6563. done:
  6564. mg_free(blk.var);
  6565. mg_free(blk.buf);
  6566. if (pid != (pid_t)-1) {
  6567. kill(pid, SIGKILL);
  6568. #if !defined(_WIN32)
  6569. {
  6570. int st;
  6571. while (waitpid(pid, &st, 0) != -1)
  6572. ; /* clean zombies */
  6573. }
  6574. #endif
  6575. }
  6576. if (fdin[0] != -1) {
  6577. close(fdin[0]);
  6578. }
  6579. if (fdout[1] != -1) {
  6580. close(fdout[1]);
  6581. }
  6582. if (in != NULL) {
  6583. fclose(in);
  6584. } else if (fdin[1] != -1) {
  6585. close(fdin[1]);
  6586. }
  6587. if (out != NULL) {
  6588. fclose(out);
  6589. } else if (fdout[0] != -1) {
  6590. close(fdout[0]);
  6591. }
  6592. if (err != NULL) {
  6593. fclose(err);
  6594. } else if (fderr[0] != -1) {
  6595. close(fderr[0]);
  6596. }
  6597. if (buf != NULL) {
  6598. mg_free(buf);
  6599. }
  6600. }
  6601. #endif /* !NO_CGI */
  6602. #if !defined(NO_FILES)
  6603. static void
  6604. mkcol(struct mg_connection *conn, const char *path)
  6605. {
  6606. int rc, body_len;
  6607. struct de de;
  6608. char date[64];
  6609. time_t curtime = time(NULL);
  6610. if (conn == NULL) {
  6611. return;
  6612. }
  6613. /* TODO (mid): Check the send_http_error situations in this function */
  6614. memset(&de.file, 0, sizeof(de.file));
  6615. if (!mg_stat(conn, path, &de.file)) {
  6616. mg_cry(conn,
  6617. "%s: mg_stat(%s) failed: %s",
  6618. __func__,
  6619. path,
  6620. strerror(ERRNO));
  6621. }
  6622. if (de.file.last_modified) {
  6623. /* TODO (high): This check does not seem to make any sense ! */
  6624. send_http_error(
  6625. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6626. return;
  6627. }
  6628. body_len = conn->data_len - conn->request_len;
  6629. if (body_len > 0) {
  6630. send_http_error(
  6631. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6632. return;
  6633. }
  6634. rc = mg_mkdir(conn, path, 0755);
  6635. if (rc == 0) {
  6636. conn->status_code = 201;
  6637. gmt_time_string(date, sizeof(date), &curtime);
  6638. mg_printf(conn,
  6639. "HTTP/1.1 %d Created\r\n"
  6640. "Date: %s\r\n",
  6641. conn->status_code,
  6642. date);
  6643. send_static_cache_header(conn);
  6644. mg_printf(conn,
  6645. "Content-Length: 0\r\n"
  6646. "Connection: %s\r\n\r\n",
  6647. suggest_connection_header(conn));
  6648. } else if (rc == -1) {
  6649. if (errno == EEXIST) {
  6650. send_http_error(
  6651. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6652. } else if (errno == EACCES) {
  6653. send_http_error(
  6654. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6655. } else if (errno == ENOENT) {
  6656. send_http_error(
  6657. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6658. } else {
  6659. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6660. }
  6661. }
  6662. }
  6663. static void
  6664. put_file(struct mg_connection *conn, const char *path)
  6665. {
  6666. struct file file = STRUCT_FILE_INITIALIZER;
  6667. const char *range;
  6668. int64_t r1, r2;
  6669. int rc;
  6670. char date[64];
  6671. time_t curtime = time(NULL);
  6672. if (conn == NULL) {
  6673. return;
  6674. }
  6675. if (mg_stat(conn, path, &file)) {
  6676. /* File already exists */
  6677. conn->status_code = 200;
  6678. if (file.is_directory) {
  6679. /* This is an already existing directory,
  6680. * so there is nothing to do for the server. */
  6681. rc = 0;
  6682. } else {
  6683. /* File exists and is not a directory. */
  6684. /* Can it be replaced? */
  6685. if (file.membuf != NULL) {
  6686. /* This is an "in-memory" file, that can not be replaced */
  6687. send_http_error(
  6688. conn,
  6689. 405,
  6690. "Error: Put not possible\nReplacing %s is not supported",
  6691. path);
  6692. return;
  6693. }
  6694. /* Check if the server may write this file */
  6695. if (access(path, W_OK) == 0) {
  6696. /* Access granted */
  6697. conn->status_code = 200;
  6698. rc = 1;
  6699. } else {
  6700. send_http_error(
  6701. conn,
  6702. 403,
  6703. "Error: Put not possible\nReplacing %s is not allowed",
  6704. path);
  6705. return;
  6706. }
  6707. }
  6708. } else {
  6709. /* File should be created */
  6710. conn->status_code = 201;
  6711. rc = put_dir(conn, path);
  6712. }
  6713. if (rc == 0) {
  6714. /* put_dir returns 0 if path is a directory */
  6715. gmt_time_string(date, sizeof(date), &curtime);
  6716. mg_printf(conn,
  6717. "HTTP/1.1 %d %s\r\n",
  6718. conn->status_code,
  6719. mg_get_response_code_text(conn->status_code, NULL));
  6720. send_no_cache_header(conn);
  6721. mg_printf(conn,
  6722. "Date: %s\r\n"
  6723. "Content-Length: 0\r\n"
  6724. "Connection: %s\r\n\r\n",
  6725. date,
  6726. suggest_connection_header(conn));
  6727. /* Request to create a directory has been fulfilled successfully.
  6728. * No need to put a file. */
  6729. return;
  6730. }
  6731. if (rc == -1) {
  6732. /* put_dir returns -1 if the path is too long */
  6733. send_http_error(conn,
  6734. 414,
  6735. "Error: Path too long\nput_dir(%s): %s",
  6736. path,
  6737. strerror(ERRNO));
  6738. return;
  6739. }
  6740. if (rc == -2) {
  6741. /* put_dir returns -2 if the directory can not be created */
  6742. send_http_error(conn,
  6743. 500,
  6744. "Error: Can not create directory\nput_dir(%s): %s",
  6745. path,
  6746. strerror(ERRNO));
  6747. return;
  6748. }
  6749. /* A file should be created or overwritten. */
  6750. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6751. mg_fclose(&file);
  6752. send_http_error(conn,
  6753. 500,
  6754. "Error: Can not create file\nfopen(%s): %s",
  6755. path,
  6756. strerror(ERRNO));
  6757. return;
  6758. }
  6759. fclose_on_exec(&file, conn);
  6760. range = mg_get_header(conn, "Content-Range");
  6761. r1 = r2 = 0;
  6762. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6763. conn->status_code = 206; /* Partial content */
  6764. fseeko(file.fp, r1, SEEK_SET);
  6765. }
  6766. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6767. /* forward_body_data failed.
  6768. * The error code has already been sent to the client,
  6769. * and conn->status_code is already set. */
  6770. mg_fclose(&file);
  6771. return;
  6772. }
  6773. gmt_time_string(date, sizeof(date), &curtime);
  6774. mg_printf(conn,
  6775. "HTTP/1.1 %d %s\r\n",
  6776. conn->status_code,
  6777. mg_get_response_code_text(conn->status_code, NULL));
  6778. send_no_cache_header(conn);
  6779. mg_printf(conn,
  6780. "Date: %s\r\n"
  6781. "Content-Length: 0\r\n"
  6782. "Connection: %s\r\n\r\n",
  6783. date,
  6784. suggest_connection_header(conn));
  6785. mg_fclose(&file);
  6786. }
  6787. static void
  6788. delete_file(struct mg_connection *conn, const char *path)
  6789. {
  6790. struct de de;
  6791. memset(&de.file, 0, sizeof(de.file));
  6792. if (!mg_stat(conn, path, &de.file)) {
  6793. /* mg_stat returns 0 if the file does not exist */
  6794. send_http_error(conn,
  6795. 404,
  6796. "Error: Cannot delete file\nFile %s not found",
  6797. path);
  6798. return;
  6799. }
  6800. if (de.file.membuf != NULL) {
  6801. /* the file is cached in memory */
  6802. send_http_error(
  6803. conn,
  6804. 405,
  6805. "Error: Delete not possible\nDeleting %s is not supported",
  6806. path);
  6807. return;
  6808. }
  6809. if (de.file.is_directory) {
  6810. if (remove_directory(conn, path)) {
  6811. /* Delete is successful: Return 204 without content. */
  6812. send_http_error(conn, 204, "%s", "");
  6813. } else {
  6814. /* Delete is not successful: Return 500 (Server error). */
  6815. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6816. }
  6817. return;
  6818. }
  6819. /* This is an existing file (not a directory).
  6820. * Check if write permission is granted. */
  6821. if (access(path, W_OK) != 0) {
  6822. /* File is read only */
  6823. send_http_error(
  6824. conn,
  6825. 403,
  6826. "Error: Delete not possible\nDeleting %s is not allowed",
  6827. path);
  6828. return;
  6829. }
  6830. /* Try to delete it. */
  6831. if (mg_remove(conn, path) == 0) {
  6832. /* Delete was successful: Return 204 without content. */
  6833. send_http_error(conn, 204, "%s", "");
  6834. } else {
  6835. /* Delete not successful (file locked). */
  6836. send_http_error(conn,
  6837. 423,
  6838. "Error: Cannot delete file\nremove(%s): %s",
  6839. path,
  6840. strerror(ERRNO));
  6841. }
  6842. }
  6843. #endif /* !NO_FILES */
  6844. static void
  6845. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6846. static void
  6847. do_ssi_include(struct mg_connection *conn,
  6848. const char *ssi,
  6849. char *tag,
  6850. int include_level)
  6851. {
  6852. char file_name[MG_BUF_LEN], path[512], *p;
  6853. struct file file = STRUCT_FILE_INITIALIZER;
  6854. size_t len;
  6855. int truncated = 0;
  6856. if (conn == NULL) {
  6857. return;
  6858. }
  6859. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6860. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6861. * always < MG_BUF_LEN. */
  6862. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6863. /* File name is relative to the webserver root */
  6864. file_name[511] = 0;
  6865. (void)mg_snprintf(conn,
  6866. &truncated,
  6867. path,
  6868. sizeof(path),
  6869. "%s/%s",
  6870. conn->ctx->config[DOCUMENT_ROOT],
  6871. file_name);
  6872. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6873. /* File name is relative to the webserver working directory
  6874. * or it is absolute system path */
  6875. file_name[511] = 0;
  6876. (void)
  6877. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6878. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6879. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6880. /* File name is relative to the currect document */
  6881. file_name[511] = 0;
  6882. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6883. if (!truncated) {
  6884. if ((p = strrchr(path, '/')) != NULL) {
  6885. p[1] = '\0';
  6886. }
  6887. len = strlen(path);
  6888. (void)mg_snprintf(conn,
  6889. &truncated,
  6890. path + len,
  6891. sizeof(path) - len,
  6892. "%s",
  6893. file_name);
  6894. }
  6895. } else {
  6896. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6897. return;
  6898. }
  6899. if (truncated) {
  6900. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6901. return;
  6902. }
  6903. if (!mg_fopen(conn, path, "rb", &file)) {
  6904. mg_cry(conn,
  6905. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6906. tag,
  6907. path,
  6908. strerror(ERRNO));
  6909. } else {
  6910. fclose_on_exec(&file, conn);
  6911. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6912. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6913. path) > 0) {
  6914. send_ssi_file(conn, path, &file, include_level + 1);
  6915. } else {
  6916. send_file_data(conn, &file, 0, INT64_MAX);
  6917. }
  6918. mg_fclose(&file);
  6919. }
  6920. }
  6921. #if !defined(NO_POPEN)
  6922. static void
  6923. do_ssi_exec(struct mg_connection *conn, char *tag)
  6924. {
  6925. char cmd[1024] = "";
  6926. struct file file = STRUCT_FILE_INITIALIZER;
  6927. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6928. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6929. } else {
  6930. cmd[1023] = 0;
  6931. if ((file.fp = popen(cmd, "r")) == NULL) {
  6932. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6933. } else {
  6934. send_file_data(conn, &file, 0, INT64_MAX);
  6935. pclose(file.fp);
  6936. }
  6937. }
  6938. }
  6939. #endif /* !NO_POPEN */
  6940. static int
  6941. mg_fgetc(struct file *filep, int offset)
  6942. {
  6943. if (filep == NULL) {
  6944. return EOF;
  6945. }
  6946. if (filep->membuf != NULL && offset >= 0
  6947. && ((unsigned int)(offset)) < filep->size) {
  6948. return ((const unsigned char *)filep->membuf)[offset];
  6949. } else if (filep->fp != NULL) {
  6950. return fgetc(filep->fp);
  6951. } else {
  6952. return EOF;
  6953. }
  6954. }
  6955. static void
  6956. send_ssi_file(struct mg_connection *conn,
  6957. const char *path,
  6958. struct file *filep,
  6959. int include_level)
  6960. {
  6961. char buf[MG_BUF_LEN];
  6962. int ch, offset, len, in_ssi_tag;
  6963. if (include_level > 10) {
  6964. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6965. return;
  6966. }
  6967. in_ssi_tag = len = offset = 0;
  6968. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6969. if (in_ssi_tag && ch == '>') {
  6970. in_ssi_tag = 0;
  6971. buf[len++] = (char)ch;
  6972. buf[len] = '\0';
  6973. /* assert(len <= (int) sizeof(buf)); */
  6974. if (len > (int)sizeof(buf)) {
  6975. break;
  6976. }
  6977. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6978. /* Not an SSI tag, pass it */
  6979. (void)mg_write(conn, buf, (size_t)len);
  6980. } else {
  6981. if (!memcmp(buf + 5, "include", 7)) {
  6982. do_ssi_include(conn, path, buf + 12, include_level);
  6983. #if !defined(NO_POPEN)
  6984. } else if (!memcmp(buf + 5, "exec", 4)) {
  6985. do_ssi_exec(conn, buf + 9);
  6986. #endif /* !NO_POPEN */
  6987. } else {
  6988. mg_cry(conn,
  6989. "%s: unknown SSI "
  6990. "command: \"%s\"",
  6991. path,
  6992. buf);
  6993. }
  6994. }
  6995. len = 0;
  6996. } else if (in_ssi_tag) {
  6997. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6998. /* Not an SSI tag */
  6999. in_ssi_tag = 0;
  7000. } else if (len == (int)sizeof(buf) - 2) {
  7001. mg_cry(conn, "%s: SSI tag is too large", path);
  7002. len = 0;
  7003. }
  7004. buf[len++] = (char)(ch & 0xff);
  7005. } else if (ch == '<') {
  7006. in_ssi_tag = 1;
  7007. if (len > 0) {
  7008. mg_write(conn, buf, (size_t)len);
  7009. }
  7010. len = 0;
  7011. buf[len++] = (char)(ch & 0xff);
  7012. } else {
  7013. buf[len++] = (char)(ch & 0xff);
  7014. if (len == (int)sizeof(buf)) {
  7015. mg_write(conn, buf, (size_t)len);
  7016. len = 0;
  7017. }
  7018. }
  7019. }
  7020. /* Send the rest of buffered data */
  7021. if (len > 0) {
  7022. mg_write(conn, buf, (size_t)len);
  7023. }
  7024. }
  7025. static void
  7026. handle_ssi_file_request(struct mg_connection *conn,
  7027. const char *path,
  7028. struct file *filep)
  7029. {
  7030. char date[64];
  7031. time_t curtime = time(NULL);
  7032. const char *cors1, *cors2, *cors3;
  7033. if (conn == NULL || path == NULL || filep == NULL) {
  7034. return;
  7035. }
  7036. if (mg_get_header(conn, "Origin")) {
  7037. /* Cross-origin resource sharing (CORS). */
  7038. cors1 = "Access-Control-Allow-Origin: ";
  7039. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7040. cors3 = "\r\n";
  7041. } else {
  7042. cors1 = cors2 = cors3 = "";
  7043. }
  7044. if (!mg_fopen(conn, path, "rb", filep)) {
  7045. /* File exists (precondition for calling this function),
  7046. * but can not be opened by the server. */
  7047. send_http_error(conn,
  7048. 500,
  7049. "Error: Cannot read file\nfopen(%s): %s",
  7050. path,
  7051. strerror(ERRNO));
  7052. } else {
  7053. conn->must_close = 1;
  7054. gmt_time_string(date, sizeof(date), &curtime);
  7055. fclose_on_exec(filep, conn);
  7056. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7057. send_no_cache_header(conn);
  7058. mg_printf(conn,
  7059. "%s%s%s"
  7060. "Date: %s\r\n"
  7061. "Content-Type: text/html\r\n"
  7062. "Connection: %s\r\n\r\n",
  7063. cors1,
  7064. cors2,
  7065. cors3,
  7066. date,
  7067. suggest_connection_header(conn));
  7068. send_ssi_file(conn, path, filep, 0);
  7069. mg_fclose(filep);
  7070. }
  7071. }
  7072. #if !defined(NO_FILES)
  7073. static void
  7074. send_options(struct mg_connection *conn)
  7075. {
  7076. char date[64];
  7077. time_t curtime = time(NULL);
  7078. if (!conn) {
  7079. return;
  7080. }
  7081. conn->status_code = 200;
  7082. conn->must_close = 1;
  7083. gmt_time_string(date, sizeof(date), &curtime);
  7084. mg_printf(conn,
  7085. "HTTP/1.1 200 OK\r\n"
  7086. "Date: %s\r\n"
  7087. /* TODO: "Cache-Control" (?) */
  7088. "Connection: %s\r\n"
  7089. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7090. "PROPFIND, MKCOL\r\n"
  7091. "DAV: 1\r\n\r\n",
  7092. date,
  7093. suggest_connection_header(conn));
  7094. }
  7095. /* Writes PROPFIND properties for a collection element */
  7096. static void
  7097. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7098. {
  7099. char mtime[64];
  7100. if (conn == NULL || uri == NULL || filep == NULL) {
  7101. return;
  7102. }
  7103. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7104. conn->num_bytes_sent +=
  7105. mg_printf(conn,
  7106. "<d:response>"
  7107. "<d:href>%s</d:href>"
  7108. "<d:propstat>"
  7109. "<d:prop>"
  7110. "<d:resourcetype>%s</d:resourcetype>"
  7111. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7112. "<d:getlastmodified>%s</d:getlastmodified>"
  7113. "</d:prop>"
  7114. "<d:status>HTTP/1.1 200 OK</d:status>"
  7115. "</d:propstat>"
  7116. "</d:response>\n",
  7117. uri,
  7118. filep->is_directory ? "<d:collection/>" : "",
  7119. filep->size,
  7120. mtime);
  7121. }
  7122. static void
  7123. print_dav_dir_entry(struct de *de, void *data)
  7124. {
  7125. char href[PATH_MAX];
  7126. char href_encoded[PATH_MAX];
  7127. int truncated;
  7128. struct mg_connection *conn = (struct mg_connection *)data;
  7129. if (!de || !conn) {
  7130. return;
  7131. }
  7132. mg_snprintf(conn,
  7133. &truncated,
  7134. href,
  7135. sizeof(href),
  7136. "%s%s",
  7137. conn->request_info.local_uri,
  7138. de->file_name);
  7139. if (!truncated) {
  7140. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  7141. print_props(conn, href_encoded, &de->file);
  7142. }
  7143. }
  7144. static void
  7145. handle_propfind(struct mg_connection *conn,
  7146. const char *path,
  7147. struct file *filep)
  7148. {
  7149. const char *depth = mg_get_header(conn, "Depth");
  7150. char date[64];
  7151. time_t curtime = time(NULL);
  7152. gmt_time_string(date, sizeof(date), &curtime);
  7153. if (!conn || !path || !filep || !conn->ctx) {
  7154. return;
  7155. }
  7156. conn->must_close = 1;
  7157. conn->status_code = 207;
  7158. mg_printf(conn,
  7159. "HTTP/1.1 207 Multi-Status\r\n"
  7160. "Date: %s\r\n",
  7161. date);
  7162. send_static_cache_header(conn);
  7163. mg_printf(conn,
  7164. "Connection: %s\r\n"
  7165. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7166. suggest_connection_header(conn));
  7167. conn->num_bytes_sent +=
  7168. mg_printf(conn,
  7169. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7170. "<d:multistatus xmlns:d='DAV:'>\n");
  7171. /* Print properties for the requested resource itself */
  7172. print_props(conn, conn->request_info.local_uri, filep);
  7173. /* If it is a directory, print directory entries too if Depth is not 0 */
  7174. if (filep && filep->is_directory
  7175. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7176. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7177. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7178. }
  7179. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7180. }
  7181. #endif
  7182. void
  7183. mg_lock_connection(struct mg_connection *conn)
  7184. {
  7185. if (conn) {
  7186. (void)pthread_mutex_lock(&conn->mutex);
  7187. }
  7188. }
  7189. void
  7190. mg_unlock_connection(struct mg_connection *conn)
  7191. {
  7192. if (conn) {
  7193. (void)pthread_mutex_unlock(&conn->mutex);
  7194. }
  7195. }
  7196. void
  7197. mg_lock_context(struct mg_context *ctx)
  7198. {
  7199. if (ctx) {
  7200. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7201. }
  7202. }
  7203. void
  7204. mg_unlock_context(struct mg_context *ctx)
  7205. {
  7206. if (ctx) {
  7207. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7208. }
  7209. }
  7210. #if defined(USE_TIMERS)
  7211. #include "timer.inl"
  7212. #endif /* USE_TIMERS */
  7213. #ifdef USE_LUA
  7214. #include "mod_lua.inl"
  7215. #endif /* USE_LUA */
  7216. #ifdef USE_DUKTAPE
  7217. #include "mod_duktape.inl"
  7218. #endif /* USE_DUKTAPE */
  7219. #if defined(USE_WEBSOCKET)
  7220. /* START OF SHA-1 code
  7221. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7222. #define SHA1HANDSOFF
  7223. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7224. *
  7225. * #if defined(__sun)
  7226. * #include "solarisfixes.h"
  7227. * #endif
  7228. */
  7229. static int
  7230. is_big_endian(void)
  7231. {
  7232. static const int n = 1;
  7233. return ((char *)&n)[0] == 0;
  7234. }
  7235. union char64long16 {
  7236. unsigned char c[64];
  7237. uint32_t l[16];
  7238. };
  7239. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7240. static uint32_t
  7241. blk0(union char64long16 *block, int i)
  7242. {
  7243. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7244. if (!is_big_endian()) {
  7245. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7246. | (rol(block->l[i], 8) & 0x00FF00FF);
  7247. }
  7248. return block->l[i];
  7249. }
  7250. #define blk(i) \
  7251. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7252. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7253. 1))
  7254. #define R0(v, w, x, y, z, i) \
  7255. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7256. w = rol(w, 30);
  7257. #define R1(v, w, x, y, z, i) \
  7258. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7259. w = rol(w, 30);
  7260. #define R2(v, w, x, y, z, i) \
  7261. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7262. w = rol(w, 30);
  7263. #define R3(v, w, x, y, z, i) \
  7264. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7265. w = rol(w, 30);
  7266. #define R4(v, w, x, y, z, i) \
  7267. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7268. w = rol(w, 30);
  7269. typedef struct {
  7270. uint32_t state[5];
  7271. uint32_t count[2];
  7272. unsigned char buffer[64];
  7273. } SHA1_CTX;
  7274. static void
  7275. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7276. {
  7277. uint32_t a, b, c, d, e;
  7278. union char64long16 block[1];
  7279. memcpy(block, buffer, 64);
  7280. a = state[0];
  7281. b = state[1];
  7282. c = state[2];
  7283. d = state[3];
  7284. e = state[4];
  7285. R0(a, b, c, d, e, 0);
  7286. R0(e, a, b, c, d, 1);
  7287. R0(d, e, a, b, c, 2);
  7288. R0(c, d, e, a, b, 3);
  7289. R0(b, c, d, e, a, 4);
  7290. R0(a, b, c, d, e, 5);
  7291. R0(e, a, b, c, d, 6);
  7292. R0(d, e, a, b, c, 7);
  7293. R0(c, d, e, a, b, 8);
  7294. R0(b, c, d, e, a, 9);
  7295. R0(a, b, c, d, e, 10);
  7296. R0(e, a, b, c, d, 11);
  7297. R0(d, e, a, b, c, 12);
  7298. R0(c, d, e, a, b, 13);
  7299. R0(b, c, d, e, a, 14);
  7300. R0(a, b, c, d, e, 15);
  7301. R1(e, a, b, c, d, 16);
  7302. R1(d, e, a, b, c, 17);
  7303. R1(c, d, e, a, b, 18);
  7304. R1(b, c, d, e, a, 19);
  7305. R2(a, b, c, d, e, 20);
  7306. R2(e, a, b, c, d, 21);
  7307. R2(d, e, a, b, c, 22);
  7308. R2(c, d, e, a, b, 23);
  7309. R2(b, c, d, e, a, 24);
  7310. R2(a, b, c, d, e, 25);
  7311. R2(e, a, b, c, d, 26);
  7312. R2(d, e, a, b, c, 27);
  7313. R2(c, d, e, a, b, 28);
  7314. R2(b, c, d, e, a, 29);
  7315. R2(a, b, c, d, e, 30);
  7316. R2(e, a, b, c, d, 31);
  7317. R2(d, e, a, b, c, 32);
  7318. R2(c, d, e, a, b, 33);
  7319. R2(b, c, d, e, a, 34);
  7320. R2(a, b, c, d, e, 35);
  7321. R2(e, a, b, c, d, 36);
  7322. R2(d, e, a, b, c, 37);
  7323. R2(c, d, e, a, b, 38);
  7324. R2(b, c, d, e, a, 39);
  7325. R3(a, b, c, d, e, 40);
  7326. R3(e, a, b, c, d, 41);
  7327. R3(d, e, a, b, c, 42);
  7328. R3(c, d, e, a, b, 43);
  7329. R3(b, c, d, e, a, 44);
  7330. R3(a, b, c, d, e, 45);
  7331. R3(e, a, b, c, d, 46);
  7332. R3(d, e, a, b, c, 47);
  7333. R3(c, d, e, a, b, 48);
  7334. R3(b, c, d, e, a, 49);
  7335. R3(a, b, c, d, e, 50);
  7336. R3(e, a, b, c, d, 51);
  7337. R3(d, e, a, b, c, 52);
  7338. R3(c, d, e, a, b, 53);
  7339. R3(b, c, d, e, a, 54);
  7340. R3(a, b, c, d, e, 55);
  7341. R3(e, a, b, c, d, 56);
  7342. R3(d, e, a, b, c, 57);
  7343. R3(c, d, e, a, b, 58);
  7344. R3(b, c, d, e, a, 59);
  7345. R4(a, b, c, d, e, 60);
  7346. R4(e, a, b, c, d, 61);
  7347. R4(d, e, a, b, c, 62);
  7348. R4(c, d, e, a, b, 63);
  7349. R4(b, c, d, e, a, 64);
  7350. R4(a, b, c, d, e, 65);
  7351. R4(e, a, b, c, d, 66);
  7352. R4(d, e, a, b, c, 67);
  7353. R4(c, d, e, a, b, 68);
  7354. R4(b, c, d, e, a, 69);
  7355. R4(a, b, c, d, e, 70);
  7356. R4(e, a, b, c, d, 71);
  7357. R4(d, e, a, b, c, 72);
  7358. R4(c, d, e, a, b, 73);
  7359. R4(b, c, d, e, a, 74);
  7360. R4(a, b, c, d, e, 75);
  7361. R4(e, a, b, c, d, 76);
  7362. R4(d, e, a, b, c, 77);
  7363. R4(c, d, e, a, b, 78);
  7364. R4(b, c, d, e, a, 79);
  7365. state[0] += a;
  7366. state[1] += b;
  7367. state[2] += c;
  7368. state[3] += d;
  7369. state[4] += e;
  7370. a = b = c = d = e = 0;
  7371. memset(block, '\0', sizeof(block));
  7372. }
  7373. static void
  7374. SHA1Init(SHA1_CTX *context)
  7375. {
  7376. context->state[0] = 0x67452301;
  7377. context->state[1] = 0xEFCDAB89;
  7378. context->state[2] = 0x98BADCFE;
  7379. context->state[3] = 0x10325476;
  7380. context->state[4] = 0xC3D2E1F0;
  7381. context->count[0] = context->count[1] = 0;
  7382. }
  7383. static void
  7384. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7385. {
  7386. uint32_t i, j;
  7387. j = context->count[0];
  7388. if ((context->count[0] += len << 3) < j) {
  7389. context->count[1]++;
  7390. }
  7391. context->count[1] += (len >> 29);
  7392. j = (j >> 3) & 63;
  7393. if ((j + len) > 63) {
  7394. memcpy(&context->buffer[j], data, (i = 64 - j));
  7395. SHA1Transform(context->state, context->buffer);
  7396. for (; i + 63 < len; i += 64) {
  7397. SHA1Transform(context->state, &data[i]);
  7398. }
  7399. j = 0;
  7400. } else
  7401. i = 0;
  7402. memcpy(&context->buffer[j], &data[i], len - i);
  7403. }
  7404. static void
  7405. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7406. {
  7407. unsigned i;
  7408. unsigned char finalcount[8], c;
  7409. for (i = 0; i < 8; i++) {
  7410. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7411. >> ((3 - (i & 3)) * 8)) & 255);
  7412. }
  7413. c = 0200;
  7414. SHA1Update(context, &c, 1);
  7415. while ((context->count[0] & 504) != 448) {
  7416. c = 0000;
  7417. SHA1Update(context, &c, 1);
  7418. }
  7419. SHA1Update(context, finalcount, 8);
  7420. for (i = 0; i < 20; i++) {
  7421. digest[i] = (unsigned char)((context->state[i >> 2]
  7422. >> ((3 - (i & 3)) * 8)) & 255);
  7423. }
  7424. memset(context, '\0', sizeof(*context));
  7425. memset(&finalcount, '\0', sizeof(finalcount));
  7426. }
  7427. /* END OF SHA1 CODE */
  7428. static int
  7429. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7430. {
  7431. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7432. const char *protocol = NULL;
  7433. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7434. SHA1_CTX sha_ctx;
  7435. int truncated;
  7436. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7437. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7438. if (truncated) {
  7439. conn->must_close = 1;
  7440. return 0;
  7441. }
  7442. SHA1Init(&sha_ctx);
  7443. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7444. SHA1Final((unsigned char *)sha, &sha_ctx);
  7445. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7446. mg_printf(conn,
  7447. "HTTP/1.1 101 Switching Protocols\r\n"
  7448. "Upgrade: websocket\r\n"
  7449. "Connection: Upgrade\r\n"
  7450. "Sec-WebSocket-Accept: %s\r\n",
  7451. b64_sha);
  7452. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7453. if (protocol) {
  7454. /* The protocol is a comma seperated list of names. */
  7455. /* The server must only return one value from this list. */
  7456. /* First check if it is a list or just a single value. */
  7457. const char *sep = strchr(protocol, ',');
  7458. if (sep == NULL) {
  7459. /* Just a single protocol -> accept it. */
  7460. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7461. } else {
  7462. /* Multiple protocols -> accept the first one. */
  7463. /* This is just a quick fix if the client offers multiple
  7464. * protocols. In order to get the behavior intended by
  7465. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7466. * required to have a list of websocket subprotocols accepted
  7467. * by the server. Then the server must either select a subprotocol
  7468. * supported by client and server, or the server has to abort the
  7469. * handshake by not returning a Sec-Websocket-Protocol header if
  7470. * no subprotocol is acceptable.
  7471. */
  7472. mg_printf(conn,
  7473. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7474. (int)(sep - protocol),
  7475. protocol);
  7476. }
  7477. /* TODO: Real subprotocol negotiation instead of just taking the first
  7478. * websocket subprotocol suggested by the client. */
  7479. } else {
  7480. mg_printf(conn, "%s", "\r\n");
  7481. }
  7482. return 1;
  7483. }
  7484. static void
  7485. read_websocket(struct mg_connection *conn,
  7486. mg_websocket_data_handler ws_data_handler,
  7487. void *callback_data)
  7488. {
  7489. /* Pointer to the beginning of the portion of the incoming websocket
  7490. * message queue.
  7491. * The original websocket upgrade request is never removed, so the queue
  7492. * begins after it. */
  7493. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7494. int n, error, exit_by_callback;
  7495. /* body_len is the length of the entire queue in bytes
  7496. * len is the length of the current message
  7497. * data_len is the length of the current message's data payload
  7498. * header_len is the length of the current message's header */
  7499. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7500. /* "The masking key is a 32-bit value chosen at random by the client."
  7501. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7502. */
  7503. unsigned char mask[4];
  7504. /* data points to the place where the message is stored when passed to
  7505. * the
  7506. * websocket_data callback. This is either mem on the stack, or a
  7507. * dynamically allocated buffer if it is too large. */
  7508. char mem[4096];
  7509. char *data = mem;
  7510. unsigned char mop; /* mask flag and opcode */
  7511. double timeout = -1.0;
  7512. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7513. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7514. }
  7515. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7516. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7517. }
  7518. mg_set_thread_name("wsock");
  7519. /* Loop continuously, reading messages from the socket, invoking the
  7520. * callback, and waiting repeatedly until an error occurs. */
  7521. while (!conn->ctx->stop_flag) {
  7522. header_len = 0;
  7523. assert(conn->data_len >= conn->request_len);
  7524. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7525. len = buf[1] & 127;
  7526. mask_len = buf[1] & 128 ? 4 : 0;
  7527. if (len < 126 && body_len >= mask_len) {
  7528. data_len = len;
  7529. header_len = 2 + mask_len;
  7530. } else if (len == 126 && body_len >= 4 + mask_len) {
  7531. header_len = 4 + mask_len;
  7532. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7533. } else if (body_len >= 10 + mask_len) {
  7534. header_len = 10 + mask_len;
  7535. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7536. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7537. }
  7538. }
  7539. if (header_len > 0 && body_len >= header_len) {
  7540. /* Allocate space to hold websocket payload */
  7541. data = mem;
  7542. if (data_len > sizeof(mem)) {
  7543. data = (char *)mg_malloc(data_len);
  7544. if (data == NULL) {
  7545. /* Allocation failed, exit the loop and then close the
  7546. * connection */
  7547. mg_cry(conn, "websocket out of memory; closing connection");
  7548. break;
  7549. }
  7550. }
  7551. /* Copy the mask before we shift the queue and destroy it */
  7552. if (mask_len > 0) {
  7553. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7554. } else {
  7555. memset(mask, 0, sizeof(mask));
  7556. }
  7557. /* Read frame payload from the first message in the queue into
  7558. * data and advance the queue by moving the memory in place. */
  7559. assert(body_len >= header_len);
  7560. if (data_len + header_len > body_len) {
  7561. mop = buf[0]; /* current mask and opcode */
  7562. /* Overflow case */
  7563. len = body_len - header_len;
  7564. memcpy(data, buf + header_len, len);
  7565. error = 0;
  7566. while (len < data_len) {
  7567. n = pull(
  7568. NULL, conn, data + len, (int)(data_len - len), timeout);
  7569. if (n <= 0) {
  7570. error = 1;
  7571. break;
  7572. }
  7573. len += (size_t)n;
  7574. }
  7575. if (error) {
  7576. mg_cry(conn, "Websocket pull failed; closing connection");
  7577. break;
  7578. }
  7579. conn->data_len = conn->request_len;
  7580. } else {
  7581. mop = buf[0]; /* current mask and opcode, overwritten by
  7582. * memmove() */
  7583. /* Length of the message being read at the front of the
  7584. * queue */
  7585. len = data_len + header_len;
  7586. /* Copy the data payload into the data pointer for the
  7587. * callback */
  7588. memcpy(data, buf + header_len, data_len);
  7589. /* Move the queue forward len bytes */
  7590. memmove(buf, buf + len, body_len - len);
  7591. /* Mark the queue as advanced */
  7592. conn->data_len -= (int)len;
  7593. }
  7594. /* Apply mask if necessary */
  7595. if (mask_len > 0) {
  7596. for (i = 0; i < data_len; ++i) {
  7597. data[i] ^= mask[i & 3];
  7598. }
  7599. }
  7600. /* Exit the loop if callback signals to exit (server side),
  7601. * or "connection close" opcode received (client side). */
  7602. exit_by_callback = 0;
  7603. if ((ws_data_handler != NULL)
  7604. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7605. exit_by_callback = 1;
  7606. }
  7607. if (data != mem) {
  7608. mg_free(data);
  7609. }
  7610. if (exit_by_callback
  7611. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7612. /* Opcode == 8, connection close */
  7613. break;
  7614. }
  7615. /* Not breaking the loop, process next websocket frame. */
  7616. } else {
  7617. /* Read from the socket into the next available location in the
  7618. * message queue. */
  7619. if ((n = pull(NULL,
  7620. conn,
  7621. conn->buf + conn->data_len,
  7622. conn->buf_size - conn->data_len,
  7623. timeout)) <= 0) {
  7624. /* Error, no bytes read */
  7625. break;
  7626. }
  7627. conn->data_len += n;
  7628. }
  7629. }
  7630. mg_set_thread_name("worker");
  7631. }
  7632. static int
  7633. mg_websocket_write_exec(struct mg_connection *conn,
  7634. int opcode,
  7635. const char *data,
  7636. size_t dataLen,
  7637. uint32_t masking_key)
  7638. {
  7639. unsigned char header[14];
  7640. size_t headerLen = 1;
  7641. int retval = -1;
  7642. header[0] = 0x80 + (opcode & 0xF);
  7643. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7644. if (dataLen < 126) {
  7645. /* inline 7-bit length field */
  7646. header[1] = (unsigned char)dataLen;
  7647. headerLen = 2;
  7648. } else if (dataLen <= 0xFFFF) {
  7649. /* 16-bit length field */
  7650. header[1] = 126;
  7651. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7652. headerLen = 4;
  7653. } else {
  7654. /* 64-bit length field */
  7655. header[1] = 127;
  7656. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7657. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7658. headerLen = 10;
  7659. }
  7660. if (masking_key) {
  7661. /* add mask */
  7662. header[1] |= 0x80;
  7663. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7664. headerLen += 4;
  7665. }
  7666. /* Note that POSIX/Winsock's send() is threadsafe
  7667. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7668. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7669. * push(), although that is only a problem if the packet is large or
  7670. * outgoing buffer is full). */
  7671. (void)mg_lock_connection(conn);
  7672. retval = mg_write(conn, header, headerLen);
  7673. if (dataLen > 0) {
  7674. retval = mg_write(conn, data, dataLen);
  7675. }
  7676. mg_unlock_connection(conn);
  7677. return retval;
  7678. }
  7679. int
  7680. mg_websocket_write(struct mg_connection *conn,
  7681. int opcode,
  7682. const char *data,
  7683. size_t dataLen)
  7684. {
  7685. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7686. }
  7687. static void
  7688. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7689. {
  7690. size_t i = 0;
  7691. i = 0;
  7692. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7693. /* Convert in 32 bit words, if data is 4 byte aligned */
  7694. while (i < (in_len - 3)) {
  7695. *(uint32_t *)(void *)(out + i) =
  7696. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7697. i += 4;
  7698. }
  7699. }
  7700. if (i != in_len) {
  7701. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7702. while (i < in_len) {
  7703. *(uint8_t *)(void *)(out + i) =
  7704. *(uint8_t *)(void *)(in + i)
  7705. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7706. i++;
  7707. }
  7708. }
  7709. }
  7710. int
  7711. mg_websocket_client_write(struct mg_connection *conn,
  7712. int opcode,
  7713. const char *data,
  7714. size_t dataLen)
  7715. {
  7716. int retval = -1;
  7717. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7718. uint32_t masking_key = (uint32_t)get_random();
  7719. if (masked_data == NULL) {
  7720. /* Return -1 in an error case */
  7721. mg_cry(conn,
  7722. "Cannot allocate buffer for masked websocket response: "
  7723. "Out of memory");
  7724. return -1;
  7725. }
  7726. mask_data(data, dataLen, masking_key, masked_data);
  7727. retval = mg_websocket_write_exec(
  7728. conn, opcode, masked_data, dataLen, masking_key);
  7729. mg_free(masked_data);
  7730. return retval;
  7731. }
  7732. static void
  7733. handle_websocket_request(struct mg_connection *conn,
  7734. const char *path,
  7735. int is_callback_resource,
  7736. mg_websocket_connect_handler ws_connect_handler,
  7737. mg_websocket_ready_handler ws_ready_handler,
  7738. mg_websocket_data_handler ws_data_handler,
  7739. mg_websocket_close_handler ws_close_handler,
  7740. void *cbData)
  7741. {
  7742. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7743. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7744. int lua_websock = 0;
  7745. #if !defined(USE_LUA)
  7746. (void)path;
  7747. #endif
  7748. /* Step 1: Check websocket protocol version. */
  7749. /* Step 1.1: Check Sec-WebSocket-Key. */
  7750. if (!websock_key) {
  7751. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7752. * requires a Sec-WebSocket-Key header.
  7753. */
  7754. /* It could be the hixie draft version
  7755. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7756. */
  7757. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7758. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7759. char key3[8];
  7760. if ((key1 != NULL) && (key2 != NULL)) {
  7761. /* This version uses 8 byte body data in a GET request */
  7762. conn->content_len = 8;
  7763. if (8 == mg_read(conn, key3, 8)) {
  7764. /* This is the hixie version */
  7765. send_http_error(conn,
  7766. 426,
  7767. "%s",
  7768. "Protocol upgrade to RFC 6455 required");
  7769. return;
  7770. }
  7771. }
  7772. /* This is an unknown version */
  7773. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7774. return;
  7775. }
  7776. /* Step 1.2: Check websocket protocol version. */
  7777. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7778. if (version == NULL || strcmp(version, "13") != 0) {
  7779. /* Reject wrong versions */
  7780. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7781. return;
  7782. }
  7783. /* Step 1.3: Could check for "Host", but we do not really nead this
  7784. * value for anything, so just ignore it. */
  7785. /* Step 2: If a callback is responsible, call it. */
  7786. if (is_callback_resource) {
  7787. if (ws_connect_handler != NULL
  7788. && ws_connect_handler(conn, cbData) != 0) {
  7789. /* C callback has returned non-zero, do not proceed with
  7790. * handshake.
  7791. */
  7792. /* Note that C callbacks are no longer called when Lua is
  7793. * responsible, so C can no longer filter callbacks for Lua. */
  7794. return;
  7795. }
  7796. }
  7797. #if defined(USE_LUA)
  7798. /* Step 3: No callback. Check if Lua is responsible. */
  7799. else {
  7800. /* Step 3.1: Check if Lua is responsible. */
  7801. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7802. lua_websock =
  7803. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7804. strlen(
  7805. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7806. path);
  7807. }
  7808. if (lua_websock) {
  7809. /* Step 3.2: Lua is responsible: call it. */
  7810. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7811. if (!conn->lua_websocket_state) {
  7812. /* Lua rejected the new client */
  7813. return;
  7814. }
  7815. }
  7816. }
  7817. #endif
  7818. /* Step 4: Check if there is a responsible websocket handler. */
  7819. if (!is_callback_resource && !lua_websock) {
  7820. /* There is no callback, an Lua is not responsible either. */
  7821. /* Reply with a 404 Not Found or with nothing at all?
  7822. * TODO (mid): check the websocket standards, how to reply to
  7823. * requests to invalid websocket addresses. */
  7824. send_http_error(conn, 404, "%s", "Not found");
  7825. return;
  7826. }
  7827. /* Step 5: The websocket connection has been accepted */
  7828. if (!send_websocket_handshake(conn, websock_key)) {
  7829. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7830. return;
  7831. }
  7832. /* Step 6: Call the ready handler */
  7833. if (is_callback_resource) {
  7834. if (ws_ready_handler != NULL) {
  7835. ws_ready_handler(conn, cbData);
  7836. }
  7837. #if defined(USE_LUA)
  7838. } else if (lua_websock) {
  7839. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7840. /* the ready handler returned false */
  7841. return;
  7842. }
  7843. #endif
  7844. }
  7845. /* Step 7: Enter the read loop */
  7846. if (is_callback_resource) {
  7847. read_websocket(conn, ws_data_handler, cbData);
  7848. #if defined(USE_LUA)
  7849. } else if (lua_websock) {
  7850. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7851. #endif
  7852. }
  7853. /* Step 8: Call the close handler */
  7854. if (ws_close_handler) {
  7855. ws_close_handler(conn, cbData);
  7856. }
  7857. }
  7858. static int
  7859. is_websocket_protocol(const struct mg_connection *conn)
  7860. {
  7861. const char *upgrade, *connection;
  7862. /* A websocket protocoll has the following HTTP headers:
  7863. *
  7864. * Connection: Upgrade
  7865. * Upgrade: Websocket
  7866. */
  7867. upgrade = mg_get_header(conn, "Upgrade");
  7868. if (upgrade == NULL) {
  7869. return 0; /* fail early, don't waste time checking other header
  7870. * fields
  7871. */
  7872. }
  7873. if (!mg_strcasestr(upgrade, "websocket")) {
  7874. return 0;
  7875. }
  7876. connection = mg_get_header(conn, "Connection");
  7877. if (connection == NULL) {
  7878. return 0;
  7879. }
  7880. if (!mg_strcasestr(connection, "upgrade")) {
  7881. return 0;
  7882. }
  7883. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7884. * "Sec-WebSocket-Version" are also required.
  7885. * Don't check them here, since even an unsupported websocket protocol
  7886. * request still IS a websocket request (in contrast to a standard HTTP
  7887. * request). It will fail later in handle_websocket_request.
  7888. */
  7889. return 1;
  7890. }
  7891. #endif /* !USE_WEBSOCKET */
  7892. static int
  7893. isbyte(int n)
  7894. {
  7895. return n >= 0 && n <= 255;
  7896. }
  7897. static int
  7898. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7899. {
  7900. int n, a, b, c, d, slash = 32, len = 0;
  7901. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7902. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7903. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7904. && slash < 33) {
  7905. len = n;
  7906. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7907. | (uint32_t)d;
  7908. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7909. }
  7910. return len;
  7911. }
  7912. static int
  7913. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7914. {
  7915. int throttle = 0;
  7916. struct vec vec, val;
  7917. uint32_t net, mask;
  7918. char mult;
  7919. double v;
  7920. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7921. mult = ',';
  7922. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7923. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7924. && mult != ',')) {
  7925. continue;
  7926. }
  7927. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7928. : 1;
  7929. if (vec.len == 1 && vec.ptr[0] == '*') {
  7930. throttle = (int)v;
  7931. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7932. if ((remote_ip & mask) == net) {
  7933. throttle = (int)v;
  7934. }
  7935. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7936. throttle = (int)v;
  7937. }
  7938. }
  7939. return throttle;
  7940. }
  7941. static uint32_t
  7942. get_remote_ip(const struct mg_connection *conn)
  7943. {
  7944. if (!conn) {
  7945. return 0;
  7946. }
  7947. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  7948. }
  7949. /* The mg_upload function is superseeded by mg_handle_form_request. */
  7950. #include "handle_form.inl"
  7951. #if defined(MG_LEGACY_INTERFACE)
  7952. /* Implement the deprecated mg_upload function by calling the new
  7953. * mg_handle_form_request function. While mg_upload could only handle
  7954. * HTML forms sent as POST request in multipart/form-data format
  7955. * containing only file input elements, mg_handle_form_request can
  7956. * handle all form input elements and all standard request methods. */
  7957. struct mg_upload_user_data {
  7958. struct mg_connection *conn;
  7959. const char *destination_dir;
  7960. int num_uploaded_files;
  7961. };
  7962. /* Helper function for deprecated mg_upload. */
  7963. static int
  7964. mg_upload_field_found(const char *key,
  7965. const char *filename,
  7966. char *path,
  7967. size_t pathlen,
  7968. void *user_data)
  7969. {
  7970. int truncated = 0;
  7971. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7972. (void)key;
  7973. if (!filename) {
  7974. mg_cry(fud->conn, "%s: No filename set", __func__);
  7975. return FORM_FIELD_STORAGE_ABORT;
  7976. }
  7977. mg_snprintf(fud->conn,
  7978. &truncated,
  7979. path,
  7980. pathlen - 1,
  7981. "%s/%s",
  7982. fud->destination_dir,
  7983. filename);
  7984. if (!truncated) {
  7985. mg_cry(fud->conn, "%s: File path too long", __func__);
  7986. return FORM_FIELD_STORAGE_ABORT;
  7987. }
  7988. return FORM_FIELD_STORAGE_STORE;
  7989. }
  7990. /* Helper function for deprecated mg_upload. */
  7991. static int
  7992. mg_upload_field_get(const char *key,
  7993. const char *value,
  7994. size_t value_size,
  7995. void *user_data)
  7996. {
  7997. /* Function should never be called */
  7998. (void)key;
  7999. (void)value;
  8000. (void)value_size;
  8001. (void)user_data;
  8002. return 0;
  8003. }
  8004. /* Helper function for deprecated mg_upload. */
  8005. static int
  8006. mg_upload_field_stored(const char *path, size_t file_size, void *user_data)
  8007. {
  8008. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8009. (void)file_size;
  8010. fud->num_uploaded_files++;
  8011. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8012. return 0;
  8013. }
  8014. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8015. int
  8016. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8017. {
  8018. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8019. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8020. mg_upload_field_get,
  8021. mg_upload_field_stored,
  8022. 0};
  8023. int ret;
  8024. fdh.user_data = (void *)&fud;
  8025. ret = mg_handle_form_request(conn, &fdh);
  8026. if (ret < 0) {
  8027. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8028. }
  8029. return fud.num_uploaded_files;
  8030. }
  8031. #endif
  8032. static int
  8033. get_first_ssl_listener_index(const struct mg_context *ctx)
  8034. {
  8035. unsigned int i;
  8036. int idx = -1;
  8037. if (ctx) {
  8038. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8039. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8040. }
  8041. }
  8042. return idx;
  8043. }
  8044. static void
  8045. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8046. {
  8047. char host[1025];
  8048. const char *host_header;
  8049. size_t hostlen;
  8050. host_header = mg_get_header(conn, "Host");
  8051. hostlen = sizeof(host);
  8052. if (host_header != NULL) {
  8053. char *pos;
  8054. mg_strlcpy(host, host_header, hostlen);
  8055. host[hostlen - 1] = '\0';
  8056. pos = strchr(host, ':');
  8057. if (pos != NULL) {
  8058. *pos = '\0';
  8059. }
  8060. } else {
  8061. /* Cannot get host from the Host: header.
  8062. * Fallback to our IP address. */
  8063. if (conn) {
  8064. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8065. }
  8066. }
  8067. /* Send host, port, uri and (if it exists) ?query_string */
  8068. if (conn) {
  8069. mg_printf(conn,
  8070. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8071. host,
  8072. (int)ntohs(
  8073. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  8074. conn->request_info.local_uri,
  8075. (conn->request_info.query_string == NULL) ? "" : "?",
  8076. (conn->request_info.query_string == NULL)
  8077. ? ""
  8078. : conn->request_info.query_string);
  8079. }
  8080. }
  8081. static void
  8082. mg_set_handler_type(struct mg_context *ctx,
  8083. const char *uri,
  8084. int handler_type,
  8085. int is_delete_request,
  8086. mg_request_handler handler,
  8087. mg_websocket_connect_handler connect_handler,
  8088. mg_websocket_ready_handler ready_handler,
  8089. mg_websocket_data_handler data_handler,
  8090. mg_websocket_close_handler close_handler,
  8091. mg_authorization_handler auth_handler,
  8092. void *cbdata)
  8093. {
  8094. struct mg_handler_info *tmp_rh, **lastref;
  8095. size_t urilen = strlen(uri);
  8096. if (handler_type == WEBSOCKET_HANDLER) {
  8097. /* assert(handler == NULL); */
  8098. /* assert(is_delete_request || connect_handler!=NULL ||
  8099. * ready_handler!=NULL || data_handler!=NULL ||
  8100. * close_handler!=NULL);
  8101. */
  8102. /* assert(auth_handler == NULL); */
  8103. if (handler != NULL) {
  8104. return;
  8105. }
  8106. if (!is_delete_request && connect_handler == NULL
  8107. && ready_handler == NULL
  8108. && data_handler == NULL
  8109. && close_handler == NULL) {
  8110. return;
  8111. }
  8112. if (auth_handler != NULL) {
  8113. return;
  8114. }
  8115. } else if (handler_type == REQUEST_HANDLER) {
  8116. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8117. * data_handler==NULL && close_handler==NULL); */
  8118. /* assert(is_delete_request || (handler!=NULL));
  8119. */
  8120. /* assert(auth_handler == NULL); */
  8121. if (connect_handler != NULL || ready_handler != NULL
  8122. || data_handler != NULL
  8123. || close_handler != NULL) {
  8124. return;
  8125. }
  8126. if (!is_delete_request && (handler == NULL)) {
  8127. return;
  8128. }
  8129. if (auth_handler != NULL) {
  8130. return;
  8131. }
  8132. } else { /* AUTH_HANDLER */
  8133. /* assert(handler == NULL); */
  8134. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8135. * data_handler==NULL && close_handler==NULL); */
  8136. /* assert(auth_handler != NULL); */
  8137. if (handler != NULL) {
  8138. return;
  8139. }
  8140. if (connect_handler != NULL || ready_handler != NULL
  8141. || data_handler != NULL
  8142. || close_handler != NULL) {
  8143. return;
  8144. }
  8145. if (!is_delete_request && (auth_handler == NULL)) {
  8146. return;
  8147. }
  8148. }
  8149. if (!ctx) {
  8150. return;
  8151. }
  8152. mg_lock_context(ctx);
  8153. /* first try to find an existing handler */
  8154. lastref = &(ctx->handlers);
  8155. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8156. if (tmp_rh->handler_type == handler_type) {
  8157. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8158. if (!is_delete_request) {
  8159. /* update existing handler */
  8160. if (handler_type == REQUEST_HANDLER) {
  8161. tmp_rh->handler = handler;
  8162. } else if (handler_type == WEBSOCKET_HANDLER) {
  8163. tmp_rh->connect_handler = connect_handler;
  8164. tmp_rh->ready_handler = ready_handler;
  8165. tmp_rh->data_handler = data_handler;
  8166. tmp_rh->close_handler = close_handler;
  8167. } else { /* AUTH_HANDLER */
  8168. tmp_rh->auth_handler = auth_handler;
  8169. }
  8170. tmp_rh->cbdata = cbdata;
  8171. } else {
  8172. /* remove existing handler */
  8173. *lastref = tmp_rh->next;
  8174. mg_free(tmp_rh->uri);
  8175. mg_free(tmp_rh);
  8176. }
  8177. mg_unlock_context(ctx);
  8178. return;
  8179. }
  8180. }
  8181. lastref = &(tmp_rh->next);
  8182. }
  8183. if (is_delete_request) {
  8184. /* no handler to set, this was a remove request to a non-existing
  8185. * handler */
  8186. mg_unlock_context(ctx);
  8187. return;
  8188. }
  8189. tmp_rh =
  8190. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8191. if (tmp_rh == NULL) {
  8192. mg_unlock_context(ctx);
  8193. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8194. return;
  8195. }
  8196. tmp_rh->uri = mg_strdup(uri);
  8197. if (!tmp_rh->uri) {
  8198. mg_unlock_context(ctx);
  8199. mg_free(tmp_rh);
  8200. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8201. return;
  8202. }
  8203. tmp_rh->uri_len = urilen;
  8204. if (handler_type == REQUEST_HANDLER) {
  8205. tmp_rh->handler = handler;
  8206. } else if (handler_type == WEBSOCKET_HANDLER) {
  8207. tmp_rh->connect_handler = connect_handler;
  8208. tmp_rh->ready_handler = ready_handler;
  8209. tmp_rh->data_handler = data_handler;
  8210. tmp_rh->close_handler = close_handler;
  8211. } else { /* AUTH_HANDLER */
  8212. tmp_rh->auth_handler = auth_handler;
  8213. }
  8214. tmp_rh->cbdata = cbdata;
  8215. tmp_rh->handler_type = handler_type;
  8216. tmp_rh->next = NULL;
  8217. *lastref = tmp_rh;
  8218. mg_unlock_context(ctx);
  8219. }
  8220. void
  8221. mg_set_request_handler(struct mg_context *ctx,
  8222. const char *uri,
  8223. mg_request_handler handler,
  8224. void *cbdata)
  8225. {
  8226. mg_set_handler_type(ctx,
  8227. uri,
  8228. REQUEST_HANDLER,
  8229. handler == NULL,
  8230. handler,
  8231. NULL,
  8232. NULL,
  8233. NULL,
  8234. NULL,
  8235. NULL,
  8236. cbdata);
  8237. }
  8238. void
  8239. mg_set_websocket_handler(struct mg_context *ctx,
  8240. const char *uri,
  8241. mg_websocket_connect_handler connect_handler,
  8242. mg_websocket_ready_handler ready_handler,
  8243. mg_websocket_data_handler data_handler,
  8244. mg_websocket_close_handler close_handler,
  8245. void *cbdata)
  8246. {
  8247. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8248. && (data_handler == NULL)
  8249. && (close_handler == NULL);
  8250. mg_set_handler_type(ctx,
  8251. uri,
  8252. WEBSOCKET_HANDLER,
  8253. is_delete_request,
  8254. NULL,
  8255. connect_handler,
  8256. ready_handler,
  8257. data_handler,
  8258. close_handler,
  8259. NULL,
  8260. cbdata);
  8261. }
  8262. void
  8263. mg_set_auth_handler(struct mg_context *ctx,
  8264. const char *uri,
  8265. mg_request_handler handler,
  8266. void *cbdata)
  8267. {
  8268. mg_set_handler_type(ctx,
  8269. uri,
  8270. AUTH_HANDLER,
  8271. handler == NULL,
  8272. NULL,
  8273. NULL,
  8274. NULL,
  8275. NULL,
  8276. NULL,
  8277. handler,
  8278. cbdata);
  8279. }
  8280. static int
  8281. get_request_handler(struct mg_connection *conn,
  8282. int handler_type,
  8283. mg_request_handler *handler,
  8284. mg_websocket_connect_handler *connect_handler,
  8285. mg_websocket_ready_handler *ready_handler,
  8286. mg_websocket_data_handler *data_handler,
  8287. mg_websocket_close_handler *close_handler,
  8288. mg_authorization_handler *auth_handler,
  8289. void **cbdata)
  8290. {
  8291. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8292. if (request_info) {
  8293. const char *uri = request_info->local_uri;
  8294. size_t urilen = strlen(uri);
  8295. struct mg_handler_info *tmp_rh;
  8296. if (!conn || !conn->ctx) {
  8297. return 0;
  8298. }
  8299. mg_lock_context(conn->ctx);
  8300. /* first try for an exact match */
  8301. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8302. tmp_rh = tmp_rh->next) {
  8303. if (tmp_rh->handler_type == handler_type) {
  8304. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8305. if (handler_type == WEBSOCKET_HANDLER) {
  8306. *connect_handler = tmp_rh->connect_handler;
  8307. *ready_handler = tmp_rh->ready_handler;
  8308. *data_handler = tmp_rh->data_handler;
  8309. *close_handler = tmp_rh->close_handler;
  8310. } else if (handler_type == REQUEST_HANDLER) {
  8311. *handler = tmp_rh->handler;
  8312. } else { /* AUTH_HANDLER */
  8313. *auth_handler = tmp_rh->auth_handler;
  8314. }
  8315. *cbdata = tmp_rh->cbdata;
  8316. mg_unlock_context(conn->ctx);
  8317. return 1;
  8318. }
  8319. }
  8320. }
  8321. /* next try for a partial match, we will accept uri/something */
  8322. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8323. tmp_rh = tmp_rh->next) {
  8324. if (tmp_rh->handler_type == handler_type) {
  8325. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8326. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8327. if (handler_type == WEBSOCKET_HANDLER) {
  8328. *connect_handler = tmp_rh->connect_handler;
  8329. *ready_handler = tmp_rh->ready_handler;
  8330. *data_handler = tmp_rh->data_handler;
  8331. *close_handler = tmp_rh->close_handler;
  8332. } else if (handler_type == REQUEST_HANDLER) {
  8333. *handler = tmp_rh->handler;
  8334. } else { /* AUTH_HANDLER */
  8335. *auth_handler = tmp_rh->auth_handler;
  8336. }
  8337. *cbdata = tmp_rh->cbdata;
  8338. mg_unlock_context(conn->ctx);
  8339. return 1;
  8340. }
  8341. }
  8342. }
  8343. /* finally try for pattern match */
  8344. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8345. tmp_rh = tmp_rh->next) {
  8346. if (tmp_rh->handler_type == handler_type) {
  8347. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8348. if (handler_type == WEBSOCKET_HANDLER) {
  8349. *connect_handler = tmp_rh->connect_handler;
  8350. *ready_handler = tmp_rh->ready_handler;
  8351. *data_handler = tmp_rh->data_handler;
  8352. *close_handler = tmp_rh->close_handler;
  8353. } else if (handler_type == REQUEST_HANDLER) {
  8354. *handler = tmp_rh->handler;
  8355. } else { /* AUTH_HANDLER */
  8356. *auth_handler = tmp_rh->auth_handler;
  8357. }
  8358. *cbdata = tmp_rh->cbdata;
  8359. mg_unlock_context(conn->ctx);
  8360. return 1;
  8361. }
  8362. }
  8363. }
  8364. mg_unlock_context(conn->ctx);
  8365. }
  8366. return 0; /* none found */
  8367. }
  8368. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8369. static int
  8370. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8371. void *cbdata)
  8372. {
  8373. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8374. if (pcallbacks->websocket_connect) {
  8375. return pcallbacks->websocket_connect(conn);
  8376. }
  8377. /* No handler set - assume "OK" */
  8378. return 0;
  8379. }
  8380. static void
  8381. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8382. {
  8383. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8384. if (pcallbacks->websocket_ready) {
  8385. pcallbacks->websocket_ready(conn);
  8386. }
  8387. }
  8388. static int
  8389. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8390. int bits,
  8391. char *data,
  8392. size_t len,
  8393. void *cbdata)
  8394. {
  8395. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8396. if (pcallbacks->websocket_data) {
  8397. return pcallbacks->websocket_data(conn, bits, data, len);
  8398. }
  8399. /* No handler set - assume "OK" */
  8400. return 1;
  8401. }
  8402. #endif
  8403. /* This is the heart of the Civetweb's logic.
  8404. * This function is called when the request is read, parsed and validated,
  8405. * and Civetweb must decide what action to take: serve a file, or
  8406. * a directory, or call embedded function, etcetera. */
  8407. static void
  8408. handle_request(struct mg_connection *conn)
  8409. {
  8410. if (conn) {
  8411. struct mg_request_info *ri = &conn->request_info;
  8412. char path[PATH_MAX];
  8413. int uri_len, ssl_index;
  8414. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8415. is_put_or_delete_request = 0, is_callback_resource = 0;
  8416. int i;
  8417. struct file file = STRUCT_FILE_INITIALIZER;
  8418. mg_request_handler callback_handler = NULL;
  8419. mg_websocket_connect_handler ws_connect_handler = NULL;
  8420. mg_websocket_ready_handler ws_ready_handler = NULL;
  8421. mg_websocket_data_handler ws_data_handler = NULL;
  8422. mg_websocket_close_handler ws_close_handler = NULL;
  8423. void *callback_data = NULL;
  8424. mg_authorization_handler auth_handler = NULL;
  8425. void *auth_callback_data = NULL;
  8426. #if !defined(NO_FILES)
  8427. time_t curtime = time(NULL);
  8428. char date[64];
  8429. #endif
  8430. path[0] = 0;
  8431. if (!ri) {
  8432. return;
  8433. }
  8434. /* 1. get the request url */
  8435. /* 1.1. split into url and query string */
  8436. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8437. != NULL) {
  8438. *((char *)conn->request_info.query_string++) = '\0';
  8439. }
  8440. uri_len = (int)strlen(ri->local_uri);
  8441. /* 1.2. decode url (if config says so) */
  8442. if (should_decode_url(conn)) {
  8443. mg_url_decode(
  8444. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8445. }
  8446. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8447. * not possible */
  8448. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8449. /* step 1. completed, the url is known now */
  8450. DEBUG_TRACE("URL: %s", ri->local_uri);
  8451. /* 2. do a https redirect, if required */
  8452. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8453. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8454. if (ssl_index >= 0) {
  8455. redirect_to_https_port(conn, ssl_index);
  8456. } else {
  8457. /* A http to https forward port has been specified,
  8458. * but no https port to forward to. */
  8459. send_http_error(conn,
  8460. 503,
  8461. "%s",
  8462. "Error: SSL forward not configured properly");
  8463. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8464. }
  8465. return;
  8466. }
  8467. /* 3. if this ip has limited speed, set it for this connection */
  8468. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8469. get_remote_ip(conn),
  8470. ri->local_uri);
  8471. /* 4. call a "handle everything" callback, if registered */
  8472. if (conn->ctx->callbacks.begin_request != NULL) {
  8473. /* Note that since V1.7 the "begin_request" function is called
  8474. * before an authorization check. If an authorization check is
  8475. * required, use a request_handler instead. */
  8476. i = conn->ctx->callbacks.begin_request(conn);
  8477. if (i > 0) {
  8478. /* callback already processed the request. Store the
  8479. return value as a status code for the access log. */
  8480. conn->status_code = i;
  8481. return;
  8482. } else if (i == 0) {
  8483. /* civetweb should process the request */
  8484. } else {
  8485. /* unspecified - may change with the next version */
  8486. return;
  8487. }
  8488. }
  8489. /* request not yet handled by a handler or redirect, so the request
  8490. * is processed here */
  8491. /* 5. interpret the url to find out how the request must be handled
  8492. */
  8493. /* 5.1. first test, if the request targets the regular http(s)://
  8494. * protocol namespace or the websocket ws(s):// protocol namespace.
  8495. */
  8496. is_websocket_request = is_websocket_protocol(conn);
  8497. /* 5.2. check if the request will be handled by a callback */
  8498. if (get_request_handler(conn,
  8499. is_websocket_request ? WEBSOCKET_HANDLER
  8500. : REQUEST_HANDLER,
  8501. &callback_handler,
  8502. &ws_connect_handler,
  8503. &ws_ready_handler,
  8504. &ws_data_handler,
  8505. &ws_close_handler,
  8506. NULL,
  8507. &callback_data)) {
  8508. /* 5.2.1. A callback will handle this request. All requests
  8509. * handled
  8510. * by a callback have to be considered as requests to a script
  8511. * resource. */
  8512. is_callback_resource = 1;
  8513. is_script_resource = 1;
  8514. is_put_or_delete_request = is_put_or_delete_method(conn);
  8515. } else {
  8516. no_callback_resource:
  8517. /* 5.2.2. No callback is responsible for this request. The URI
  8518. * addresses a file based resource (static content or Lua/cgi
  8519. * scripts in the file system). */
  8520. is_callback_resource = 0;
  8521. interpret_uri(conn,
  8522. path,
  8523. sizeof(path),
  8524. &file,
  8525. &is_found,
  8526. &is_script_resource,
  8527. &is_websocket_request,
  8528. &is_put_or_delete_request);
  8529. }
  8530. /* 6. authorization check */
  8531. /* 6.1. a custom authorization handler is installed */
  8532. if (get_request_handler(conn,
  8533. AUTH_HANDLER,
  8534. NULL,
  8535. NULL,
  8536. NULL,
  8537. NULL,
  8538. NULL,
  8539. &auth_handler,
  8540. &auth_callback_data)) {
  8541. if (!auth_handler(conn, auth_callback_data)) {
  8542. return;
  8543. }
  8544. } else if (is_put_or_delete_request && !is_script_resource
  8545. && !is_callback_resource) {
  8546. /* 6.2. this request is a PUT/DELETE to a real file */
  8547. /* 6.2.1. thus, the server must have real files */
  8548. #if defined(NO_FILES)
  8549. if (1) {
  8550. #else
  8551. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8552. #endif
  8553. /* This server does not have any real files, thus the
  8554. * PUT/DELETE methods are not valid. */
  8555. send_http_error(conn,
  8556. 405,
  8557. "%s method not allowed",
  8558. conn->request_info.request_method);
  8559. return;
  8560. }
  8561. #if !defined(NO_FILES)
  8562. /* 6.2.2. Check if put authorization for static files is
  8563. * available.
  8564. */
  8565. if (!is_authorized_for_put(conn)) {
  8566. send_authorization_request(conn);
  8567. return;
  8568. }
  8569. #endif
  8570. } else {
  8571. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8572. * or it is a PUT or DELETE request to a resource that does not
  8573. * correspond to a file. Check authorization. */
  8574. if (!check_authorization(conn, path)) {
  8575. send_authorization_request(conn);
  8576. return;
  8577. }
  8578. }
  8579. /* request is authorized or does not need authorization */
  8580. /* 7. check if there are request handlers for this uri */
  8581. if (is_callback_resource) {
  8582. if (!is_websocket_request) {
  8583. i = callback_handler(conn, callback_data);
  8584. if (i > 0) {
  8585. /* Do nothing, callback has served the request. Store
  8586. * the
  8587. * return value as status code for the log and discard
  8588. * all
  8589. * data from the client not used by the callback. */
  8590. conn->status_code = i;
  8591. discard_unread_request_data(conn);
  8592. } else {
  8593. /* TODO (high): what if the handler did NOT handle the
  8594. * request */
  8595. /* The last version did handle this as a file request,
  8596. * but
  8597. * since a file request is not always a script resource,
  8598. * the authorization check might be different */
  8599. interpret_uri(conn,
  8600. path,
  8601. sizeof(path),
  8602. &file,
  8603. &is_found,
  8604. &is_script_resource,
  8605. &is_websocket_request,
  8606. &is_put_or_delete_request);
  8607. callback_handler = NULL;
  8608. /* TODO (very low): goto is deprecated but for the
  8609. * moment,
  8610. * a goto is simpler than some curious loop. */
  8611. /* The situation "callback does not handle the request"
  8612. * needs to be reconsidered anyway. */
  8613. goto no_callback_resource;
  8614. }
  8615. } else {
  8616. #if defined(USE_WEBSOCKET)
  8617. handle_websocket_request(conn,
  8618. path,
  8619. is_callback_resource,
  8620. ws_connect_handler,
  8621. ws_ready_handler,
  8622. ws_data_handler,
  8623. ws_close_handler,
  8624. callback_data);
  8625. #endif
  8626. }
  8627. return;
  8628. }
  8629. /* 8. handle websocket requests */
  8630. #if defined(USE_WEBSOCKET)
  8631. if (is_websocket_request) {
  8632. if (is_script_resource) {
  8633. /* Websocket Lua script */
  8634. handle_websocket_request(conn,
  8635. path,
  8636. 0 /* Lua Script */,
  8637. NULL,
  8638. NULL,
  8639. NULL,
  8640. NULL,
  8641. &conn->ctx->callbacks);
  8642. } else {
  8643. #if defined(MG_LEGACY_INTERFACE)
  8644. handle_websocket_request(
  8645. conn,
  8646. path,
  8647. !is_script_resource /* could be deprecated global callback */,
  8648. deprecated_websocket_connect_wrapper,
  8649. deprecated_websocket_ready_wrapper,
  8650. deprecated_websocket_data_wrapper,
  8651. NULL,
  8652. &conn->ctx->callbacks);
  8653. #else
  8654. send_http_error(conn, 404, "%s", "Not found");
  8655. #endif
  8656. }
  8657. return;
  8658. } else
  8659. #endif
  8660. #if defined(NO_FILES)
  8661. /* 9a. In case the server uses only callbacks, this uri is
  8662. * unknown.
  8663. * Then, all request handling ends here. */
  8664. send_http_error(conn, 404, "%s", "Not Found");
  8665. #else
  8666. /* 9b. This request is either for a static file or resource handled
  8667. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8668. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8669. send_http_error(conn, 404, "%s", "Not Found");
  8670. return;
  8671. }
  8672. /* 10. File is handled by a script. */
  8673. if (is_script_resource) {
  8674. handle_file_based_request(conn, path, &file);
  8675. return;
  8676. }
  8677. /* 11. Handle put/delete/mkcol requests */
  8678. if (is_put_or_delete_request) {
  8679. /* 11.1. PUT method */
  8680. if (!strcmp(ri->request_method, "PUT")) {
  8681. put_file(conn, path);
  8682. return;
  8683. }
  8684. /* 11.2. DELETE method */
  8685. if (!strcmp(ri->request_method, "DELETE")) {
  8686. delete_file(conn, path);
  8687. return;
  8688. }
  8689. /* 11.3. MKCOL method */
  8690. if (!strcmp(ri->request_method, "MKCOL")) {
  8691. mkcol(conn, path);
  8692. return;
  8693. }
  8694. /* 11.4. PATCH method
  8695. * This method is not supported for static resources,
  8696. * only for scripts (Lua, CGI) and callbacks. */
  8697. send_http_error(conn,
  8698. 405,
  8699. "%s method not allowed",
  8700. conn->request_info.request_method);
  8701. return;
  8702. }
  8703. /* 11. File does not exist, or it was configured that it should be
  8704. * hidden */
  8705. if (!is_found || (must_hide_file(conn, path))) {
  8706. send_http_error(conn, 404, "%s", "Not found");
  8707. return;
  8708. }
  8709. /* 12. Directory uris should end with a slash */
  8710. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8711. gmt_time_string(date, sizeof(date), &curtime);
  8712. mg_printf(conn,
  8713. "HTTP/1.1 301 Moved Permanently\r\n"
  8714. "Location: %s/\r\n"
  8715. "Date: %s\r\n"
  8716. /* "Cache-Control: private\r\n" (= default) */
  8717. "Content-Length: 0\r\n"
  8718. "Connection: %s\r\n\r\n",
  8719. ri->request_uri,
  8720. date,
  8721. suggest_connection_header(conn));
  8722. return;
  8723. }
  8724. /* 13. Handle other methods than GET/HEAD */
  8725. /* 13.1. Handle PROPFIND */
  8726. if (!strcmp(ri->request_method, "PROPFIND")) {
  8727. handle_propfind(conn, path, &file);
  8728. return;
  8729. }
  8730. /* 13.2. Handle OPTIONS for files */
  8731. if (!strcmp(ri->request_method, "OPTIONS")) {
  8732. /* This standard handler is only used for real files.
  8733. * Scripts should support the OPTIONS method themselves, to allow a
  8734. * maximum flexibility.
  8735. * Lua and CGI scripts may fully support CORS this way (including
  8736. * preflights). */
  8737. send_options(conn);
  8738. return;
  8739. }
  8740. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8741. if (0 != strcmp(ri->request_method, "GET")
  8742. && 0 != strcmp(ri->request_method, "HEAD")) {
  8743. send_http_error(conn,
  8744. 405,
  8745. "%s method not allowed",
  8746. conn->request_info.request_method);
  8747. return;
  8748. }
  8749. /* 14. directories */
  8750. if (file.is_directory) {
  8751. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8752. /* 14.1. use a substitute file */
  8753. /* TODO (high): substitute index may be a script resource.
  8754. * define what should be possible in this case. */
  8755. } else {
  8756. /* 14.2. no substitute file */
  8757. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8758. "yes")) {
  8759. handle_directory_request(conn, path);
  8760. } else {
  8761. send_http_error(conn,
  8762. 403,
  8763. "%s",
  8764. "Error: Directory listing denied");
  8765. }
  8766. return;
  8767. }
  8768. }
  8769. handle_file_based_request(conn, path, &file);
  8770. #endif /* !defined(NO_FILES) */
  8771. #if 0
  8772. /* Perform redirect and auth checks before calling begin_request()
  8773. * handler.
  8774. * Otherwise, begin_request() would need to perform auth checks and
  8775. * redirects. */
  8776. #endif
  8777. }
  8778. return;
  8779. }
  8780. static void
  8781. handle_file_based_request(struct mg_connection *conn,
  8782. const char *path,
  8783. struct file *file)
  8784. {
  8785. if (!conn || !conn->ctx) {
  8786. return;
  8787. }
  8788. if (0) {
  8789. #ifdef USE_LUA
  8790. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8791. strlen(
  8792. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8793. path) > 0) {
  8794. /* Lua server page: an SSI like page containing mostly plain html
  8795. * code
  8796. * plus some tags with server generated contents. */
  8797. handle_lsp_request(conn, path, file, NULL);
  8798. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8799. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8800. path) > 0) {
  8801. /* Lua in-server module script: a CGI like script used to generate
  8802. * the
  8803. * entire reply. */
  8804. mg_exec_lua_script(conn, path, NULL);
  8805. #endif
  8806. #if defined(USE_DUKTAPE)
  8807. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8808. strlen(
  8809. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8810. path) > 0) {
  8811. /* Call duktape to generate the page */
  8812. mg_exec_duktape_script(conn, path);
  8813. #endif
  8814. #if !defined(NO_CGI)
  8815. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8816. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8817. path) > 0) {
  8818. /* CGI scripts may support all HTTP methods */
  8819. handle_cgi_request(conn, path);
  8820. #endif /* !NO_CGI */
  8821. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8822. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8823. path) > 0) {
  8824. handle_ssi_file_request(conn, path, file);
  8825. #if !defined(NO_CACHING)
  8826. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8827. /* Send 304 "Not Modified" - this must not send any body data */
  8828. send_http_error(conn, 304, "%s", "");
  8829. #endif /* !NO_CACHING */
  8830. } else {
  8831. handle_static_file_request(conn, path, file, NULL);
  8832. }
  8833. }
  8834. static void
  8835. close_all_listening_sockets(struct mg_context *ctx)
  8836. {
  8837. unsigned int i;
  8838. if (!ctx) {
  8839. return;
  8840. }
  8841. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8842. closesocket(ctx->listening_sockets[i].sock);
  8843. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8844. }
  8845. mg_free(ctx->listening_sockets);
  8846. ctx->listening_sockets = NULL;
  8847. mg_free(ctx->listening_ports);
  8848. ctx->listening_ports = NULL;
  8849. }
  8850. /* Valid listening port specification is: [ip_address:]port[s]
  8851. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8852. * Examples for IPv6: [::]:80, [::1]:80,
  8853. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8854. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8855. static int
  8856. parse_port_string(const struct vec *vec, struct socket *so)
  8857. {
  8858. unsigned int a, b, c, d, port;
  8859. int ch, len;
  8860. #if defined(USE_IPV6)
  8861. char buf[100] = {0};
  8862. #endif
  8863. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8864. * Also, all-zeroes in the socket address means binding to all addresses
  8865. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8866. memset(so, 0, sizeof(*so));
  8867. so->lsa.sin.sin_family = AF_INET;
  8868. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8869. == 5) {
  8870. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8871. so->lsa.sin.sin_addr.s_addr =
  8872. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8873. so->lsa.sin.sin_port = htons((uint16_t)port);
  8874. #if defined(USE_IPV6)
  8875. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8876. && mg_inet_pton(
  8877. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8878. /* IPv6 address, examples: see above */
  8879. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8880. */
  8881. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8882. #endif
  8883. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8884. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8885. so->lsa.sin.sin_port = htons((uint16_t)port);
  8886. } else {
  8887. /* Parsing failure. Make port invalid. */
  8888. port = 0;
  8889. len = 0;
  8890. }
  8891. /* sscanf and the option splitting code ensure the following condition
  8892. */
  8893. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8894. return 0;
  8895. }
  8896. ch = vec->ptr[len]; /* Next character after the port number */
  8897. so->is_ssl = (ch == 's');
  8898. so->ssl_redir = (ch == 'r');
  8899. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8900. return is_valid_port(port)
  8901. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8902. }
  8903. static int
  8904. set_ports_option(struct mg_context *ctx)
  8905. {
  8906. const char *list;
  8907. int on = 1;
  8908. #if defined(USE_IPV6)
  8909. int off = 0;
  8910. #endif
  8911. struct vec vec;
  8912. struct socket so, *ptr;
  8913. in_port_t *portPtr;
  8914. union usa usa;
  8915. socklen_t len;
  8916. int portsTotal = 0;
  8917. int portsOk = 0;
  8918. if (!ctx) {
  8919. return 0;
  8920. }
  8921. memset(&so, 0, sizeof(so));
  8922. memset(&usa, 0, sizeof(usa));
  8923. len = sizeof(usa);
  8924. list = ctx->config[LISTENING_PORTS];
  8925. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8926. portsTotal++;
  8927. if (!parse_port_string(&vec, &so)) {
  8928. mg_cry(fc(ctx),
  8929. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8930. (int)vec.len,
  8931. vec.ptr,
  8932. portsTotal,
  8933. "[IP_ADDRESS:]PORT[s|r]");
  8934. continue;
  8935. }
  8936. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8937. mg_cry(fc(ctx),
  8938. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8939. "option set?",
  8940. portsTotal);
  8941. continue;
  8942. }
  8943. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8944. == INVALID_SOCKET) {
  8945. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8946. continue;
  8947. }
  8948. #ifdef _WIN32
  8949. /* Windows SO_REUSEADDR lets many procs binds to a
  8950. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8951. * if someone already has the socket -- DTL */
  8952. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8953. * Windows might need a few seconds before
  8954. * the same port can be used again in the
  8955. * same process, so a short Sleep may be
  8956. * required between mg_stop and mg_start.
  8957. */
  8958. if (setsockopt(so.sock,
  8959. SOL_SOCKET,
  8960. SO_EXCLUSIVEADDRUSE,
  8961. (SOCK_OPT_TYPE)&on,
  8962. sizeof(on)) != 0) {
  8963. mg_cry(fc(ctx),
  8964. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8965. portsTotal);
  8966. }
  8967. #else
  8968. if (setsockopt(so.sock,
  8969. SOL_SOCKET,
  8970. SO_REUSEADDR,
  8971. (SOCK_OPT_TYPE)&on,
  8972. sizeof(on)) != 0) {
  8973. mg_cry(fc(ctx),
  8974. "cannot set socket option SO_REUSEADDR (entry %i)",
  8975. portsTotal);
  8976. }
  8977. #endif
  8978. #if defined(USE_IPV6)
  8979. if (so.lsa.sa.sa_family == AF_INET6
  8980. && setsockopt(so.sock,
  8981. IPPROTO_IPV6,
  8982. IPV6_V6ONLY,
  8983. (void *)&off,
  8984. sizeof(off)) != 0) {
  8985. mg_cry(fc(ctx),
  8986. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8987. portsTotal);
  8988. }
  8989. #endif
  8990. if (so.lsa.sa.sa_family == AF_INET) {
  8991. len = sizeof(so.lsa.sin);
  8992. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8993. mg_cry(fc(ctx),
  8994. "cannot bind to %.*s: %d (%s)",
  8995. (int)vec.len,
  8996. vec.ptr,
  8997. (int)ERRNO,
  8998. strerror(errno));
  8999. closesocket(so.sock);
  9000. so.sock = INVALID_SOCKET;
  9001. continue;
  9002. }
  9003. }
  9004. #if defined(USE_IPV6)
  9005. else if (so.lsa.sa.sa_family == AF_INET6) {
  9006. len = sizeof(so.lsa.sin6);
  9007. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9008. mg_cry(fc(ctx),
  9009. "cannot bind to IPv6 %.*s: %d (%s)",
  9010. (int)vec.len,
  9011. vec.ptr,
  9012. (int)ERRNO,
  9013. strerror(errno));
  9014. closesocket(so.sock);
  9015. so.sock = INVALID_SOCKET;
  9016. continue;
  9017. }
  9018. }
  9019. #endif
  9020. else {
  9021. mg_cry(fc(ctx),
  9022. "cannot bind: address family not supported (entry %i)",
  9023. portsTotal);
  9024. continue;
  9025. }
  9026. if (listen(so.sock, SOMAXCONN) != 0) {
  9027. mg_cry(fc(ctx),
  9028. "cannot listen to %.*s: %d (%s)",
  9029. (int)vec.len,
  9030. vec.ptr,
  9031. (int)ERRNO,
  9032. strerror(errno));
  9033. closesocket(so.sock);
  9034. so.sock = INVALID_SOCKET;
  9035. continue;
  9036. }
  9037. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  9038. int err = (int)ERRNO;
  9039. mg_cry(fc(ctx),
  9040. "call to getsockname failed %.*s: %d (%s)",
  9041. (int)vec.len,
  9042. vec.ptr,
  9043. err,
  9044. strerror(errno));
  9045. closesocket(so.sock);
  9046. so.sock = INVALID_SOCKET;
  9047. continue;
  9048. }
  9049. if ((ptr = (struct socket *)
  9050. mg_realloc(ctx->listening_sockets,
  9051. (ctx->num_listening_sockets + 1)
  9052. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9053. mg_cry(fc(ctx), "%s", "Out of memory");
  9054. closesocket(so.sock);
  9055. so.sock = INVALID_SOCKET;
  9056. continue;
  9057. }
  9058. if ((portPtr =
  9059. (in_port_t *)mg_realloc(ctx->listening_ports,
  9060. (ctx->num_listening_sockets + 1)
  9061. * sizeof(ctx->listening_ports[0])))
  9062. == NULL) {
  9063. mg_cry(fc(ctx), "%s", "Out of memory");
  9064. closesocket(so.sock);
  9065. so.sock = INVALID_SOCKET;
  9066. mg_free(ptr);
  9067. continue;
  9068. }
  9069. set_close_on_exec(so.sock, fc(ctx));
  9070. ctx->listening_sockets = ptr;
  9071. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9072. ctx->listening_ports = portPtr;
  9073. ctx->listening_ports[ctx->num_listening_sockets] =
  9074. ntohs(usa.sin.sin_port);
  9075. ctx->num_listening_sockets++;
  9076. portsOk++;
  9077. }
  9078. if (portsOk != portsTotal) {
  9079. close_all_listening_sockets(ctx);
  9080. portsOk = 0;
  9081. }
  9082. return portsOk;
  9083. }
  9084. static const char *
  9085. header_val(const struct mg_connection *conn, const char *header)
  9086. {
  9087. const char *header_value;
  9088. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9089. return "-";
  9090. } else {
  9091. return header_value;
  9092. }
  9093. }
  9094. static void
  9095. log_access(const struct mg_connection *conn)
  9096. {
  9097. const struct mg_request_info *ri;
  9098. struct file fi;
  9099. char date[64], src_addr[IP_ADDR_STR_LEN];
  9100. struct tm *tm;
  9101. const char *referer;
  9102. const char *user_agent;
  9103. char buf[4096];
  9104. if (!conn || !conn->ctx) {
  9105. return;
  9106. }
  9107. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9108. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9109. == 0) {
  9110. fi.fp = NULL;
  9111. }
  9112. } else {
  9113. fi.fp = NULL;
  9114. }
  9115. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9116. return;
  9117. }
  9118. tm = localtime(&conn->conn_birth_time);
  9119. if (tm != NULL) {
  9120. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9121. } else {
  9122. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9123. date[sizeof(date) - 1] = '\0';
  9124. }
  9125. ri = &conn->request_info;
  9126. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9127. referer = header_val(conn, "Referer");
  9128. user_agent = header_val(conn, "User-Agent");
  9129. mg_snprintf(conn,
  9130. NULL, /* Ignore truncation in access log */
  9131. buf,
  9132. sizeof(buf),
  9133. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9134. src_addr,
  9135. ri->remote_user == NULL ? "-" : ri->remote_user,
  9136. date,
  9137. ri->request_method ? ri->request_method : "-",
  9138. ri->request_uri ? ri->request_uri : "-",
  9139. ri->query_string ? "?" : "",
  9140. ri->query_string ? ri->query_string : "",
  9141. ri->http_version,
  9142. conn->status_code,
  9143. conn->num_bytes_sent,
  9144. referer,
  9145. user_agent);
  9146. if (conn->ctx->callbacks.log_access) {
  9147. conn->ctx->callbacks.log_access(conn, buf);
  9148. }
  9149. if (fi.fp) {
  9150. flockfile(fi.fp);
  9151. fprintf(fi.fp, "%s\n", buf);
  9152. fflush(fi.fp);
  9153. funlockfile(fi.fp);
  9154. mg_fclose(&fi);
  9155. }
  9156. }
  9157. /* Verify given socket address against the ACL.
  9158. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9159. */
  9160. static int
  9161. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9162. {
  9163. int allowed, flag;
  9164. uint32_t net, mask;
  9165. struct vec vec;
  9166. if (ctx) {
  9167. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9168. /* If any ACL is set, deny by default */
  9169. allowed = list == NULL ? '+' : '-';
  9170. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9171. flag = vec.ptr[0];
  9172. if ((flag != '+' && flag != '-')
  9173. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9174. mg_cry(fc(ctx),
  9175. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9176. __func__);
  9177. return -1;
  9178. }
  9179. if (net == (remote_ip & mask)) {
  9180. allowed = flag;
  9181. }
  9182. }
  9183. return allowed == '+';
  9184. }
  9185. return -1;
  9186. }
  9187. #if !defined(_WIN32)
  9188. static int
  9189. set_uid_option(struct mg_context *ctx)
  9190. {
  9191. struct passwd *pw;
  9192. if (ctx) {
  9193. const char *uid = ctx->config[RUN_AS_USER];
  9194. int success = 0;
  9195. if (uid == NULL) {
  9196. success = 1;
  9197. } else {
  9198. if ((pw = getpwnam(uid)) == NULL) {
  9199. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9200. } else if (setgid(pw->pw_gid) == -1) {
  9201. mg_cry(fc(ctx),
  9202. "%s: setgid(%s): %s",
  9203. __func__,
  9204. uid,
  9205. strerror(errno));
  9206. } else if (setgroups(0, NULL)) {
  9207. mg_cry(fc(ctx),
  9208. "%s: setgroups(): %s",
  9209. __func__,
  9210. strerror(errno));
  9211. } else if (setuid(pw->pw_uid) == -1) {
  9212. mg_cry(fc(ctx),
  9213. "%s: setuid(%s): %s",
  9214. __func__,
  9215. uid,
  9216. strerror(errno));
  9217. } else {
  9218. success = 1;
  9219. }
  9220. }
  9221. return success;
  9222. }
  9223. return 0;
  9224. }
  9225. #endif /* !_WIN32 */
  9226. static void
  9227. tls_dtor(void *key)
  9228. {
  9229. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9230. /* key == pthread_getspecific(sTlsKey); */
  9231. if (tls) {
  9232. if (tls->is_master == 2) {
  9233. tls->is_master = -3; /* Mark memory as dead */
  9234. mg_free(tls);
  9235. }
  9236. }
  9237. pthread_setspecific(sTlsKey, NULL);
  9238. }
  9239. #if !defined(NO_SSL)
  9240. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9241. static unsigned long
  9242. ssl_id_callback(void)
  9243. {
  9244. #ifdef _WIN32
  9245. return GetCurrentThreadId();
  9246. #else
  9247. #ifdef __clang__
  9248. #pragma clang diagnostic push
  9249. #pragma clang diagnostic ignored "-Wunreachable-code"
  9250. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9251. * or not, so one of the two conditions will be unreachable by construction.
  9252. * Unfortunately the C standard does not define a way to check this at
  9253. * compile time, since the #if preprocessor conditions can not use the sizeof
  9254. * operator as an argument. */
  9255. #endif
  9256. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9257. /* This is the problematic case for CRYPTO_set_id_callback:
  9258. * The OS pthread_t can not be cast to unsigned long. */
  9259. struct mg_workerTLS *tls =
  9260. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9261. if (tls == NULL) {
  9262. /* SSL called from an unknown thread: Create some thread index.
  9263. */
  9264. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9265. tls->is_master = -2; /* -2 means "3rd party thread" */
  9266. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9267. pthread_setspecific(sTlsKey, tls);
  9268. }
  9269. return tls->thread_idx;
  9270. } else {
  9271. /* pthread_t may be any data type, so a simple cast to unsigned long
  9272. * can rise a warning/error, depending on the platform.
  9273. * Here memcpy is used as an anything-to-anything cast. */
  9274. unsigned long ret = 0;
  9275. pthread_t t = pthread_self();
  9276. memcpy(&ret, &t, sizeof(pthread_t));
  9277. return ret;
  9278. }
  9279. #ifdef __clang__
  9280. #pragma clang diagnostic pop
  9281. #endif
  9282. #endif
  9283. }
  9284. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9285. static const char *ssl_error(void);
  9286. static int
  9287. refresh_trust(struct mg_connection *conn)
  9288. {
  9289. static int reload_lock = 0;
  9290. static long int data_check = 0;
  9291. struct stat cert_buf;
  9292. long int t;
  9293. char *pem;
  9294. int should_verify_peer;
  9295. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9296. && conn->ctx->callbacks.init_ssl == NULL) {
  9297. return 0;
  9298. }
  9299. t = data_check;
  9300. if (stat(pem, &cert_buf) != -1) {
  9301. t = (long int)cert_buf.st_mtime;
  9302. }
  9303. if (data_check != t) {
  9304. data_check = t;
  9305. should_verify_peer =
  9306. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9307. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9308. == 0);
  9309. if (should_verify_peer) {
  9310. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9311. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9312. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9313. ca_file,
  9314. ca_path) != 1) {
  9315. mg_cry(fc(conn->ctx),
  9316. "SSL_CTX_load_verify_locations error: %s "
  9317. "ssl_verify_peer requires setting "
  9318. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9319. "present in "
  9320. "the .conf file?",
  9321. ssl_error());
  9322. return 0;
  9323. }
  9324. }
  9325. if (!reload_lock) {
  9326. reload_lock = 1;
  9327. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9328. return 0;
  9329. }
  9330. reload_lock = 0;
  9331. }
  9332. }
  9333. /* lock while cert is reloading */
  9334. while (reload_lock) {
  9335. sleep(1);
  9336. }
  9337. return 1;
  9338. }
  9339. static pthread_mutex_t *ssl_mutexes;
  9340. static int
  9341. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9342. {
  9343. int ret, err;
  9344. int short_trust;
  9345. if (!conn) {
  9346. return 0;
  9347. }
  9348. short_trust =
  9349. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9350. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9351. if (short_trust) {
  9352. int trust_ret = refresh_trust(conn);
  9353. if (!trust_ret) {
  9354. return trust_ret;
  9355. }
  9356. }
  9357. conn->ssl = SSL_new(s);
  9358. if (conn->ssl == NULL) {
  9359. return 0;
  9360. }
  9361. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9362. if (ret != 1) {
  9363. err = SSL_get_error(conn->ssl, ret);
  9364. (void)err; /* TODO: set some error message */
  9365. SSL_free(conn->ssl);
  9366. conn->ssl = NULL;
  9367. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9368. /* see
  9369. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9370. ERR_remove_state(0);
  9371. return 0;
  9372. }
  9373. ret = func(conn->ssl);
  9374. if (ret != 1) {
  9375. err = SSL_get_error(conn->ssl, ret);
  9376. (void)err; /* TODO: set some error message */
  9377. SSL_free(conn->ssl);
  9378. conn->ssl = NULL;
  9379. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9380. /* see
  9381. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9382. ERR_remove_state(0);
  9383. return 0;
  9384. }
  9385. return 1;
  9386. }
  9387. /* Return OpenSSL error message (from CRYPTO lib) */
  9388. static const char *
  9389. ssl_error(void)
  9390. {
  9391. unsigned long err;
  9392. err = ERR_get_error();
  9393. return err == 0 ? "" : ERR_error_string(err, NULL);
  9394. }
  9395. static void
  9396. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9397. {
  9398. (void)line;
  9399. (void)file;
  9400. if (mode & 1) {
  9401. /* 1 is CRYPTO_LOCK */
  9402. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9403. } else {
  9404. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9405. }
  9406. }
  9407. #if !defined(NO_SSL_DL)
  9408. static void *
  9409. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9410. {
  9411. union {
  9412. void *p;
  9413. void (*fp)(void);
  9414. } u;
  9415. void *dll_handle;
  9416. struct ssl_func *fp;
  9417. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9418. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9419. return NULL;
  9420. }
  9421. for (fp = sw; fp->name != NULL; fp++) {
  9422. #ifdef _WIN32
  9423. /* GetProcAddress() returns pointer to function */
  9424. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9425. #else
  9426. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9427. * pointers to function pointers. We need to use a union to make a
  9428. * cast. */
  9429. u.p = dlsym(dll_handle, fp->name);
  9430. #endif /* _WIN32 */
  9431. if (u.fp == NULL) {
  9432. mg_cry(fc(ctx),
  9433. "%s: %s: cannot find %s",
  9434. __func__,
  9435. dll_name,
  9436. fp->name);
  9437. dlclose(dll_handle);
  9438. return NULL;
  9439. } else {
  9440. fp->ptr = u.fp;
  9441. }
  9442. }
  9443. return dll_handle;
  9444. }
  9445. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9446. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9447. #endif /* NO_SSL_DL */
  9448. #if defined(SSL_ALREADY_INITIALIZED)
  9449. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9450. #else
  9451. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9452. #endif
  9453. static int
  9454. initialize_ssl(struct mg_context *ctx)
  9455. {
  9456. int i;
  9457. size_t size;
  9458. #if !defined(NO_SSL_DL)
  9459. if (!cryptolib_dll_handle) {
  9460. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9461. if (!cryptolib_dll_handle) {
  9462. return 0;
  9463. }
  9464. }
  9465. #endif /* NO_SSL_DL */
  9466. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9467. return 1;
  9468. }
  9469. /* Initialize locking callbacks, needed for thread safety.
  9470. * http://www.openssl.org/support/faq.html#PROG1
  9471. */
  9472. i = CRYPTO_num_locks();
  9473. if (i < 0) {
  9474. i = 0;
  9475. }
  9476. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9477. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9478. mg_cry(fc(ctx),
  9479. "%s: cannot allocate mutexes: %s",
  9480. __func__,
  9481. ssl_error());
  9482. return 0;
  9483. }
  9484. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9485. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9486. }
  9487. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9488. CRYPTO_set_id_callback(&ssl_id_callback);
  9489. return 1;
  9490. }
  9491. static int
  9492. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9493. {
  9494. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9495. mg_cry(fc(ctx),
  9496. "%s: cannot open certificate file %s: %s",
  9497. __func__,
  9498. pem,
  9499. ssl_error());
  9500. return 0;
  9501. }
  9502. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9503. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9504. mg_cry(fc(ctx),
  9505. "%s: cannot open private key file %s: %s",
  9506. __func__,
  9507. pem,
  9508. ssl_error());
  9509. return 0;
  9510. }
  9511. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9512. mg_cry(fc(ctx),
  9513. "%s: certificate and private key do not match: %s",
  9514. __func__,
  9515. pem);
  9516. return 0;
  9517. }
  9518. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9519. mg_cry(fc(ctx),
  9520. "%s: cannot use certificate chain file %s: %s",
  9521. __func__,
  9522. pem,
  9523. ssl_error());
  9524. return 0;
  9525. }
  9526. return 1;
  9527. }
  9528. static long
  9529. ssl_get_protocol(int version_id)
  9530. {
  9531. long ret = SSL_OP_ALL;
  9532. if (version_id > 0)
  9533. ret |= SSL_OP_NO_SSLv2;
  9534. if (version_id > 1)
  9535. ret |= SSL_OP_NO_SSLv3;
  9536. if (version_id > 2)
  9537. ret |= SSL_OP_NO_TLSv1;
  9538. if (version_id > 3)
  9539. ret |= SSL_OP_NO_TLSv1_1;
  9540. return ret;
  9541. }
  9542. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9543. static int
  9544. set_ssl_option(struct mg_context *ctx)
  9545. {
  9546. const char *pem;
  9547. int callback_ret;
  9548. int should_verify_peer;
  9549. const char *ca_path;
  9550. const char *ca_file;
  9551. int use_default_verify_paths;
  9552. int verify_depth;
  9553. time_t now_rt = time(NULL);
  9554. struct timespec now_mt;
  9555. md5_byte_t ssl_context_id[16];
  9556. md5_state_t md5state;
  9557. int protocol_ver;
  9558. /* If PEM file is not specified and the init_ssl callback
  9559. * is not specified, skip SSL initialization. */
  9560. if (!ctx) {
  9561. return 0;
  9562. }
  9563. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9564. && ctx->callbacks.init_ssl == NULL) {
  9565. return 1;
  9566. }
  9567. if (!initialize_ssl(ctx)) {
  9568. return 0;
  9569. }
  9570. #if !defined(NO_SSL_DL)
  9571. if (!ssllib_dll_handle) {
  9572. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9573. if (!ssllib_dll_handle) {
  9574. return 0;
  9575. }
  9576. }
  9577. #endif /* NO_SSL_DL */
  9578. /* Initialize SSL library */
  9579. SSL_library_init();
  9580. SSL_load_error_strings();
  9581. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9582. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9583. return 0;
  9584. }
  9585. SSL_CTX_clear_options(ctx->ssl_ctx,
  9586. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9587. | SSL_OP_NO_TLSv1_1);
  9588. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9589. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9590. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9591. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9592. /* If a callback has been specified, call it. */
  9593. callback_ret =
  9594. (ctx->callbacks.init_ssl == NULL)
  9595. ? 0
  9596. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9597. /* If callback returns 0, civetweb sets up the SSL certificate.
  9598. * If it returns 1, civetweb assumes the calback already did this.
  9599. * If it returns -1, initializing ssl fails. */
  9600. if (callback_ret < 0) {
  9601. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9602. return 0;
  9603. }
  9604. if (callback_ret > 0) {
  9605. if (pem != NULL) {
  9606. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9607. }
  9608. return 1;
  9609. }
  9610. /* Use some UID as session context ID. */
  9611. md5_init(&md5state);
  9612. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9613. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9614. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9615. md5_append(&md5state,
  9616. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9617. strlen(ctx->config[LISTENING_PORTS]));
  9618. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9619. md5_finish(&md5state, ssl_context_id);
  9620. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9621. (const unsigned char *)&ssl_context_id,
  9622. sizeof(ssl_context_id));
  9623. if (pem != NULL) {
  9624. if (!ssl_use_pem_file(ctx, pem)) {
  9625. return 0;
  9626. }
  9627. }
  9628. should_verify_peer =
  9629. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9630. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9631. use_default_verify_paths =
  9632. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9633. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9634. if (should_verify_peer) {
  9635. ca_path = ctx->config[SSL_CA_PATH];
  9636. ca_file = ctx->config[SSL_CA_FILE];
  9637. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9638. != 1) {
  9639. mg_cry(fc(ctx),
  9640. "SSL_CTX_load_verify_locations error: %s "
  9641. "ssl_verify_peer requires setting "
  9642. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9643. "present in "
  9644. "the .conf file?",
  9645. ssl_error());
  9646. return 0;
  9647. }
  9648. SSL_CTX_set_verify(ctx->ssl_ctx,
  9649. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9650. NULL);
  9651. if (use_default_verify_paths
  9652. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9653. mg_cry(fc(ctx),
  9654. "SSL_CTX_set_default_verify_paths error: %s",
  9655. ssl_error());
  9656. return 0;
  9657. }
  9658. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9659. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9660. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9661. }
  9662. }
  9663. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9664. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9665. != 1) {
  9666. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9667. }
  9668. }
  9669. return 1;
  9670. }
  9671. static void
  9672. uninitialize_ssl(struct mg_context *ctx)
  9673. {
  9674. int i;
  9675. (void)ctx;
  9676. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9677. /* Shutdown according to
  9678. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9679. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9680. */
  9681. CRYPTO_set_locking_callback(NULL);
  9682. CRYPTO_set_id_callback(NULL);
  9683. ENGINE_cleanup();
  9684. CONF_modules_unload(1);
  9685. ERR_free_strings();
  9686. EVP_cleanup();
  9687. CRYPTO_cleanup_all_ex_data();
  9688. ERR_remove_state(0);
  9689. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9690. pthread_mutex_destroy(&ssl_mutexes[i]);
  9691. }
  9692. mg_free(ssl_mutexes);
  9693. ssl_mutexes = NULL;
  9694. }
  9695. }
  9696. #endif /* !NO_SSL */
  9697. static int
  9698. set_gpass_option(struct mg_context *ctx)
  9699. {
  9700. if (ctx) {
  9701. struct file file = STRUCT_FILE_INITIALIZER;
  9702. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9703. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9704. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9705. return 0;
  9706. }
  9707. return 1;
  9708. }
  9709. return 0;
  9710. }
  9711. static int
  9712. set_acl_option(struct mg_context *ctx)
  9713. {
  9714. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9715. }
  9716. static void
  9717. reset_per_request_attributes(struct mg_connection *conn)
  9718. {
  9719. if (!conn) {
  9720. return;
  9721. }
  9722. conn->path_info = NULL;
  9723. conn->num_bytes_sent = conn->consumed_content = 0;
  9724. conn->status_code = -1;
  9725. conn->is_chunked = 0;
  9726. conn->must_close = conn->request_len = conn->throttle = 0;
  9727. conn->request_info.content_length = -1;
  9728. conn->request_info.remote_user = NULL;
  9729. conn->request_info.request_method = NULL;
  9730. conn->request_info.request_uri = NULL;
  9731. conn->request_info.local_uri = NULL;
  9732. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9733. * local_uri and request_uri */
  9734. conn->request_info.http_version = NULL;
  9735. conn->request_info.num_headers = 0;
  9736. conn->data_len = 0;
  9737. conn->chunk_remainder = 0;
  9738. conn->internal_error = 0;
  9739. }
  9740. static int
  9741. set_sock_timeout(SOCKET sock, int milliseconds)
  9742. {
  9743. int r0 = 0, r1, r2;
  9744. #ifdef _WIN32
  9745. /* Windows specific */
  9746. DWORD tv = (DWORD)milliseconds;
  9747. #else
  9748. /* Linux, ... (not Windows) */
  9749. struct timeval tv;
  9750. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9751. * max. time waiting for the acknowledged of TCP data before the connection
  9752. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9753. * If this option is not set, the default timeout of 20-30 minutes is used.
  9754. */
  9755. /* #define TCP_USER_TIMEOUT (18) */
  9756. #if defined(TCP_USER_TIMEOUT)
  9757. unsigned int uto = (unsigned int)milliseconds;
  9758. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9759. #endif
  9760. memset(&tv, 0, sizeof(tv));
  9761. tv.tv_sec = milliseconds / 1000;
  9762. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9763. #endif /* _WIN32 */
  9764. r1 = setsockopt(
  9765. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9766. r2 = setsockopt(
  9767. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9768. return r0 || r1 || r2;
  9769. }
  9770. static int
  9771. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9772. {
  9773. if (setsockopt(sock,
  9774. IPPROTO_TCP,
  9775. TCP_NODELAY,
  9776. (SOCK_OPT_TYPE)&nodelay_on,
  9777. sizeof(nodelay_on)) != 0) {
  9778. /* Error */
  9779. return 1;
  9780. }
  9781. /* OK */
  9782. return 0;
  9783. }
  9784. static void
  9785. close_socket_gracefully(struct mg_connection *conn)
  9786. {
  9787. #if defined(_WIN32)
  9788. char buf[MG_BUF_LEN];
  9789. int n;
  9790. #endif
  9791. struct linger linger;
  9792. if (!conn) {
  9793. return;
  9794. }
  9795. /* Set linger option to avoid socket hanging out after close. This
  9796. * prevent
  9797. * ephemeral port exhaust problem under high QPS. */
  9798. linger.l_onoff = 1;
  9799. linger.l_linger = 1;
  9800. if (setsockopt(conn->client.sock,
  9801. SOL_SOCKET,
  9802. SO_LINGER,
  9803. (char *)&linger,
  9804. sizeof(linger)) != 0) {
  9805. mg_cry(conn,
  9806. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9807. __func__,
  9808. strerror(ERRNO));
  9809. }
  9810. /* Send FIN to the client */
  9811. shutdown(conn->client.sock, SHUT_WR);
  9812. set_non_blocking_mode(conn->client.sock);
  9813. #if defined(_WIN32)
  9814. /* Read and discard pending incoming data. If we do not do that and
  9815. * close
  9816. * the socket, the data in the send buffer may be discarded. This
  9817. * behaviour is seen on Windows, when client keeps sending data
  9818. * when server decides to close the connection; then when client
  9819. * does recv() it gets no data back. */
  9820. do {
  9821. n = pull(
  9822. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9823. } while (n > 0);
  9824. #endif
  9825. /* Now we know that our FIN is ACK-ed, safe to close */
  9826. closesocket(conn->client.sock);
  9827. conn->client.sock = INVALID_SOCKET;
  9828. }
  9829. static void
  9830. close_connection(struct mg_connection *conn)
  9831. {
  9832. if (!conn || !conn->ctx) {
  9833. return;
  9834. }
  9835. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9836. if (conn->lua_websocket_state) {
  9837. lua_websocket_close(conn, conn->lua_websocket_state);
  9838. conn->lua_websocket_state = NULL;
  9839. }
  9840. #endif
  9841. /* call the connection_close callback if assigned */
  9842. if ((conn->ctx->callbacks.connection_close != NULL)
  9843. && (conn->ctx->context_type == 1)) {
  9844. conn->ctx->callbacks.connection_close(conn);
  9845. }
  9846. mg_lock_connection(conn);
  9847. conn->must_close = 1;
  9848. #ifndef NO_SSL
  9849. if (conn->ssl != NULL) {
  9850. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9851. */
  9852. SSL_shutdown(conn->ssl);
  9853. SSL_free(conn->ssl);
  9854. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9855. /* see
  9856. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9857. ERR_remove_state(0);
  9858. conn->ssl = NULL;
  9859. }
  9860. #endif
  9861. if (conn->client.sock != INVALID_SOCKET) {
  9862. close_socket_gracefully(conn);
  9863. conn->client.sock = INVALID_SOCKET;
  9864. }
  9865. mg_unlock_connection(conn);
  9866. }
  9867. void
  9868. mg_close_connection(struct mg_connection *conn)
  9869. {
  9870. struct mg_context *client_ctx = NULL;
  9871. unsigned int i;
  9872. if (conn == NULL) {
  9873. return;
  9874. }
  9875. if (conn->ctx->context_type == 2) {
  9876. client_ctx = conn->ctx;
  9877. /* client context: loops must end */
  9878. conn->ctx->stop_flag = 1;
  9879. }
  9880. #ifndef NO_SSL
  9881. if (conn->client_ssl_ctx != NULL) {
  9882. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9883. }
  9884. #endif
  9885. close_connection(conn);
  9886. if (client_ctx != NULL) {
  9887. /* join worker thread and free context */
  9888. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9889. if (client_ctx->workerthreadids[i] != 0) {
  9890. mg_join_thread(client_ctx->workerthreadids[i]);
  9891. }
  9892. }
  9893. mg_free(client_ctx->workerthreadids);
  9894. mg_free(client_ctx);
  9895. (void)pthread_mutex_destroy(&conn->mutex);
  9896. mg_free(conn);
  9897. }
  9898. }
  9899. static struct mg_connection *
  9900. mg_connect_client_impl(const struct mg_client_options *client_options,
  9901. int use_ssl,
  9902. char *ebuf,
  9903. size_t ebuf_len)
  9904. {
  9905. static struct mg_context fake_ctx;
  9906. struct mg_connection *conn = NULL;
  9907. SOCKET sock;
  9908. union usa sa;
  9909. if (!connect_socket(&fake_ctx,
  9910. client_options->host,
  9911. client_options->port,
  9912. use_ssl,
  9913. ebuf,
  9914. ebuf_len,
  9915. &sock,
  9916. &sa)) {
  9917. ;
  9918. } else if ((conn = (struct mg_connection *)
  9919. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9920. mg_snprintf(NULL,
  9921. NULL, /* No truncation check for ebuf */
  9922. ebuf,
  9923. ebuf_len,
  9924. "calloc(): %s",
  9925. strerror(ERRNO));
  9926. closesocket(sock);
  9927. #ifndef NO_SSL
  9928. } else if (use_ssl
  9929. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9930. == NULL) {
  9931. mg_snprintf(NULL,
  9932. NULL, /* No truncation check for ebuf */
  9933. ebuf,
  9934. ebuf_len,
  9935. "SSL_CTX_new error");
  9936. closesocket(sock);
  9937. mg_free(conn);
  9938. conn = NULL;
  9939. #endif /* NO_SSL */
  9940. } else {
  9941. #ifdef USE_IPV6
  9942. socklen_t len = (sa.sa.sa_family == AF_INET)
  9943. ? sizeof(conn->client.rsa.sin)
  9944. : sizeof(conn->client.rsa.sin6);
  9945. struct sockaddr *psa =
  9946. (sa.sa.sa_family == AF_INET)
  9947. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9948. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9949. #else
  9950. socklen_t len = sizeof(conn->client.rsa.sin);
  9951. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9952. #endif
  9953. conn->buf_size = MAX_REQUEST_SIZE;
  9954. conn->buf = (char *)(conn + 1);
  9955. conn->ctx = &fake_ctx;
  9956. conn->client.sock = sock;
  9957. conn->client.lsa = sa;
  9958. if (getsockname(sock, psa, &len) != 0) {
  9959. mg_cry(conn,
  9960. "%s: getsockname() failed: %s",
  9961. __func__,
  9962. strerror(ERRNO));
  9963. }
  9964. conn->client.is_ssl = use_ssl ? 1 : 0;
  9965. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9966. #ifndef NO_SSL
  9967. if (use_ssl) {
  9968. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9969. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9970. * SSL_CTX_set_verify call is needed to switch off server
  9971. * certificate checking, which is off by default in OpenSSL and
  9972. * on in yaSSL. */
  9973. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9974. * SSL_VERIFY_PEER, verify_ssl_server); */
  9975. if (client_options->client_cert) {
  9976. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9977. mg_snprintf(NULL,
  9978. NULL, /* No truncation check for ebuf */
  9979. ebuf,
  9980. ebuf_len,
  9981. "Can not use SSL client certificate");
  9982. SSL_CTX_free(conn->client_ssl_ctx);
  9983. closesocket(sock);
  9984. mg_free(conn);
  9985. conn = NULL;
  9986. }
  9987. }
  9988. if (client_options->server_cert) {
  9989. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9990. client_options->server_cert,
  9991. NULL);
  9992. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9993. } else {
  9994. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9995. }
  9996. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9997. mg_snprintf(NULL,
  9998. NULL, /* No truncation check for ebuf */
  9999. ebuf,
  10000. ebuf_len,
  10001. "SSL connection error");
  10002. SSL_CTX_free(conn->client_ssl_ctx);
  10003. closesocket(sock);
  10004. mg_free(conn);
  10005. conn = NULL;
  10006. }
  10007. }
  10008. #endif
  10009. }
  10010. return conn;
  10011. }
  10012. CIVETWEB_API struct mg_connection *
  10013. mg_connect_client_secure(const struct mg_client_options *client_options,
  10014. char *error_buffer,
  10015. size_t error_buffer_size)
  10016. {
  10017. return mg_connect_client_impl(client_options,
  10018. 1,
  10019. error_buffer,
  10020. error_buffer_size);
  10021. }
  10022. struct mg_connection *
  10023. mg_connect_client(const char *host,
  10024. int port,
  10025. int use_ssl,
  10026. char *error_buffer,
  10027. size_t error_buffer_size)
  10028. {
  10029. struct mg_client_options opts;
  10030. memset(&opts, 0, sizeof(opts));
  10031. opts.host = host;
  10032. opts.port = port;
  10033. return mg_connect_client_impl(&opts,
  10034. use_ssl,
  10035. error_buffer,
  10036. error_buffer_size);
  10037. }
  10038. static const struct {
  10039. const char *proto;
  10040. size_t proto_len;
  10041. unsigned default_port;
  10042. } abs_uri_protocols[] = {{"http://", 7, 80},
  10043. {"https://", 8, 443},
  10044. {"ws://", 5, 80},
  10045. {"wss://", 6, 443},
  10046. {NULL, 0, 0}};
  10047. /* Check if the uri is valid.
  10048. * return 0 for invalid uri,
  10049. * return 1 for *,
  10050. * return 2 for relative uri,
  10051. * return 3 for absolute uri without port,
  10052. * return 4 for absolute uri with port */
  10053. static int
  10054. get_uri_type(const char *uri)
  10055. {
  10056. int i;
  10057. char *hostend, *portbegin, *portend;
  10058. unsigned long port;
  10059. /* According to the HTTP standard
  10060. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10061. * URI can be an asterisk (*) or should start with slash (relative uri),
  10062. * or it should start with the protocol (absolute uri). */
  10063. if (uri[0] == '*' && uri[1] == '\0') {
  10064. /* asterisk */
  10065. return 1;
  10066. }
  10067. if (uri[0] == '/') {
  10068. /* relative uri */
  10069. return 2;
  10070. }
  10071. /* It could be an absolute uri: */
  10072. /* This function only checks if the uri is valid, not if it is
  10073. * addressing the current server. So civetweb can also be used
  10074. * as a proxy server. */
  10075. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10076. if (mg_strncasecmp(uri,
  10077. abs_uri_protocols[i].proto,
  10078. abs_uri_protocols[i].proto_len) == 0) {
  10079. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10080. if (!hostend) {
  10081. return 0;
  10082. }
  10083. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10084. if (!portbegin) {
  10085. return 3;
  10086. }
  10087. port = strtoul(portbegin + 1, &portend, 10);
  10088. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10089. return 0;
  10090. }
  10091. return 4;
  10092. }
  10093. }
  10094. return 0;
  10095. }
  10096. /* Return NULL or the relative uri at the current server */
  10097. static const char *
  10098. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10099. {
  10100. const char *server_domain;
  10101. size_t server_domain_len;
  10102. size_t request_domain_len = 0;
  10103. unsigned long port = 0;
  10104. int i;
  10105. const char *hostbegin = NULL;
  10106. const char *hostend = NULL;
  10107. const char *portbegin;
  10108. char *portend;
  10109. /* DNS is case insensitive, so use case insensitive string compare here
  10110. */
  10111. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10112. if (!server_domain) {
  10113. return 0;
  10114. }
  10115. server_domain_len = strlen(server_domain);
  10116. if (!server_domain_len) {
  10117. return 0;
  10118. }
  10119. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10120. if (mg_strncasecmp(uri,
  10121. abs_uri_protocols[i].proto,
  10122. abs_uri_protocols[i].proto_len) == 0) {
  10123. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10124. hostend = strchr(hostbegin, '/');
  10125. if (!hostend) {
  10126. return 0;
  10127. }
  10128. portbegin = strchr(hostbegin, ':');
  10129. if ((!portbegin) || (portbegin > hostend)) {
  10130. port = abs_uri_protocols[i].default_port;
  10131. request_domain_len = (size_t)(hostend - hostbegin);
  10132. } else {
  10133. port = strtoul(portbegin + 1, &portend, 10);
  10134. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10135. return 0;
  10136. }
  10137. request_domain_len = (size_t)(portbegin - hostbegin);
  10138. }
  10139. /* protocol found, port set */
  10140. break;
  10141. }
  10142. }
  10143. if (!port) {
  10144. /* port remains 0 if the protocol is not found */
  10145. return 0;
  10146. }
  10147. #if defined(USE_IPV6)
  10148. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10149. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10150. /* Request is directed to a different port */
  10151. return 0;
  10152. }
  10153. } else
  10154. #endif
  10155. {
  10156. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10157. /* Request is directed to a different port */
  10158. return 0;
  10159. }
  10160. }
  10161. if ((request_domain_len != server_domain_len)
  10162. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10163. /* Request is directed to another server */
  10164. return 0;
  10165. }
  10166. return hostend;
  10167. }
  10168. static int
  10169. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10170. {
  10171. const char *cl;
  10172. if (ebuf_len > 0) {
  10173. ebuf[0] = '\0';
  10174. }
  10175. *err = 0;
  10176. reset_per_request_attributes(conn);
  10177. if (!conn) {
  10178. mg_snprintf(conn,
  10179. NULL, /* No truncation check for ebuf */
  10180. ebuf,
  10181. ebuf_len,
  10182. "%s",
  10183. "Internal error");
  10184. *err = 500;
  10185. return 0;
  10186. }
  10187. /* Set the time the request was received. This value should be used for
  10188. * timeouts. */
  10189. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10190. conn->request_len =
  10191. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10192. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10193. */
  10194. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10195. mg_snprintf(conn,
  10196. NULL, /* No truncation check for ebuf */
  10197. ebuf,
  10198. ebuf_len,
  10199. "%s",
  10200. "Invalid request size");
  10201. *err = 500;
  10202. return 0;
  10203. }
  10204. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10205. mg_snprintf(conn,
  10206. NULL, /* No truncation check for ebuf */
  10207. ebuf,
  10208. ebuf_len,
  10209. "%s",
  10210. "Request Too Large");
  10211. *err = 413;
  10212. return 0;
  10213. } else if (conn->request_len <= 0) {
  10214. if (conn->data_len > 0) {
  10215. mg_snprintf(conn,
  10216. NULL, /* No truncation check for ebuf */
  10217. ebuf,
  10218. ebuf_len,
  10219. "%s",
  10220. "Client sent malformed request");
  10221. *err = 400;
  10222. } else {
  10223. /* Server did not send anything -> just close the connection */
  10224. conn->must_close = 1;
  10225. mg_snprintf(conn,
  10226. NULL, /* No truncation check for ebuf */
  10227. ebuf,
  10228. ebuf_len,
  10229. "%s",
  10230. "Client did not send a request");
  10231. *err = 0;
  10232. }
  10233. return 0;
  10234. } else if (parse_http_message(conn->buf,
  10235. conn->buf_size,
  10236. &conn->request_info) <= 0) {
  10237. mg_snprintf(conn,
  10238. NULL, /* No truncation check for ebuf */
  10239. ebuf,
  10240. ebuf_len,
  10241. "%s",
  10242. "Bad Request");
  10243. *err = 400;
  10244. return 0;
  10245. } else {
  10246. /* Message is a valid request or response */
  10247. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10248. /* Request/response has content length set */
  10249. char *endptr = NULL;
  10250. conn->content_len = strtoll(cl, &endptr, 10);
  10251. if (endptr == cl) {
  10252. mg_snprintf(conn,
  10253. NULL, /* No truncation check for ebuf */
  10254. ebuf,
  10255. ebuf_len,
  10256. "%s",
  10257. "Bad Request");
  10258. *err = 411;
  10259. return 0;
  10260. }
  10261. /* Publish the content length back to the request info. */
  10262. conn->request_info.content_length = conn->content_len;
  10263. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10264. != NULL
  10265. && strcmp(cl, "chunked") == 0) {
  10266. conn->is_chunked = 1;
  10267. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10268. || !mg_strcasecmp(conn->request_info.request_method,
  10269. "PUT")) {
  10270. /* POST or PUT request without content length set */
  10271. conn->content_len = -1;
  10272. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10273. "HTTP/",
  10274. 5)) {
  10275. /* Response without content length set */
  10276. conn->content_len = -1;
  10277. } else {
  10278. /* Other request */
  10279. conn->content_len = 0;
  10280. }
  10281. }
  10282. return 1;
  10283. }
  10284. int
  10285. mg_get_response(struct mg_connection *conn,
  10286. char *ebuf,
  10287. size_t ebuf_len,
  10288. int timeout)
  10289. {
  10290. if (conn) {
  10291. /* Implementation of API function for HTTP clients */
  10292. int err, ret;
  10293. struct mg_context *octx = conn->ctx;
  10294. struct mg_context rctx = *(conn->ctx);
  10295. char txt[32]; /* will not overflow */
  10296. if (timeout >= 0) {
  10297. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10298. rctx.config[REQUEST_TIMEOUT] = txt;
  10299. set_sock_timeout(conn->client.sock, timeout);
  10300. } else {
  10301. rctx.config[REQUEST_TIMEOUT] = NULL;
  10302. }
  10303. conn->ctx = &rctx;
  10304. ret = getreq(conn, ebuf, ebuf_len, &err);
  10305. conn->ctx = octx;
  10306. /* TODO: 1) uri is deprecated;
  10307. * 2) here, ri.uri is the http response code */
  10308. conn->request_info.uri = conn->request_info.request_uri;
  10309. /* TODO (mid): Define proper return values - maybe return length?
  10310. * For the first test use <0 for error and >0 for OK */
  10311. return (ret == 0) ? -1 : +1;
  10312. }
  10313. return -1;
  10314. }
  10315. struct mg_connection *
  10316. mg_download(const char *host,
  10317. int port,
  10318. int use_ssl,
  10319. char *ebuf,
  10320. size_t ebuf_len,
  10321. const char *fmt,
  10322. ...)
  10323. {
  10324. struct mg_connection *conn;
  10325. va_list ap;
  10326. int i;
  10327. int reqerr;
  10328. va_start(ap, fmt);
  10329. ebuf[0] = '\0';
  10330. /* open a connection */
  10331. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10332. if (conn != NULL) {
  10333. i = mg_vprintf(conn, fmt, ap);
  10334. if (i <= 0) {
  10335. mg_snprintf(conn,
  10336. NULL, /* No truncation check for ebuf */
  10337. ebuf,
  10338. ebuf_len,
  10339. "%s",
  10340. "Error sending request");
  10341. } else {
  10342. getreq(conn, ebuf, ebuf_len, &reqerr);
  10343. /* TODO: 1) uri is deprecated;
  10344. * 2) here, ri.uri is the http response code */
  10345. conn->request_info.uri = conn->request_info.request_uri;
  10346. }
  10347. }
  10348. /* if an error occured, close the connection */
  10349. if (ebuf[0] != '\0' && conn != NULL) {
  10350. mg_close_connection(conn);
  10351. conn = NULL;
  10352. }
  10353. va_end(ap);
  10354. return conn;
  10355. }
  10356. struct websocket_client_thread_data {
  10357. struct mg_connection *conn;
  10358. mg_websocket_data_handler data_handler;
  10359. mg_websocket_close_handler close_handler;
  10360. void *callback_data;
  10361. };
  10362. #if defined(USE_WEBSOCKET)
  10363. #ifdef _WIN32
  10364. static unsigned __stdcall websocket_client_thread(void *data)
  10365. #else
  10366. static void *
  10367. websocket_client_thread(void *data)
  10368. #endif
  10369. {
  10370. struct websocket_client_thread_data *cdata =
  10371. (struct websocket_client_thread_data *)data;
  10372. mg_set_thread_name("ws-client");
  10373. if (cdata->conn->ctx) {
  10374. if (cdata->conn->ctx->callbacks.init_thread) {
  10375. /* 3 indicates a websocket client thread */
  10376. /* TODO: check if conn->ctx can be set */
  10377. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10378. }
  10379. }
  10380. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10381. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10382. if (cdata->close_handler != NULL) {
  10383. cdata->close_handler(cdata->conn, cdata->callback_data);
  10384. }
  10385. mg_free((void *)cdata);
  10386. #ifdef _WIN32
  10387. return 0;
  10388. #else
  10389. return NULL;
  10390. #endif
  10391. }
  10392. #endif
  10393. struct mg_connection *
  10394. mg_connect_websocket_client(const char *host,
  10395. int port,
  10396. int use_ssl,
  10397. char *error_buffer,
  10398. size_t error_buffer_size,
  10399. const char *path,
  10400. const char *origin,
  10401. mg_websocket_data_handler data_func,
  10402. mg_websocket_close_handler close_func,
  10403. void *user_data)
  10404. {
  10405. struct mg_connection *conn = NULL;
  10406. #if defined(USE_WEBSOCKET)
  10407. struct mg_context *newctx = NULL;
  10408. struct websocket_client_thread_data *thread_data;
  10409. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10410. static const char *handshake_req;
  10411. if (origin != NULL) {
  10412. handshake_req = "GET %s HTTP/1.1\r\n"
  10413. "Host: %s\r\n"
  10414. "Upgrade: websocket\r\n"
  10415. "Connection: Upgrade\r\n"
  10416. "Sec-WebSocket-Key: %s\r\n"
  10417. "Sec-WebSocket-Version: 13\r\n"
  10418. "Origin: %s\r\n"
  10419. "\r\n";
  10420. } else {
  10421. handshake_req = "GET %s HTTP/1.1\r\n"
  10422. "Host: %s\r\n"
  10423. "Upgrade: websocket\r\n"
  10424. "Connection: Upgrade\r\n"
  10425. "Sec-WebSocket-Key: %s\r\n"
  10426. "Sec-WebSocket-Version: 13\r\n"
  10427. "\r\n";
  10428. }
  10429. /* Establish the client connection and request upgrade */
  10430. conn = mg_download(host,
  10431. port,
  10432. use_ssl,
  10433. error_buffer,
  10434. error_buffer_size,
  10435. handshake_req,
  10436. path,
  10437. host,
  10438. magic,
  10439. origin);
  10440. /* Connection object will be null if something goes wrong */
  10441. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10442. if (!*error_buffer) {
  10443. /* if there is a connection, but it did not return 101,
  10444. * error_buffer is not yet set */
  10445. mg_snprintf(conn,
  10446. NULL, /* No truncation check for ebuf */
  10447. error_buffer,
  10448. error_buffer_size,
  10449. "Unexpected server reply");
  10450. }
  10451. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10452. if (conn != NULL) {
  10453. mg_free(conn);
  10454. conn = NULL;
  10455. }
  10456. return conn;
  10457. }
  10458. /* For client connections, mg_context is fake. Since we need to set a
  10459. * callback function, we need to create a copy and modify it. */
  10460. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10461. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10462. newctx->user_data = user_data;
  10463. newctx->context_type = 2; /* client context type */
  10464. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10465. newctx->workerthreadids =
  10466. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10467. conn->ctx = newctx;
  10468. thread_data = (struct websocket_client_thread_data *)
  10469. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10470. thread_data->conn = conn;
  10471. thread_data->data_handler = data_func;
  10472. thread_data->close_handler = close_func;
  10473. thread_data->callback_data = NULL;
  10474. /* Start a thread to read the websocket client connection
  10475. * This thread will automatically stop when mg_disconnect is
  10476. * called on the client connection */
  10477. if (mg_start_thread_with_id(websocket_client_thread,
  10478. (void *)thread_data,
  10479. newctx->workerthreadids) != 0) {
  10480. mg_free((void *)thread_data);
  10481. mg_free((void *)newctx->workerthreadids);
  10482. mg_free((void *)newctx);
  10483. mg_free((void *)conn);
  10484. conn = NULL;
  10485. DEBUG_TRACE("%s",
  10486. "Websocket client connect thread could not be started\r\n");
  10487. }
  10488. #else
  10489. /* Appease "unused parameter" warnings */
  10490. (void)host;
  10491. (void)port;
  10492. (void)use_ssl;
  10493. (void)error_buffer;
  10494. (void)error_buffer_size;
  10495. (void)path;
  10496. (void)origin;
  10497. (void)user_data;
  10498. (void)data_func;
  10499. (void)close_func;
  10500. #endif
  10501. return conn;
  10502. }
  10503. static void
  10504. process_new_connection(struct mg_connection *conn)
  10505. {
  10506. if (conn && conn->ctx) {
  10507. struct mg_request_info *ri = &conn->request_info;
  10508. int keep_alive_enabled, keep_alive, discard_len;
  10509. char ebuf[100];
  10510. const char *hostend;
  10511. int reqerr, uri_type;
  10512. keep_alive_enabled =
  10513. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10514. /* Important: on new connection, reset the receiving buffer. Credit
  10515. * goes to crule42. */
  10516. conn->data_len = 0;
  10517. do {
  10518. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10519. /* The request sent by the client could not be understood by
  10520. * the server, or it was incomplete or a timeout. Send an
  10521. * error message and close the connection. */
  10522. if (reqerr > 0) {
  10523. /*assert(ebuf[0] != '\0');*/
  10524. send_http_error(conn, reqerr, "%s", ebuf);
  10525. }
  10526. } else if (strcmp(ri->http_version, "1.0")
  10527. && strcmp(ri->http_version, "1.1")) {
  10528. mg_snprintf(conn,
  10529. NULL, /* No truncation check for ebuf */
  10530. ebuf,
  10531. sizeof(ebuf),
  10532. "Bad HTTP version: [%s]",
  10533. ri->http_version);
  10534. send_http_error(conn, 505, "%s", ebuf);
  10535. }
  10536. if (ebuf[0] == '\0') {
  10537. uri_type = get_uri_type(conn->request_info.request_uri);
  10538. switch (uri_type) {
  10539. case 1:
  10540. /* Asterisk */
  10541. conn->request_info.local_uri = NULL;
  10542. break;
  10543. case 2:
  10544. /* relative uri */
  10545. conn->request_info.local_uri =
  10546. conn->request_info.request_uri;
  10547. break;
  10548. case 3:
  10549. case 4:
  10550. /* absolute uri (with/without port) */
  10551. hostend = get_rel_url_at_current_server(
  10552. conn->request_info.request_uri, conn);
  10553. if (hostend) {
  10554. conn->request_info.local_uri = hostend;
  10555. } else {
  10556. conn->request_info.local_uri = NULL;
  10557. }
  10558. break;
  10559. default:
  10560. mg_snprintf(conn,
  10561. NULL, /* No truncation check for ebuf */
  10562. ebuf,
  10563. sizeof(ebuf),
  10564. "Invalid URI: [%s]",
  10565. ri->request_uri);
  10566. send_http_error(conn, 400, "%s", ebuf);
  10567. break;
  10568. }
  10569. /* TODO: cleanup uri, local_uri and request_uri */
  10570. conn->request_info.uri = conn->request_info.local_uri;
  10571. }
  10572. if (ebuf[0] == '\0') {
  10573. if (conn->request_info.local_uri) {
  10574. /* handle request to local server */
  10575. handle_request(conn);
  10576. if (conn->ctx->callbacks.end_request != NULL) {
  10577. conn->ctx->callbacks.end_request(conn,
  10578. conn->status_code);
  10579. }
  10580. log_access(conn);
  10581. } else {
  10582. /* TODO: handle non-local request (PROXY) */
  10583. conn->must_close = 1;
  10584. }
  10585. } else {
  10586. conn->must_close = 1;
  10587. }
  10588. if (ri->remote_user != NULL) {
  10589. mg_free((void *)ri->remote_user);
  10590. /* Important! When having connections with and without auth
  10591. * would cause double free and then crash */
  10592. ri->remote_user = NULL;
  10593. }
  10594. /* NOTE(lsm): order is important here. should_keep_alive() call
  10595. * is
  10596. * using parsed request, which will be invalid after memmove's
  10597. * below.
  10598. * Therefore, memorize should_keep_alive() result now for later
  10599. * use
  10600. * in loop exit condition. */
  10601. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10602. && conn->content_len >= 0 && should_keep_alive(conn);
  10603. /* Discard all buffered data for this request */
  10604. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10605. && conn->request_len + conn->content_len
  10606. < (int64_t)conn->data_len
  10607. ? (int)(conn->request_len + conn->content_len)
  10608. : conn->data_len;
  10609. /*assert(discard_len >= 0);*/
  10610. if (discard_len < 0)
  10611. break;
  10612. conn->data_len -= discard_len;
  10613. if (conn->data_len > 0) {
  10614. memmove(conn->buf,
  10615. conn->buf + discard_len,
  10616. (size_t)conn->data_len);
  10617. }
  10618. /* assert(conn->data_len >= 0); */
  10619. /* assert(conn->data_len <= conn->buf_size); */
  10620. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10621. break;
  10622. }
  10623. } while (keep_alive);
  10624. }
  10625. }
  10626. /* Worker threads take accepted socket from the queue */
  10627. static int
  10628. consume_socket(struct mg_context *ctx, struct socket *sp)
  10629. {
  10630. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10631. if (!ctx) {
  10632. return 0;
  10633. }
  10634. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10635. DEBUG_TRACE("%s", "going idle");
  10636. /* If the queue is empty, wait. We're idle at this point. */
  10637. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10638. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10639. }
  10640. /* If we're stopping, sq_head may be equal to sq_tail. */
  10641. if (ctx->sq_head > ctx->sq_tail) {
  10642. /* Copy socket from the queue and increment tail */
  10643. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10644. ctx->sq_tail++;
  10645. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10646. /* Wrap pointers if needed */
  10647. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10648. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10649. ctx->sq_head -= QUEUE_SIZE(ctx);
  10650. }
  10651. }
  10652. (void)pthread_cond_signal(&ctx->sq_empty);
  10653. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10654. return !ctx->stop_flag;
  10655. #undef QUEUE_SIZE
  10656. }
  10657. static void *
  10658. worker_thread_run(void *thread_func_param)
  10659. {
  10660. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10661. struct mg_connection *conn;
  10662. struct mg_workerTLS tls;
  10663. #if defined(MG_LEGACY_INTERFACE)
  10664. uint32_t addr;
  10665. #endif
  10666. mg_set_thread_name("worker");
  10667. tls.is_master = 0;
  10668. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10669. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10670. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10671. #endif
  10672. if (ctx->callbacks.init_thread) {
  10673. /* call init_thread for a worker thread (type 1) */
  10674. ctx->callbacks.init_thread(ctx, 1);
  10675. }
  10676. conn =
  10677. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10678. if (conn == NULL) {
  10679. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10680. } else {
  10681. pthread_setspecific(sTlsKey, &tls);
  10682. conn->buf_size = MAX_REQUEST_SIZE;
  10683. conn->buf = (char *)(conn + 1);
  10684. conn->ctx = ctx;
  10685. conn->request_info.user_data = ctx->user_data;
  10686. /* Allocate a mutex for this connection to allow communication both
  10687. * within the request handler and from elsewhere in the application
  10688. */
  10689. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10690. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10691. * signal sq_empty condvar to wake up the master waiting in
  10692. * produce_socket() */
  10693. while (consume_socket(ctx, &conn->client)) {
  10694. conn->conn_birth_time = time(NULL);
  10695. /* Fill in IP, port info early so even if SSL setup below fails,
  10696. * error handler would have the corresponding info.
  10697. * Thanks to Johannes Winkelmann for the patch.
  10698. */
  10699. #if defined(USE_IPV6)
  10700. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10701. conn->request_info.remote_port =
  10702. ntohs(conn->client.rsa.sin6.sin6_port);
  10703. } else
  10704. #endif
  10705. {
  10706. conn->request_info.remote_port =
  10707. ntohs(conn->client.rsa.sin.sin_port);
  10708. }
  10709. sockaddr_to_string(conn->request_info.remote_addr,
  10710. sizeof(conn->request_info.remote_addr),
  10711. &conn->client.rsa);
  10712. #if defined(MG_LEGACY_INTERFACE)
  10713. /* This legacy interface only works for the IPv4 case */
  10714. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10715. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10716. #endif
  10717. conn->request_info.is_ssl = conn->client.is_ssl;
  10718. if (!conn->client.is_ssl
  10719. #ifndef NO_SSL
  10720. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10721. #endif
  10722. ) {
  10723. process_new_connection(conn);
  10724. }
  10725. close_connection(conn);
  10726. }
  10727. }
  10728. /* Signal master that we're done with connection and exiting */
  10729. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10730. ctx->running_worker_threads--;
  10731. (void)pthread_cond_signal(&ctx->thread_cond);
  10732. /* assert(ctx->running_worker_threads >= 0); */
  10733. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10734. pthread_setspecific(sTlsKey, NULL);
  10735. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10736. CloseHandle(tls.pthread_cond_helper_mutex);
  10737. #endif
  10738. pthread_mutex_destroy(&conn->mutex);
  10739. mg_free(conn);
  10740. DEBUG_TRACE("%s", "exiting");
  10741. return NULL;
  10742. }
  10743. /* Threads have different return types on Windows and Unix. */
  10744. #ifdef _WIN32
  10745. static unsigned __stdcall worker_thread(void *thread_func_param)
  10746. {
  10747. worker_thread_run(thread_func_param);
  10748. return 0;
  10749. }
  10750. #else
  10751. static void *
  10752. worker_thread(void *thread_func_param)
  10753. {
  10754. worker_thread_run(thread_func_param);
  10755. return NULL;
  10756. }
  10757. #endif /* _WIN32 */
  10758. /* Master thread adds accepted socket to a queue */
  10759. static void
  10760. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10761. {
  10762. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10763. if (!ctx) {
  10764. return;
  10765. }
  10766. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10767. /* If the queue is full, wait */
  10768. while (ctx->stop_flag == 0
  10769. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10770. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10771. }
  10772. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10773. /* Copy socket to the queue and increment head */
  10774. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10775. ctx->sq_head++;
  10776. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10777. }
  10778. (void)pthread_cond_signal(&ctx->sq_full);
  10779. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10780. #undef QUEUE_SIZE
  10781. }
  10782. static void
  10783. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10784. {
  10785. struct socket so;
  10786. char src_addr[IP_ADDR_STR_LEN];
  10787. socklen_t len = sizeof(so.rsa);
  10788. int on = 1;
  10789. int timeout;
  10790. if (!listener) {
  10791. return;
  10792. }
  10793. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10794. == INVALID_SOCKET) {
  10795. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10796. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10797. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10798. closesocket(so.sock);
  10799. so.sock = INVALID_SOCKET;
  10800. } else {
  10801. /* Put so socket structure into the queue */
  10802. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10803. set_close_on_exec(so.sock, fc(ctx));
  10804. so.is_ssl = listener->is_ssl;
  10805. so.ssl_redir = listener->ssl_redir;
  10806. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10807. mg_cry(fc(ctx),
  10808. "%s: getsockname() failed: %s",
  10809. __func__,
  10810. strerror(ERRNO));
  10811. }
  10812. /* Set TCP keep-alive. This is needed because if HTTP-level
  10813. * keep-alive
  10814. * is enabled, and client resets the connection, server won't get
  10815. * TCP FIN or RST and will keep the connection open forever. With
  10816. * TCP keep-alive, next keep-alive handshake will figure out that
  10817. * the client is down and will close the server end.
  10818. * Thanks to Igor Klopov who suggested the patch. */
  10819. if (setsockopt(so.sock,
  10820. SOL_SOCKET,
  10821. SO_KEEPALIVE,
  10822. (SOCK_OPT_TYPE)&on,
  10823. sizeof(on)) != 0) {
  10824. mg_cry(fc(ctx),
  10825. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10826. __func__,
  10827. strerror(ERRNO));
  10828. }
  10829. /* Disable TCP Nagle's algorithm. Normally TCP packets are
  10830. * coalesced
  10831. * to effectively fill up the underlying IP packet payload and
  10832. * reduce
  10833. * the overhead of sending lots of small buffers. However this hurts
  10834. * the server's throughput (ie. operations per second) when HTTP 1.1
  10835. * persistent connections are used and the responses are relatively
  10836. * small (eg. less than 1400 bytes).
  10837. */
  10838. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10839. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10840. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10841. mg_cry(fc(ctx),
  10842. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10843. __func__,
  10844. strerror(ERRNO));
  10845. }
  10846. }
  10847. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10848. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10849. } else {
  10850. timeout = -1;
  10851. }
  10852. /* Set socket timeout to the given value, but not more than a
  10853. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10854. * so the server can exit after that time if requested. */
  10855. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10856. set_sock_timeout(so.sock, timeout);
  10857. } else {
  10858. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10859. }
  10860. produce_socket(ctx, &so);
  10861. }
  10862. }
  10863. static void
  10864. master_thread_run(void *thread_func_param)
  10865. {
  10866. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10867. struct mg_workerTLS tls;
  10868. struct pollfd *pfd;
  10869. unsigned int i;
  10870. unsigned int workerthreadcount;
  10871. if (!ctx) {
  10872. return;
  10873. }
  10874. mg_set_thread_name("master");
  10875. /* Increase priority of the master thread */
  10876. #if defined(_WIN32)
  10877. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10878. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10879. int min_prio = sched_get_priority_min(SCHED_RR);
  10880. int max_prio = sched_get_priority_max(SCHED_RR);
  10881. if ((min_prio >= 0) && (max_prio >= 0)
  10882. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10883. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10884. struct sched_param sched_param = {0};
  10885. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10886. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10887. }
  10888. #endif
  10889. /* Initialize thread local storage */
  10890. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10891. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10892. #endif
  10893. tls.is_master = 1;
  10894. pthread_setspecific(sTlsKey, &tls);
  10895. if (ctx->callbacks.init_thread) {
  10896. /* Callback for the master thread (type 0) */
  10897. ctx->callbacks.init_thread(ctx, 0);
  10898. }
  10899. /* Server starts *now* */
  10900. ctx->start_time = time(NULL);
  10901. /* Allocate memory for the listening sockets, and start the server */
  10902. pfd =
  10903. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10904. while (pfd != NULL && ctx->stop_flag == 0) {
  10905. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10906. pfd[i].fd = ctx->listening_sockets[i].sock;
  10907. pfd[i].events = POLLIN;
  10908. }
  10909. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10910. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10911. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10912. * successful poll, and POLLIN is defined as
  10913. * (POLLRDNORM | POLLRDBAND)
  10914. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10915. * pfd[i].revents == POLLIN. */
  10916. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10917. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10918. }
  10919. }
  10920. }
  10921. }
  10922. mg_free(pfd);
  10923. DEBUG_TRACE("%s", "stopping workers");
  10924. /* Stop signal received: somebody called mg_stop. Quit. */
  10925. close_all_listening_sockets(ctx);
  10926. /* Wakeup workers that are waiting for connections to handle. */
  10927. pthread_cond_broadcast(&ctx->sq_full);
  10928. /* Wait until all threads finish */
  10929. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10930. while (ctx->running_worker_threads > 0) {
  10931. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10932. }
  10933. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10934. /* Join all worker threads to avoid leaking threads. */
  10935. workerthreadcount = ctx->cfg_worker_threads;
  10936. for (i = 0; i < workerthreadcount; i++) {
  10937. if (ctx->workerthreadids[i] != 0) {
  10938. mg_join_thread(ctx->workerthreadids[i]);
  10939. }
  10940. }
  10941. #if !defined(NO_SSL)
  10942. if (ctx->ssl_ctx != NULL) {
  10943. uninitialize_ssl(ctx);
  10944. }
  10945. #endif
  10946. DEBUG_TRACE("%s", "exiting");
  10947. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10948. CloseHandle(tls.pthread_cond_helper_mutex);
  10949. #endif
  10950. pthread_setspecific(sTlsKey, NULL);
  10951. /* Signal mg_stop() that we're done.
  10952. * WARNING: This must be the very last thing this
  10953. * thread does, as ctx becomes invalid after this line. */
  10954. ctx->stop_flag = 2;
  10955. }
  10956. /* Threads have different return types on Windows and Unix. */
  10957. #ifdef _WIN32
  10958. static unsigned __stdcall master_thread(void *thread_func_param)
  10959. {
  10960. master_thread_run(thread_func_param);
  10961. return 0;
  10962. }
  10963. #else
  10964. static void *
  10965. master_thread(void *thread_func_param)
  10966. {
  10967. master_thread_run(thread_func_param);
  10968. return NULL;
  10969. }
  10970. #endif /* _WIN32 */
  10971. static void
  10972. free_context(struct mg_context *ctx)
  10973. {
  10974. int i;
  10975. struct mg_handler_info *tmp_rh;
  10976. if (ctx == NULL) {
  10977. return;
  10978. }
  10979. if (ctx->callbacks.exit_context) {
  10980. ctx->callbacks.exit_context(ctx);
  10981. }
  10982. /* All threads exited, no sync is needed. Destroy thread mutex and
  10983. * condvars
  10984. */
  10985. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10986. (void)pthread_cond_destroy(&ctx->thread_cond);
  10987. (void)pthread_cond_destroy(&ctx->sq_empty);
  10988. (void)pthread_cond_destroy(&ctx->sq_full);
  10989. /* Destroy other context global data structures mutex */
  10990. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10991. #if defined(USE_TIMERS)
  10992. timers_exit(ctx);
  10993. #endif
  10994. /* Deallocate config parameters */
  10995. for (i = 0; i < NUM_OPTIONS; i++) {
  10996. if (ctx->config[i] != NULL) {
  10997. #if defined(_MSC_VER)
  10998. #pragma warning(suppress : 6001)
  10999. #endif
  11000. mg_free(ctx->config[i]);
  11001. }
  11002. }
  11003. /* Deallocate request handlers */
  11004. while (ctx->handlers) {
  11005. tmp_rh = ctx->handlers;
  11006. ctx->handlers = tmp_rh->next;
  11007. mg_free(tmp_rh->uri);
  11008. mg_free(tmp_rh);
  11009. }
  11010. #ifndef NO_SSL
  11011. /* Deallocate SSL context */
  11012. if (ctx->ssl_ctx != NULL) {
  11013. SSL_CTX_free(ctx->ssl_ctx);
  11014. }
  11015. #endif /* !NO_SSL */
  11016. /* Deallocate worker thread ID array */
  11017. if (ctx->workerthreadids != NULL) {
  11018. mg_free(ctx->workerthreadids);
  11019. }
  11020. /* Deallocate the tls variable */
  11021. if (mg_atomic_dec(&sTlsInit) == 0) {
  11022. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11023. DeleteCriticalSection(&global_log_file_lock);
  11024. #endif /* _WIN32 && !__SYMBIAN32__ */
  11025. #if !defined(_WIN32)
  11026. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11027. #endif
  11028. pthread_key_delete(sTlsKey);
  11029. }
  11030. /* deallocate system name string */
  11031. mg_free(ctx->systemName);
  11032. /* Deallocate context itself */
  11033. mg_free(ctx);
  11034. }
  11035. void
  11036. mg_stop(struct mg_context *ctx)
  11037. {
  11038. pthread_t mt;
  11039. if (!ctx) {
  11040. return;
  11041. }
  11042. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11043. * two threads is not allowed. */
  11044. mt = ctx->masterthreadid;
  11045. if (mt == 0) {
  11046. return;
  11047. }
  11048. ctx->masterthreadid = 0;
  11049. ctx->stop_flag = 1;
  11050. /* Wait until mg_fini() stops */
  11051. while (ctx->stop_flag != 2) {
  11052. (void)mg_sleep(10);
  11053. }
  11054. mg_join_thread(mt);
  11055. free_context(ctx);
  11056. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11057. (void)WSACleanup();
  11058. #endif /* _WIN32 && !__SYMBIAN32__ */
  11059. }
  11060. static void
  11061. get_system_name(char **sysName)
  11062. {
  11063. #if defined(_WIN32)
  11064. #if !defined(__SYMBIAN32__)
  11065. char name[128];
  11066. DWORD dwVersion = 0;
  11067. DWORD dwMajorVersion = 0;
  11068. DWORD dwMinorVersion = 0;
  11069. DWORD dwBuild = 0;
  11070. #ifdef _MSC_VER
  11071. #pragma warning(push)
  11072. // GetVersion was declared deprecated
  11073. #pragma warning(disable : 4996)
  11074. #endif
  11075. dwVersion = GetVersion();
  11076. #ifdef _MSC_VER
  11077. #pragma warning(pop)
  11078. #endif
  11079. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11080. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11081. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11082. (void)dwBuild;
  11083. sprintf(name,
  11084. "Windows %u.%u",
  11085. (unsigned)dwMajorVersion,
  11086. (unsigned)dwMinorVersion);
  11087. *sysName = mg_strdup(name);
  11088. #else
  11089. *sysName = mg_strdup("Symbian");
  11090. #endif
  11091. #else
  11092. struct utsname name;
  11093. memset(&name, 0, sizeof(name));
  11094. uname(&name);
  11095. *sysName = mg_strdup(name.sysname);
  11096. #endif
  11097. }
  11098. struct mg_context *
  11099. mg_start(const struct mg_callbacks *callbacks,
  11100. void *user_data,
  11101. const char **options)
  11102. {
  11103. struct mg_context *ctx;
  11104. const char *name, *value, *default_value;
  11105. int idx, ok, workerthreadcount;
  11106. unsigned int i;
  11107. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11108. struct mg_workerTLS tls;
  11109. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11110. WSADATA data;
  11111. WSAStartup(MAKEWORD(2, 2), &data);
  11112. #endif /* _WIN32 && !__SYMBIAN32__ */
  11113. /* Allocate context and initialize reasonable general case defaults. */
  11114. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11115. return NULL;
  11116. }
  11117. /* Random number generator will initialize at the first call */
  11118. ctx->auth_nonce_mask =
  11119. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11120. if (mg_atomic_inc(&sTlsInit) == 1) {
  11121. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11122. InitializeCriticalSection(&global_log_file_lock);
  11123. #endif /* _WIN32 && !__SYMBIAN32__ */
  11124. #if !defined(_WIN32)
  11125. pthread_mutexattr_init(&pthread_mutex_attr);
  11126. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11127. #endif
  11128. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11129. /* Fatal error - abort start. However, this situation should
  11130. * never
  11131. * occur in practice. */
  11132. mg_atomic_dec(&sTlsInit);
  11133. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11134. mg_free(ctx);
  11135. return NULL;
  11136. }
  11137. } else {
  11138. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11139. * initialized. */
  11140. mg_sleep(1);
  11141. }
  11142. tls.is_master = -1;
  11143. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11144. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11145. tls.pthread_cond_helper_mutex = NULL;
  11146. #endif
  11147. pthread_setspecific(sTlsKey, &tls);
  11148. #if defined(USE_LUA)
  11149. lua_init_optional_libraries();
  11150. #endif
  11151. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11152. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  11153. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11154. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11155. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11156. if (!ok) {
  11157. /* Fatal error - abort start. However, this situation should never
  11158. * occur in practice. */
  11159. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11160. mg_free(ctx);
  11161. pthread_setspecific(sTlsKey, NULL);
  11162. return NULL;
  11163. }
  11164. if (callbacks) {
  11165. ctx->callbacks = *callbacks;
  11166. exit_callback = callbacks->exit_context;
  11167. ctx->callbacks.exit_context = 0;
  11168. }
  11169. ctx->user_data = user_data;
  11170. ctx->handlers = NULL;
  11171. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11172. ctx->shared_lua_websockets = 0;
  11173. #endif
  11174. while (options && (name = *options++) != NULL) {
  11175. if ((idx = get_option_index(name)) == -1) {
  11176. mg_cry(fc(ctx), "Invalid option: %s", name);
  11177. free_context(ctx);
  11178. pthread_setspecific(sTlsKey, NULL);
  11179. return NULL;
  11180. } else if ((value = *options++) == NULL) {
  11181. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11182. free_context(ctx);
  11183. pthread_setspecific(sTlsKey, NULL);
  11184. return NULL;
  11185. }
  11186. if (ctx->config[idx] != NULL) {
  11187. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11188. mg_free(ctx->config[idx]);
  11189. }
  11190. ctx->config[idx] = mg_strdup(value);
  11191. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11192. }
  11193. /* Set default value if needed */
  11194. for (i = 0; config_options[i].name != NULL; i++) {
  11195. default_value = config_options[i].default_value;
  11196. if (ctx->config[i] == NULL && default_value != NULL) {
  11197. ctx->config[i] = mg_strdup(default_value);
  11198. }
  11199. }
  11200. #if defined(NO_FILES)
  11201. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11202. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11203. free_context(ctx);
  11204. pthread_setspecific(sTlsKey, NULL);
  11205. return NULL;
  11206. }
  11207. #endif
  11208. get_system_name(&ctx->systemName);
  11209. /* NOTE(lsm): order is important here. SSL certificates must
  11210. * be initialized before listening ports. UID must be set last. */
  11211. if (!set_gpass_option(ctx) ||
  11212. #if !defined(NO_SSL)
  11213. !set_ssl_option(ctx) ||
  11214. #endif
  11215. !set_ports_option(ctx) ||
  11216. #if !defined(_WIN32)
  11217. !set_uid_option(ctx) ||
  11218. #endif
  11219. !set_acl_option(ctx)) {
  11220. free_context(ctx);
  11221. pthread_setspecific(sTlsKey, NULL);
  11222. return NULL;
  11223. }
  11224. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11225. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11226. * won't kill the whole process. */
  11227. (void)signal(SIGPIPE, SIG_IGN);
  11228. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11229. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11230. if (workerthreadcount > MAX_WORKER_THREADS) {
  11231. mg_cry(fc(ctx), "Too many worker threads");
  11232. free_context(ctx);
  11233. pthread_setspecific(sTlsKey, NULL);
  11234. return NULL;
  11235. }
  11236. if (workerthreadcount > 0) {
  11237. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11238. ctx->workerthreadids =
  11239. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11240. if (ctx->workerthreadids == NULL) {
  11241. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11242. free_context(ctx);
  11243. pthread_setspecific(sTlsKey, NULL);
  11244. return NULL;
  11245. }
  11246. }
  11247. #if defined(USE_TIMERS)
  11248. if (timers_init(ctx) != 0) {
  11249. mg_cry(fc(ctx), "Error creating timers");
  11250. free_context(ctx);
  11251. pthread_setspecific(sTlsKey, NULL);
  11252. return NULL;
  11253. }
  11254. #endif
  11255. /* Context has been created - init user libraries */
  11256. if (ctx->callbacks.init_context) {
  11257. ctx->callbacks.init_context(ctx);
  11258. }
  11259. ctx->callbacks.exit_context = exit_callback;
  11260. ctx->context_type = 1; /* server context */
  11261. /* Start master (listening) thread */
  11262. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11263. /* Start worker threads */
  11264. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11265. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11266. ctx->running_worker_threads++;
  11267. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11268. if (mg_start_thread_with_id(worker_thread,
  11269. ctx,
  11270. &ctx->workerthreadids[i]) != 0) {
  11271. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11272. ctx->running_worker_threads--;
  11273. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11274. if (i > 0) {
  11275. mg_cry(fc(ctx),
  11276. "Cannot start worker thread %i: error %ld",
  11277. i + 1,
  11278. (long)ERRNO);
  11279. } else {
  11280. mg_cry(fc(ctx),
  11281. "Cannot create threads: error %ld",
  11282. (long)ERRNO);
  11283. free_context(ctx);
  11284. pthread_setspecific(sTlsKey, NULL);
  11285. return NULL;
  11286. }
  11287. break;
  11288. }
  11289. }
  11290. pthread_setspecific(sTlsKey, NULL);
  11291. return ctx;
  11292. }
  11293. /* Feature check API function */
  11294. unsigned
  11295. mg_check_feature(unsigned feature)
  11296. {
  11297. static const unsigned feature_set = 0
  11298. /* Set bits for available features according to API documentation.
  11299. * This bit mask is created at compile time, according to the active
  11300. * preprocessor defines. It is a single const value at runtime. */
  11301. #if !defined(NO_FILES)
  11302. | 1
  11303. #endif
  11304. #if !defined(NO_SSL)
  11305. | 2
  11306. #endif
  11307. #if !defined(NO_CGI)
  11308. | 4
  11309. #endif
  11310. #if defined(USE_IPV6)
  11311. | 8
  11312. #endif
  11313. #if defined(USE_WEBSOCKET)
  11314. | 16
  11315. #endif
  11316. #if defined(USE_LUA)
  11317. | 32
  11318. #endif
  11319. #if defined(USE_DUKTAPE)
  11320. | 64
  11321. #endif
  11322. /* Set some extra bits not defined in the API documentation.
  11323. * These bits may change without further notice. */
  11324. #if defined(MG_LEGACY_INTERFACE)
  11325. | 128
  11326. #endif
  11327. #if defined(MEMORY_DEBUGGING)
  11328. | 256
  11329. #endif
  11330. #if defined(USE_TIMERS)
  11331. | 512
  11332. #endif
  11333. #if !defined(NO_NONCE_CHECK)
  11334. | 1024
  11335. #endif
  11336. #if !defined(NO_POPEN)
  11337. | 2048
  11338. #endif
  11339. ;
  11340. return (feature & feature_set);
  11341. }