civetweb.c 344 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264
  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. #define NO_POPEN /* WinCE has no popen */
  204. typedef long off_t;
  205. #define errno ((int)(GetLastError()))
  206. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  207. #endif /* _WIN32_WCE */
  208. #define MAKEUQUAD(lo, hi) \
  209. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  210. #define RATE_DIFF (10000000) /* 100 nsecs */
  211. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  212. #define SYS2UNIX_TIME(lo, hi) \
  213. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  214. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  215. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  216. * Also use _strtoui64 on modern M$ compilers */
  217. #if defined(_MSC_VER)
  218. #if (_MSC_VER < 1300)
  219. #define STRX(x) #x
  220. #define STR(x) STRX(x)
  221. #define __func__ __FILE__ ":" STR(__LINE__)
  222. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  223. #define strtoll(x, y, z) (_atoi64(x))
  224. #else
  225. #define __func__ __FUNCTION__
  226. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  227. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  228. #endif
  229. #endif /* _MSC_VER */
  230. #define ERRNO ((int)(GetLastError()))
  231. #define NO_SOCKLEN_T
  232. #if defined(_WIN64) || defined(__MINGW64__)
  233. #define SSL_LIB "ssleay64.dll"
  234. #define CRYPTO_LIB "libeay64.dll"
  235. #else
  236. #define SSL_LIB "ssleay32.dll"
  237. #define CRYPTO_LIB "libeay32.dll"
  238. #endif
  239. #define O_NONBLOCK (0)
  240. #ifndef W_OK
  241. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  242. #endif
  243. #if !defined(EWOULDBLOCK)
  244. #define EWOULDBLOCK WSAEWOULDBLOCK
  245. #endif /* !EWOULDBLOCK */
  246. #define _POSIX_
  247. #define INT64_FMT "I64d"
  248. #define UINT64_FMT "I64u"
  249. #define WINCDECL __cdecl
  250. #define SHUT_RD (0)
  251. #define SHUT_WR (1)
  252. #define SHUT_BOTH (2)
  253. #define vsnprintf_impl _vsnprintf
  254. #define access _access
  255. #define mg_sleep(x) (Sleep(x))
  256. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  257. #ifndef popen
  258. #define popen(x, y) (_popen(x, y))
  259. #endif
  260. #ifndef pclose
  261. #define pclose(x) (_pclose(x))
  262. #endif
  263. #define close(x) (_close(x))
  264. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  265. #define RTLD_LAZY (0)
  266. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  267. #define fdopen(x, y) (_fdopen((x), (y)))
  268. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  269. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  270. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  271. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  272. #define sleep(x) (Sleep((x)*1000))
  273. #define rmdir(x) (_rmdir(x))
  274. #define timegm(x) (_mkgmtime(x))
  275. #if !defined(fileno)
  276. #define fileno(x) (_fileno(x))
  277. #endif /* !fileno MINGW #defines fileno */
  278. typedef HANDLE pthread_mutex_t;
  279. typedef DWORD pthread_key_t;
  280. typedef HANDLE pthread_t;
  281. typedef struct {
  282. CRITICAL_SECTION threadIdSec;
  283. int waitingthreadcount; /* The number of threads queued. */
  284. pthread_t *waitingthreadhdls; /* The thread handles. */
  285. } pthread_cond_t;
  286. #ifndef __clockid_t_defined
  287. typedef DWORD clockid_t;
  288. #endif
  289. #ifndef CLOCK_MONOTONIC
  290. #define CLOCK_MONOTONIC (1)
  291. #endif
  292. #ifndef CLOCK_REALTIME
  293. #define CLOCK_REALTIME (2)
  294. #endif
  295. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  296. #define _TIMESPEC_DEFINED
  297. #endif
  298. #ifndef _TIMESPEC_DEFINED
  299. struct timespec {
  300. time_t tv_sec; /* seconds */
  301. long tv_nsec; /* nanoseconds */
  302. };
  303. #endif
  304. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  305. static int pthread_mutex_lock(pthread_mutex_t *);
  306. static int pthread_mutex_unlock(pthread_mutex_t *);
  307. static void path_to_unicode(const struct mg_connection *conn,
  308. const char *path,
  309. wchar_t *wbuf,
  310. size_t wbuf_len);
  311. struct file;
  312. static const char *
  313. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  314. #if defined(HAVE_STDINT)
  315. #include <stdint.h>
  316. #else
  317. typedef unsigned char uint8_t;
  318. typedef unsigned short uint16_t;
  319. typedef unsigned int uint32_t;
  320. typedef unsigned __int64 uint64_t;
  321. typedef __int64 int64_t;
  322. #ifndef INT64_MAX
  323. #define INT64_MAX (9223372036854775807)
  324. #endif
  325. #endif /* HAVE_STDINT */
  326. /* POSIX dirent interface */
  327. struct dirent {
  328. char d_name[PATH_MAX];
  329. };
  330. typedef struct DIR {
  331. HANDLE handle;
  332. WIN32_FIND_DATAW info;
  333. struct dirent result;
  334. } DIR;
  335. #if defined(_WIN32) && !defined(POLLIN)
  336. #ifndef HAVE_POLL
  337. struct pollfd {
  338. SOCKET fd;
  339. short events;
  340. short revents;
  341. };
  342. #define POLLIN (0x0300)
  343. #endif
  344. #endif
  345. /* Mark required libraries */
  346. #if defined(_MSC_VER)
  347. #pragma comment(lib, "Ws2_32.lib")
  348. #endif
  349. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  350. block */
  351. #include <sys/wait.h>
  352. #include <sys/socket.h>
  353. #include <sys/poll.h>
  354. #include <netinet/in.h>
  355. #include <arpa/inet.h>
  356. #include <sys/time.h>
  357. #include <sys/utsname.h>
  358. #include <stdint.h>
  359. #include <inttypes.h>
  360. #include <netdb.h>
  361. #include <netinet/tcp.h>
  362. typedef const void *SOCK_OPT_TYPE;
  363. #if defined(ANDROID)
  364. typedef unsigned short int in_port_t;
  365. #endif
  366. #include <pwd.h>
  367. #include <unistd.h>
  368. #include <grp.h>
  369. #include <dirent.h>
  370. #define vsnprintf_impl vsnprintf
  371. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  372. #include <dlfcn.h>
  373. #endif
  374. #include <pthread.h>
  375. #if defined(__MACH__)
  376. #define SSL_LIB "libssl.dylib"
  377. #define CRYPTO_LIB "libcrypto.dylib"
  378. #else
  379. #if !defined(SSL_LIB)
  380. #define SSL_LIB "libssl.so"
  381. #endif
  382. #if !defined(CRYPTO_LIB)
  383. #define CRYPTO_LIB "libcrypto.so"
  384. #endif
  385. #endif
  386. #ifndef O_BINARY
  387. #define O_BINARY (0)
  388. #endif /* O_BINARY */
  389. #define closesocket(a) (close(a))
  390. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  391. #define mg_remove(conn, x) (remove(x))
  392. #define mg_sleep(x) (usleep((x)*1000))
  393. #define mg_opendir(conn, x) (opendir(x))
  394. #define mg_closedir(x) (closedir(x))
  395. #define mg_readdir(x) (readdir(x))
  396. #define ERRNO (errno)
  397. #define INVALID_SOCKET (-1)
  398. #define INT64_FMT PRId64
  399. #define UINT64_FMT PRIu64
  400. typedef int SOCKET;
  401. #define WINCDECL
  402. #if defined(__hpux)
  403. /* HPUX 11 does not have monotonic, fall back to realtime */
  404. #ifndef CLOCK_MONOTONIC
  405. #define CLOCK_MONOTONIC CLOCK_REALTIME
  406. #endif
  407. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  408. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  409. * the prototypes use int* rather than socklen_t* which matches the
  410. * actual library expectation. When called with the wrong size arg
  411. * accept() returns a zero client inet addr and check_acl() always
  412. * fails. Since socklen_t is widely used below, just force replace
  413. * their typedef with int. - DTL
  414. */
  415. #define socklen_t int
  416. #endif /* hpux */
  417. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  418. block */
  419. /* va_copy should always be a macro, C99 and C++11 - DTL */
  420. #ifndef va_copy
  421. #define va_copy(x, y) ((x) = (y))
  422. #endif
  423. #ifdef _WIN32
  424. /* Create substitutes for POSIX functions in Win32. */
  425. #if defined(__MINGW32__)
  426. /* Show no warning in case system functions are not used. */
  427. #pragma GCC diagnostic push
  428. #pragma GCC diagnostic ignored "-Wunused-function"
  429. #endif
  430. static CRITICAL_SECTION global_log_file_lock;
  431. static DWORD
  432. pthread_self(void)
  433. {
  434. return GetCurrentThreadId();
  435. }
  436. static int
  437. pthread_key_create(
  438. pthread_key_t *key,
  439. void (*_ignored)(void *) /* destructor not supported for Windows */
  440. )
  441. {
  442. (void)_ignored;
  443. if ((key != 0)) {
  444. *key = TlsAlloc();
  445. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  446. }
  447. return -2;
  448. }
  449. static int
  450. pthread_key_delete(pthread_key_t key)
  451. {
  452. return TlsFree(key) ? 0 : 1;
  453. }
  454. static int
  455. pthread_setspecific(pthread_key_t key, void *value)
  456. {
  457. return TlsSetValue(key, value) ? 0 : 1;
  458. }
  459. static void *
  460. pthread_getspecific(pthread_key_t key)
  461. {
  462. return TlsGetValue(key);
  463. }
  464. #if defined(__MINGW32__)
  465. /* Enable unused function warning again */
  466. #pragma GCC diagnostic pop
  467. #endif
  468. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  469. #else
  470. static pthread_mutexattr_t pthread_mutex_attr;
  471. #endif /* _WIN32 */
  472. #define PASSWORDS_FILE_NAME ".htpasswd"
  473. #define CGI_ENVIRONMENT_SIZE (4096)
  474. #define MAX_CGI_ENVIR_VARS (256)
  475. #define MG_BUF_LEN (8192)
  476. #ifndef MAX_REQUEST_SIZE
  477. #define MAX_REQUEST_SIZE (16384)
  478. #endif
  479. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  480. "request size length must be a positive number");
  481. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  482. #if !defined(DEBUG_TRACE)
  483. #if defined(DEBUG)
  484. #if defined(_WIN32_WCE)
  485. /* Create substitutes for POSIX functions in Win32. */
  486. #if defined(__MINGW32__)
  487. /* Show no warning in case system functions are not used. */
  488. #pragma GCC diagnostic push
  489. #pragma GCC diagnostic ignored "-Wunused-function"
  490. #endif
  491. static time_t
  492. time(time_t *ptime)
  493. {
  494. time_t t;
  495. SYSTEMTIME st;
  496. FILETIME ft;
  497. GetSystemTime(&st);
  498. SystemTimeToFileTime(&st, &ft);
  499. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  500. if (ptime != NULL) {
  501. *ptime = t;
  502. }
  503. return t;
  504. }
  505. static struct tm *
  506. localtime_s(const time_t *ptime, struct tm *ptm)
  507. {
  508. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  509. FILETIME ft, lft;
  510. SYSTEMTIME st;
  511. TIME_ZONE_INFORMATION tzinfo;
  512. if (ptm == NULL) {
  513. return NULL;
  514. }
  515. *(int64_t *)&ft = t;
  516. FileTimeToLocalFileTime(&ft, &lft);
  517. FileTimeToSystemTime(&lft, &st);
  518. ptm->tm_year = st.wYear - 1900;
  519. ptm->tm_mon = st.wMonth - 1;
  520. ptm->tm_wday = st.wDayOfWeek;
  521. ptm->tm_mday = st.wDay;
  522. ptm->tm_hour = st.wHour;
  523. ptm->tm_min = st.wMinute;
  524. ptm->tm_sec = st.wSecond;
  525. ptm->tm_yday = 0; /* hope nobody uses this */
  526. ptm->tm_isdst =
  527. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  528. return ptm;
  529. }
  530. static struct tm *
  531. gmtime_s(const time_t *ptime, struct tm *ptm)
  532. {
  533. /* FIXME(lsm): fix this. */
  534. return localtime_s(ptime, ptm);
  535. }
  536. static struct tm tm_array[MAX_WORKER_THREADS];
  537. static int tm_index = 0;
  538. static struct tm *
  539. localtime(const time_t *ptime)
  540. {
  541. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  542. return localtime_s(ptime, tls_tm + i);
  543. }
  544. static struct tm *
  545. gmtime(const time_t *ptime)
  546. {
  547. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  548. return gmtime_s(ptime, tls_tm + i);
  549. }
  550. static size_t
  551. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  552. {
  553. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  554. // for WinCE");
  555. return 0;
  556. }
  557. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  558. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  559. #define remove(f) mg_remove(NULL, f)
  560. static int
  561. rename(const char *a, const char *b)
  562. {
  563. wchar_t wa[PATH_MAX];
  564. wchar_t wb[PATH_MAX];
  565. path_to_unicode(conn, path, wa, ARRAY_SIZE(wa));
  566. path_to_unicode(conn, path, wb, ARRAY_SIZE(wb));
  567. return MoveFileW(wa, wb) ? 0 : -1;
  568. }
  569. struct stat {
  570. int64_t st_size;
  571. };
  572. static int
  573. stat(const char *name, struct stat *st)
  574. {
  575. wchar_t wbuf[PATH_MAX];
  576. WIN32_FILE_ATTRIBUTE_DATA attr;
  577. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  578. memset(&attr, 0, sizeof(attr));
  579. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  580. st->st_size = ((int64_t)attr.nFileSizeHigh)
  581. << 32 + (int64_t)attr.nFileSizeLow;
  582. /* TODO ... */
  583. }
  584. #define access(x, a) 1 /* not required anyway */
  585. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  586. #define EEXIST 1 /* TODO: See Windows error codes */
  587. #define EACCES 2 /* TODO: See Windows error codes */
  588. #define ENOENT 3 /* TODO: See Windows Error codes */
  589. #if defined(__MINGW32__)
  590. /* Enable unused function warning again */
  591. #pragma GCC diagnostic pop
  592. #endif
  593. #endif /* defined(_WIN32_WCE) */
  594. static void DEBUG_TRACE_FUNC(const char *func,
  595. unsigned line,
  596. PRINTF_FORMAT_STRING(const char *fmt),
  597. ...) PRINTF_ARGS(3, 4);
  598. static void
  599. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  600. {
  601. va_list args;
  602. flockfile(stdout);
  603. printf("*** %lu.%p.%s.%u: ",
  604. (unsigned long)time(NULL),
  605. (void *)pthread_self(),
  606. func,
  607. line);
  608. va_start(args, fmt);
  609. vprintf(fmt, args);
  610. va_end(args);
  611. putchar('\n');
  612. fflush(stdout);
  613. funlockfile(stdout);
  614. }
  615. #define DEBUG_TRACE(fmt, ...) \
  616. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  617. #else
  618. #define DEBUG_TRACE(fmt, ...) \
  619. do { \
  620. } while (0)
  621. #endif /* DEBUG */
  622. #endif /* DEBUG_TRACE */
  623. #if defined(MEMORY_DEBUGGING)
  624. unsigned long mg_memory_debug_blockCount = 0;
  625. unsigned long mg_memory_debug_totalMemUsed = 0;
  626. static void *
  627. mg_malloc_ex(size_t size, const char *file, unsigned line)
  628. {
  629. void *data = malloc(size + sizeof(size_t));
  630. void *memory = 0;
  631. char mallocStr[256];
  632. if (data) {
  633. *(size_t *)data = size;
  634. mg_memory_debug_totalMemUsed += size;
  635. mg_memory_debug_blockCount++;
  636. memory = (void *)(((char *)data) + sizeof(size_t));
  637. }
  638. sprintf(mallocStr,
  639. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  640. memory,
  641. (unsigned long)size,
  642. mg_memory_debug_totalMemUsed,
  643. mg_memory_debug_blockCount,
  644. file,
  645. line);
  646. #if defined(_WIN32)
  647. OutputDebugStringA(mallocStr);
  648. #else
  649. DEBUG_TRACE("%s", mallocStr);
  650. #endif
  651. return memory;
  652. }
  653. static void *
  654. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  655. {
  656. void *data = mg_malloc_ex(size * count, file, line);
  657. if (data) {
  658. memset(data, 0, size);
  659. }
  660. return data;
  661. }
  662. static void
  663. mg_free_ex(void *memory, const char *file, unsigned line)
  664. {
  665. char mallocStr[256];
  666. void *data = (void *)(((char *)memory) - sizeof(size_t));
  667. size_t size;
  668. if (memory) {
  669. size = *(size_t *)data;
  670. mg_memory_debug_totalMemUsed -= size;
  671. mg_memory_debug_blockCount--;
  672. sprintf(mallocStr,
  673. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  674. memory,
  675. (unsigned long)size,
  676. mg_memory_debug_totalMemUsed,
  677. mg_memory_debug_blockCount,
  678. file,
  679. line);
  680. #if defined(_WIN32)
  681. OutputDebugStringA(mallocStr);
  682. #else
  683. DEBUG_TRACE("%s", mallocStr);
  684. #endif
  685. free(data);
  686. }
  687. }
  688. static void *
  689. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  690. {
  691. char mallocStr[256];
  692. void *data;
  693. void *_realloc;
  694. size_t oldsize;
  695. if (newsize) {
  696. if (memory) {
  697. data = (void *)(((char *)memory) - sizeof(size_t));
  698. oldsize = *(size_t *)data;
  699. _realloc = realloc(data, newsize + sizeof(size_t));
  700. if (_realloc) {
  701. data = _realloc;
  702. mg_memory_debug_totalMemUsed -= oldsize;
  703. sprintf(mallocStr,
  704. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  705. memory,
  706. (unsigned long)oldsize,
  707. mg_memory_debug_totalMemUsed,
  708. mg_memory_debug_blockCount,
  709. file,
  710. line);
  711. #if defined(_WIN32)
  712. OutputDebugStringA(mallocStr);
  713. #else
  714. DEBUG_TRACE("%s", mallocStr);
  715. #endif
  716. mg_memory_debug_totalMemUsed += newsize;
  717. sprintf(mallocStr,
  718. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  719. memory,
  720. (unsigned long)newsize,
  721. mg_memory_debug_totalMemUsed,
  722. mg_memory_debug_blockCount,
  723. file,
  724. line);
  725. #if defined(_WIN32)
  726. OutputDebugStringA(mallocStr);
  727. #else
  728. DEBUG_TRACE("%s", mallocStr);
  729. #endif
  730. *(size_t *)data = newsize;
  731. data = (void *)(((char *)data) + sizeof(size_t));
  732. } else {
  733. #if defined(_WIN32)
  734. OutputDebugStringA("MEM: realloc failed\n");
  735. #else
  736. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  737. #endif
  738. return _realloc;
  739. }
  740. } else {
  741. data = mg_malloc_ex(newsize, file, line);
  742. }
  743. } else {
  744. data = 0;
  745. mg_free_ex(memory, file, line);
  746. }
  747. return data;
  748. }
  749. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  750. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  751. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  752. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  753. #else
  754. static __inline void *
  755. mg_malloc(size_t a)
  756. {
  757. return malloc(a);
  758. }
  759. static __inline void *
  760. mg_calloc(size_t a, size_t b)
  761. {
  762. return calloc(a, b);
  763. }
  764. static __inline void *
  765. mg_realloc(void *a, size_t b)
  766. {
  767. return realloc(a, b);
  768. }
  769. static __inline void
  770. mg_free(void *a)
  771. {
  772. free(a);
  773. }
  774. #endif
  775. static void mg_vsnprintf(const struct mg_connection *conn,
  776. int *truncated,
  777. char *buf,
  778. size_t buflen,
  779. const char *fmt,
  780. va_list ap);
  781. static void mg_snprintf(const struct mg_connection *conn,
  782. int *truncated,
  783. char *buf,
  784. size_t buflen,
  785. PRINTF_FORMAT_STRING(const char *fmt),
  786. ...) PRINTF_ARGS(5, 6);
  787. /* This following lines are just meant as a reminder to use the mg-functions
  788. * for memory management */
  789. #ifdef malloc
  790. #undef malloc
  791. #endif
  792. #ifdef calloc
  793. #undef calloc
  794. #endif
  795. #ifdef realloc
  796. #undef realloc
  797. #endif
  798. #ifdef free
  799. #undef free
  800. #endif
  801. #ifdef snprintf
  802. #undef snprintf
  803. #endif
  804. #ifdef vsnprintf
  805. #undef vsnprintf
  806. #endif
  807. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  808. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  809. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  810. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  811. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  812. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  813. * but this define only works well for Windows. */
  814. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  815. #endif
  816. #define MD5_STATIC static
  817. #include "md5.inl"
  818. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  819. #ifdef NO_SOCKLEN_T
  820. typedef int socklen_t;
  821. #endif /* NO_SOCKLEN_T */
  822. #define _DARWIN_UNLIMITED_SELECT
  823. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  824. #if !defined(MSG_NOSIGNAL)
  825. #define MSG_NOSIGNAL (0)
  826. #endif
  827. #if !defined(SOMAXCONN)
  828. #define SOMAXCONN (100)
  829. #endif
  830. /* Size of the accepted socket queue */
  831. #if !defined(MGSQLEN)
  832. #define MGSQLEN (20)
  833. #endif
  834. #if defined(NO_SSL)
  835. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  836. typedef struct SSL_CTX SSL_CTX;
  837. #else
  838. #if defined(NO_SSL_DL)
  839. #include <openssl/ssl.h>
  840. #include <openssl/err.h>
  841. #include <openssl/crypto.h>
  842. #include <openssl/x509.h>
  843. #include <openssl/pem.h>
  844. #include <openssl/engine.h>
  845. #include <openssl/conf.h>
  846. #else
  847. /* SSL loaded dynamically from DLL.
  848. * I put the prototypes here to be independent from OpenSSL source
  849. * installation. */
  850. typedef struct ssl_st SSL;
  851. typedef struct ssl_method_st SSL_METHOD;
  852. typedef struct ssl_ctx_st SSL_CTX;
  853. typedef struct x509_store_ctx_st X509_STORE_CTX;
  854. #define SSL_CTRL_OPTIONS (32)
  855. #define SSL_CTRL_CLEAR_OPTIONS (77)
  856. #define SSL_CTRL_SET_ECDH_AUTO (94)
  857. #define SSL_VERIFY_NONE (0)
  858. #define SSL_VERIFY_PEER (1)
  859. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  860. #define SSL_VERIFY_CLIENT_ONCE (4)
  861. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  862. #define SSL_OP_NO_SSLv2 (0x01000000L)
  863. #define SSL_OP_NO_SSLv3 (0x02000000L)
  864. #define SSL_OP_NO_TLSv1 (0x04000000L)
  865. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  866. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  867. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  868. struct ssl_func {
  869. const char *name; /* SSL function name */
  870. void (*ptr)(void); /* Function pointer */
  871. };
  872. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  873. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  874. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  875. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  876. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  877. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  878. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  879. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  880. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  881. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  882. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  883. #define SSL_CTX_use_PrivateKey_file \
  884. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  885. #define SSL_CTX_use_certificate_file \
  886. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  887. #define SSL_CTX_set_default_passwd_cb \
  888. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  889. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  890. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  891. #define SSL_CTX_use_certificate_chain_file \
  892. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  893. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  894. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  895. #define SSL_CTX_set_verify \
  896. (*(void (*)(SSL_CTX *, \
  897. int, \
  898. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  899. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  900. #define SSL_CTX_load_verify_locations \
  901. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  902. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  903. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  904. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  905. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  906. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  907. #define SSL_CIPHER_get_name \
  908. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  909. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  910. #define SSL_CTX_set_session_id_context \
  911. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  912. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  913. #define SSL_CTX_set_cipher_list \
  914. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  915. #define SSL_CTX_set_options(ctx, op) \
  916. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  917. #define SSL_CTX_clear_options(ctx, op) \
  918. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  919. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  920. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  921. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  922. #define CRYPTO_set_locking_callback \
  923. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  924. #define CRYPTO_set_id_callback \
  925. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  926. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  927. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  928. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  929. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  930. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  931. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  932. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  933. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  934. /* set_ssl_option() function updates this array.
  935. * It loads SSL library dynamically and changes NULLs to the actual addresses
  936. * of respective functions. The macros above (like SSL_connect()) are really
  937. * just calling these functions indirectly via the pointer. */
  938. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  939. {"SSL_accept", NULL},
  940. {"SSL_connect", NULL},
  941. {"SSL_read", NULL},
  942. {"SSL_write", NULL},
  943. {"SSL_get_error", NULL},
  944. {"SSL_set_fd", NULL},
  945. {"SSL_new", NULL},
  946. {"SSL_CTX_new", NULL},
  947. {"SSLv23_server_method", NULL},
  948. {"SSL_library_init", NULL},
  949. {"SSL_CTX_use_PrivateKey_file", NULL},
  950. {"SSL_CTX_use_certificate_file", NULL},
  951. {"SSL_CTX_set_default_passwd_cb", NULL},
  952. {"SSL_CTX_free", NULL},
  953. {"SSL_load_error_strings", NULL},
  954. {"SSL_CTX_use_certificate_chain_file", NULL},
  955. {"SSLv23_client_method", NULL},
  956. {"SSL_pending", NULL},
  957. {"SSL_CTX_set_verify", NULL},
  958. {"SSL_shutdown", NULL},
  959. {"SSL_CTX_load_verify_locations", NULL},
  960. {"SSL_CTX_set_default_verify_paths", NULL},
  961. {"SSL_CTX_set_verify_depth", NULL},
  962. {"SSL_get_peer_certificate", NULL},
  963. {"SSL_get_version", NULL},
  964. {"SSL_get_current_cipher", NULL},
  965. {"SSL_CIPHER_get_name", NULL},
  966. {"SSL_CTX_check_private_key", NULL},
  967. {"SSL_CTX_set_session_id_context", NULL},
  968. {"SSL_CTX_ctrl", NULL},
  969. {"SSL_CTX_set_cipher_list", NULL},
  970. {NULL, NULL}};
  971. /* Similar array as ssl_sw. These functions could be located in different
  972. * lib. */
  973. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  974. {"CRYPTO_set_locking_callback", NULL},
  975. {"CRYPTO_set_id_callback", NULL},
  976. {"ERR_get_error", NULL},
  977. {"ERR_error_string", NULL},
  978. {"ERR_remove_state", NULL},
  979. {"ERR_free_strings", NULL},
  980. {"ENGINE_cleanup", NULL},
  981. {"CONF_modules_unload", NULL},
  982. {"CRYPTO_cleanup_all_ex_data", NULL},
  983. {"EVP_cleanup", NULL},
  984. {NULL, NULL}};
  985. #endif /* NO_SSL_DL */
  986. #endif /* NO_SSL */
  987. #if !defined(NO_CACHING)
  988. static const char *month_names[] = {"Jan",
  989. "Feb",
  990. "Mar",
  991. "Apr",
  992. "May",
  993. "Jun",
  994. "Jul",
  995. "Aug",
  996. "Sep",
  997. "Oct",
  998. "Nov",
  999. "Dec"};
  1000. #endif /* !NO_CACHING */
  1001. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1002. * union u. */
  1003. union usa {
  1004. struct sockaddr sa;
  1005. struct sockaddr_in sin;
  1006. #if defined(USE_IPV6)
  1007. struct sockaddr_in6 sin6;
  1008. #endif
  1009. };
  1010. /* Describes a string (chunk of memory). */
  1011. struct vec {
  1012. const char *ptr;
  1013. size_t len;
  1014. };
  1015. struct file {
  1016. uint64_t size;
  1017. time_t last_modified;
  1018. FILE *fp;
  1019. const char *membuf; /* Non-NULL if file data is in memory */
  1020. int is_directory;
  1021. int gzipped; /* set to 1 if the content is gzipped
  1022. * in which case we need a content-encoding: gzip header */
  1023. };
  1024. #define STRUCT_FILE_INITIALIZER \
  1025. { \
  1026. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1027. }
  1028. /* Describes listening socket, or socket which was accept()-ed by the master
  1029. * thread and queued for future handling by the worker thread. */
  1030. struct socket {
  1031. SOCKET sock; /* Listening socket */
  1032. union usa lsa; /* Local socket address */
  1033. union usa rsa; /* Remote socket address */
  1034. unsigned char is_ssl; /* Is port SSL-ed */
  1035. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1036. * port */
  1037. };
  1038. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1039. enum {
  1040. CGI_EXTENSIONS,
  1041. CGI_ENVIRONMENT,
  1042. PUT_DELETE_PASSWORDS_FILE,
  1043. CGI_INTERPRETER,
  1044. PROTECT_URI,
  1045. AUTHENTICATION_DOMAIN,
  1046. SSI_EXTENSIONS,
  1047. THROTTLE,
  1048. ACCESS_LOG_FILE,
  1049. ENABLE_DIRECTORY_LISTING,
  1050. ERROR_LOG_FILE,
  1051. GLOBAL_PASSWORDS_FILE,
  1052. INDEX_FILES,
  1053. ENABLE_KEEP_ALIVE,
  1054. ACCESS_CONTROL_LIST,
  1055. EXTRA_MIME_TYPES,
  1056. LISTENING_PORTS,
  1057. DOCUMENT_ROOT,
  1058. SSL_CERTIFICATE,
  1059. NUM_THREADS,
  1060. RUN_AS_USER,
  1061. REWRITE,
  1062. HIDE_FILES,
  1063. REQUEST_TIMEOUT,
  1064. SSL_DO_VERIFY_PEER,
  1065. SSL_CA_PATH,
  1066. SSL_CA_FILE,
  1067. SSL_VERIFY_DEPTH,
  1068. SSL_DEFAULT_VERIFY_PATHS,
  1069. SSL_CIPHER_LIST,
  1070. SSL_PROTOCOL_VERSION,
  1071. SSL_SHORT_TRUST,
  1072. #if defined(USE_WEBSOCKET)
  1073. WEBSOCKET_TIMEOUT,
  1074. #endif
  1075. DECODE_URL,
  1076. #if defined(USE_LUA)
  1077. LUA_PRELOAD_FILE,
  1078. LUA_SCRIPT_EXTENSIONS,
  1079. LUA_SERVER_PAGE_EXTENSIONS,
  1080. #endif
  1081. #if defined(USE_DUKTAPE)
  1082. DUKTAPE_SCRIPT_EXTENSIONS,
  1083. #endif
  1084. #if defined(USE_WEBSOCKET)
  1085. WEBSOCKET_ROOT,
  1086. #endif
  1087. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1088. LUA_WEBSOCKET_EXTENSIONS,
  1089. #endif
  1090. ACCESS_CONTROL_ALLOW_ORIGIN,
  1091. ERROR_PAGES,
  1092. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1093. * socket option typedef TCP_NODELAY. */
  1094. #if !defined(NO_CACHING)
  1095. STATIC_FILE_MAX_AGE,
  1096. #endif
  1097. NUM_OPTIONS
  1098. };
  1099. /* Config option name, config types, default value */
  1100. static struct mg_option config_options[] = {
  1101. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1102. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1103. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1104. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1105. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1106. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1107. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1108. {"throttle", CONFIG_TYPE_STRING, NULL},
  1109. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1110. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1111. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1112. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1113. {"index_files",
  1114. CONFIG_TYPE_STRING,
  1115. #ifdef USE_LUA
  1116. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1117. "index.shtml,index.php"},
  1118. #else
  1119. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1120. #endif
  1121. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1122. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1123. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1124. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1125. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1126. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1127. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1128. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1129. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1130. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1131. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1132. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1133. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1134. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1135. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1136. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1137. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1138. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1139. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1140. #if defined(USE_WEBSOCKET)
  1141. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1142. #endif
  1143. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1144. #if defined(USE_LUA)
  1145. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1146. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1147. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1148. #endif
  1149. #if defined(USE_DUKTAPE)
  1150. /* The support for duktape is still in alpha version state.
  1151. * The name of this config option might change. */
  1152. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1153. #endif
  1154. #if defined(USE_WEBSOCKET)
  1155. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1156. #endif
  1157. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1158. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1159. #endif
  1160. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1161. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1162. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1163. #if !defined(NO_CACHING)
  1164. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1165. #endif
  1166. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1167. /* Check if the config_options and the corresponding enum have compatible
  1168. * sizes. */
  1169. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1170. == (NUM_OPTIONS + 1),
  1171. "config_options and enum not sync");
  1172. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1173. struct mg_handler_info {
  1174. /* Name/Pattern of the URI. */
  1175. char *uri;
  1176. size_t uri_len;
  1177. /* handler type */
  1178. int handler_type;
  1179. /* Handler for http/https or authorization requests. */
  1180. mg_request_handler handler;
  1181. /* Handler for ws/wss (websocket) requests. */
  1182. mg_websocket_connect_handler connect_handler;
  1183. mg_websocket_ready_handler ready_handler;
  1184. mg_websocket_data_handler data_handler;
  1185. mg_websocket_close_handler close_handler;
  1186. /* Handler for authorization requests */
  1187. mg_authorization_handler auth_handler;
  1188. /* User supplied argument for the handler function. */
  1189. void *cbdata;
  1190. /* next handler in a linked list */
  1191. struct mg_handler_info *next;
  1192. };
  1193. struct mg_context {
  1194. volatile int stop_flag; /* Should we stop event loop */
  1195. SSL_CTX *ssl_ctx; /* SSL context */
  1196. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1197. struct mg_callbacks callbacks; /* User-defined callback function */
  1198. void *user_data; /* User-defined data */
  1199. int context_type; /* 1 = server context, 2 = client context */
  1200. struct socket *listening_sockets;
  1201. in_port_t *listening_ports;
  1202. unsigned int num_listening_sockets;
  1203. volatile int
  1204. running_worker_threads; /* Number of currently running worker threads */
  1205. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1206. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1207. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1208. volatile int sq_head; /* Head of the socket queue */
  1209. volatile int sq_tail; /* Tail of the socket queue */
  1210. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1211. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1212. pthread_t masterthreadid; /* The master thread ID */
  1213. unsigned int
  1214. cfg_worker_threads; /* The number of configured worker threads. */
  1215. pthread_t *workerthreadids; /* The worker thread IDs */
  1216. time_t start_time; /* Server start time, used for authentication */
  1217. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1218. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1219. unsigned long nonce_count; /* Used nonces, used for authentication */
  1220. char *systemName; /* What operating system is running */
  1221. /* linked list of uri handlers */
  1222. struct mg_handler_info *handlers;
  1223. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1224. /* linked list of shared lua websockets */
  1225. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1226. #endif
  1227. #ifdef USE_TIMERS
  1228. struct ttimers *timers;
  1229. #endif
  1230. };
  1231. struct mg_connection {
  1232. struct mg_request_info request_info;
  1233. struct mg_context *ctx;
  1234. SSL *ssl; /* SSL descriptor */
  1235. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1236. struct socket client; /* Connected client */
  1237. time_t conn_birth_time; /* Time (wall clock) when connection was
  1238. * established */
  1239. struct timespec req_time; /* Time (since system start) when the request
  1240. * was received */
  1241. int64_t num_bytes_sent; /* Total bytes sent to client */
  1242. int64_t content_len; /* Content-Length header value */
  1243. int64_t consumed_content; /* How many bytes of content have been read */
  1244. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1245. * data available, 2: all data read */
  1246. size_t chunk_remainder; /* Unread data from the last chunk */
  1247. char *buf; /* Buffer for received data */
  1248. char *path_info; /* PATH_INFO part of the URL */
  1249. int must_close; /* 1 if connection must be closed */
  1250. int in_error_handler; /* 1 if in handler for user defined error
  1251. * pages */
  1252. int internal_error; /* 1 if an error occured while processing the
  1253. * request */
  1254. int buf_size; /* Buffer size */
  1255. int request_len; /* Size of the request + headers in a buffer */
  1256. int data_len; /* Total size of data in a buffer */
  1257. int status_code; /* HTTP reply status code, e.g. 200 */
  1258. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1259. * throttle */
  1260. time_t last_throttle_time; /* Last time throttled data was sent */
  1261. int64_t last_throttle_bytes; /* Bytes sent this second */
  1262. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1263. * atomic transmissions for websockets */
  1264. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1265. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1266. #endif
  1267. };
  1268. static pthread_key_t sTlsKey; /* Thread local storage index */
  1269. static int sTlsInit = 0;
  1270. static int thread_idx_max = 0;
  1271. struct mg_workerTLS {
  1272. int is_master;
  1273. unsigned long thread_idx;
  1274. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1275. HANDLE pthread_cond_helper_mutex;
  1276. #endif
  1277. };
  1278. /* Directory entry */
  1279. struct de {
  1280. struct mg_connection *conn;
  1281. char *file_name;
  1282. struct file file;
  1283. };
  1284. #if defined(USE_WEBSOCKET)
  1285. static int is_websocket_protocol(const struct mg_connection *conn);
  1286. #else
  1287. #define is_websocket_protocol(conn) (0)
  1288. #endif
  1289. static int
  1290. mg_atomic_inc(volatile int *addr)
  1291. {
  1292. int ret;
  1293. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1294. /* Depending on the SDK, this function uses either
  1295. * (volatile unsigned int *) or (volatile LONG *),
  1296. * so whatever you use, the other SDK is likely to raise a warning. */
  1297. ret = InterlockedIncrement((volatile long *)addr);
  1298. #elif defined(__GNUC__) \
  1299. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1300. ret = __sync_add_and_fetch(addr, 1);
  1301. #else
  1302. ret = (++(*addr));
  1303. #endif
  1304. return ret;
  1305. }
  1306. static int
  1307. mg_atomic_dec(volatile int *addr)
  1308. {
  1309. int ret;
  1310. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1311. /* Depending on the SDK, this function uses either
  1312. * (volatile unsigned int *) or (volatile LONG *),
  1313. * so whatever you use, the other SDK is likely to raise a warning. */
  1314. ret = InterlockedDecrement((volatile long *)addr);
  1315. #elif defined(__GNUC__) \
  1316. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1317. ret = __sync_sub_and_fetch(addr, 1);
  1318. #else
  1319. ret = (--(*addr));
  1320. #endif
  1321. return ret;
  1322. }
  1323. #if !defined(NO_THREAD_NAME)
  1324. #if defined(_WIN32) && defined(_MSC_VER)
  1325. /* Set the thread name for debugging purposes in Visual Studio
  1326. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1327. */
  1328. #pragma pack(push, 8)
  1329. typedef struct tagTHREADNAME_INFO {
  1330. DWORD dwType; /* Must be 0x1000. */
  1331. LPCSTR szName; /* Pointer to name (in user addr space). */
  1332. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1333. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1334. } THREADNAME_INFO;
  1335. #pragma pack(pop)
  1336. #elif defined(__linux__)
  1337. #include <sys/prctl.h>
  1338. #include <sys/sendfile.h>
  1339. #endif
  1340. static void
  1341. mg_set_thread_name(const char *name)
  1342. {
  1343. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1344. mg_snprintf(
  1345. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1346. #if defined(_WIN32)
  1347. #if defined(_MSC_VER)
  1348. /* Windows and Visual Studio Compiler */
  1349. __try
  1350. {
  1351. THREADNAME_INFO info;
  1352. info.dwType = 0x1000;
  1353. info.szName = threadName;
  1354. info.dwThreadID = ~0U;
  1355. info.dwFlags = 0;
  1356. RaiseException(0x406D1388,
  1357. 0,
  1358. sizeof(info) / sizeof(ULONG_PTR),
  1359. (ULONG_PTR *)&info);
  1360. }
  1361. __except(EXCEPTION_EXECUTE_HANDLER)
  1362. {
  1363. }
  1364. #elif defined(__MINGW32__)
  1365. /* No option known to set thread name for MinGW */
  1366. #endif
  1367. #elif defined(__GLIBC__) \
  1368. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1369. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1370. (void)pthread_setname_np(pthread_self(), threadName);
  1371. #elif defined(__linux__)
  1372. /* on linux we can use the old prctl function */
  1373. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1374. #endif
  1375. }
  1376. #else /* !defined(NO_THREAD_NAME) */
  1377. void
  1378. mg_set_thread_name(const char *threadName)
  1379. {
  1380. }
  1381. #endif
  1382. #if defined(MG_LEGACY_INTERFACE)
  1383. const char **
  1384. mg_get_valid_option_names(void)
  1385. {
  1386. /* This function is deprecated. Use mg_get_valid_options instead. */
  1387. static const char *
  1388. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1389. int i;
  1390. for (i = 0; config_options[i].name != NULL; i++) {
  1391. data[i * 2] = config_options[i].name;
  1392. data[i * 2 + 1] = config_options[i].default_value;
  1393. }
  1394. return data;
  1395. }
  1396. #endif
  1397. const struct mg_option *
  1398. mg_get_valid_options(void)
  1399. {
  1400. return config_options;
  1401. }
  1402. static int
  1403. is_file_in_memory(const struct mg_connection *conn,
  1404. const char *path,
  1405. struct file *filep)
  1406. {
  1407. size_t size = 0;
  1408. if (!conn || !filep) {
  1409. return 0;
  1410. }
  1411. if (conn->ctx->callbacks.open_file) {
  1412. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1413. if (filep->membuf != NULL) {
  1414. /* NOTE: override filep->size only on success. Otherwise, it might
  1415. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1416. filep->size = size;
  1417. }
  1418. }
  1419. return filep->membuf != NULL;
  1420. }
  1421. static int
  1422. is_file_opened(const struct file *filep)
  1423. {
  1424. if (!filep) {
  1425. return 0;
  1426. }
  1427. return filep->membuf != NULL || filep->fp != NULL;
  1428. }
  1429. /* mg_fopen will open a file either in memory or on the disk.
  1430. * The input parameter path is a string in UTF-8 encoding.
  1431. * The input parameter mode is the same as for fopen.
  1432. * Either fp or membuf will be set in the output struct filep.
  1433. * The function returns 1 on success, 0 on error. */
  1434. static int
  1435. mg_fopen(const struct mg_connection *conn,
  1436. const char *path,
  1437. const char *mode,
  1438. struct file *filep)
  1439. {
  1440. struct stat st;
  1441. if (!filep) {
  1442. return 0;
  1443. }
  1444. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1445. * only get the file status. They should not work on different members of
  1446. * the same structure (bad cohesion). */
  1447. memset(filep, 0, sizeof(*filep));
  1448. if (stat(path, &st) == 0) {
  1449. filep->size = (uint64_t)(st.st_size);
  1450. }
  1451. if (!is_file_in_memory(conn, path, filep)) {
  1452. #ifdef _WIN32
  1453. wchar_t wbuf[PATH_MAX], wmode[20];
  1454. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1455. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1456. filep->fp = _wfopen(wbuf, wmode);
  1457. #else
  1458. /* Linux et al already use unicode. No need to convert. */
  1459. filep->fp = fopen(path, mode);
  1460. #endif
  1461. }
  1462. return is_file_opened(filep);
  1463. }
  1464. static void
  1465. mg_fclose(struct file *filep)
  1466. {
  1467. if (filep != NULL && filep->fp != NULL) {
  1468. fclose(filep->fp);
  1469. }
  1470. }
  1471. static void
  1472. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1473. {
  1474. for (; *src != '\0' && n > 1; n--) {
  1475. *dst++ = *src++;
  1476. }
  1477. *dst = '\0';
  1478. }
  1479. static int
  1480. lowercase(const char *s)
  1481. {
  1482. return tolower(*(const unsigned char *)s);
  1483. }
  1484. int
  1485. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1486. {
  1487. int diff = 0;
  1488. if (len > 0) {
  1489. do {
  1490. diff = lowercase(s1++) - lowercase(s2++);
  1491. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1492. }
  1493. return diff;
  1494. }
  1495. int
  1496. mg_strcasecmp(const char *s1, const char *s2)
  1497. {
  1498. int diff;
  1499. do {
  1500. diff = lowercase(s1++) - lowercase(s2++);
  1501. } while (diff == 0 && s1[-1] != '\0');
  1502. return diff;
  1503. }
  1504. static char *
  1505. mg_strndup(const char *ptr, size_t len)
  1506. {
  1507. char *p;
  1508. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1509. mg_strlcpy(p, ptr, len + 1);
  1510. }
  1511. return p;
  1512. }
  1513. static char *
  1514. mg_strdup(const char *str)
  1515. {
  1516. return mg_strndup(str, strlen(str));
  1517. }
  1518. static const char *
  1519. mg_strcasestr(const char *big_str, const char *small_str)
  1520. {
  1521. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1522. if (big_len >= small_len) {
  1523. for (i = 0; i <= (big_len - small_len); i++) {
  1524. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1525. return big_str + i;
  1526. }
  1527. }
  1528. }
  1529. return NULL;
  1530. }
  1531. /* Return null terminated string of given maximum length.
  1532. * Report errors if length is exceeded. */
  1533. static void
  1534. mg_vsnprintf(const struct mg_connection *conn,
  1535. int *truncated,
  1536. char *buf,
  1537. size_t buflen,
  1538. const char *fmt,
  1539. va_list ap)
  1540. {
  1541. int n, ok;
  1542. if (buflen == 0) {
  1543. return;
  1544. }
  1545. #ifdef __clang__
  1546. #pragma clang diagnostic push
  1547. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1548. /* Using fmt as a non-literal is intended here, since it is mostly called
  1549. * indirectly by mg_snprintf */
  1550. #endif
  1551. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1552. ok = (n >= 0) && ((size_t)n < buflen);
  1553. #ifdef __clang__
  1554. #pragma clang diagnostic pop
  1555. #endif
  1556. if (ok) {
  1557. if (truncated) {
  1558. *truncated = 0;
  1559. }
  1560. } else {
  1561. if (truncated) {
  1562. *truncated = 1;
  1563. }
  1564. mg_cry(conn,
  1565. "truncating vsnprintf buffer: [%.*s]",
  1566. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1567. buf);
  1568. n = (int)buflen - 1;
  1569. }
  1570. buf[n] = '\0';
  1571. }
  1572. static void
  1573. mg_snprintf(const struct mg_connection *conn,
  1574. int *truncated,
  1575. char *buf,
  1576. size_t buflen,
  1577. const char *fmt,
  1578. ...)
  1579. {
  1580. va_list ap;
  1581. va_start(ap, fmt);
  1582. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1583. va_end(ap);
  1584. }
  1585. static int
  1586. get_option_index(const char *name)
  1587. {
  1588. int i;
  1589. for (i = 0; config_options[i].name != NULL; i++) {
  1590. if (strcmp(config_options[i].name, name) == 0) {
  1591. return i;
  1592. }
  1593. }
  1594. return -1;
  1595. }
  1596. const char *
  1597. mg_get_option(const struct mg_context *ctx, const char *name)
  1598. {
  1599. int i;
  1600. if ((i = get_option_index(name)) == -1) {
  1601. return NULL;
  1602. } else if (!ctx || ctx->config[i] == NULL) {
  1603. return "";
  1604. } else {
  1605. return ctx->config[i];
  1606. }
  1607. }
  1608. struct mg_context *
  1609. mg_get_context(const struct mg_connection *conn)
  1610. {
  1611. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1612. }
  1613. void *
  1614. mg_get_user_data(const struct mg_context *ctx)
  1615. {
  1616. return (ctx == NULL) ? NULL : ctx->user_data;
  1617. }
  1618. void
  1619. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1620. {
  1621. if (conn != NULL) {
  1622. conn->request_info.conn_data = data;
  1623. }
  1624. }
  1625. void *
  1626. mg_get_user_connection_data(const struct mg_connection *conn)
  1627. {
  1628. if (conn != NULL) {
  1629. return conn->request_info.conn_data;
  1630. }
  1631. return NULL;
  1632. }
  1633. size_t
  1634. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1635. {
  1636. size_t i;
  1637. if (!ctx) {
  1638. return 0;
  1639. }
  1640. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1641. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1642. ports[i] = ctx->listening_ports[i];
  1643. }
  1644. return i;
  1645. }
  1646. int
  1647. mg_get_server_ports(const struct mg_context *ctx,
  1648. int size,
  1649. struct mg_server_ports *ports)
  1650. {
  1651. int i, cnt = 0;
  1652. if (size <= 0) {
  1653. return -1;
  1654. }
  1655. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1656. if (!ctx) {
  1657. return -1;
  1658. }
  1659. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1660. return -1;
  1661. }
  1662. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1663. ports[cnt].port = ctx->listening_ports[i];
  1664. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1665. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1666. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1667. /* IPv4 */
  1668. ports[cnt].protocol = 1;
  1669. cnt++;
  1670. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1671. /* IPv6 */
  1672. ports[cnt].protocol = 3;
  1673. cnt++;
  1674. }
  1675. }
  1676. return cnt;
  1677. }
  1678. static void
  1679. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1680. {
  1681. buf[0] = '\0';
  1682. if (!usa) {
  1683. return;
  1684. }
  1685. if (usa->sa.sa_family == AF_INET) {
  1686. getnameinfo(&usa->sa,
  1687. sizeof(usa->sin),
  1688. buf,
  1689. (unsigned)len,
  1690. NULL,
  1691. 0,
  1692. NI_NUMERICHOST);
  1693. }
  1694. #if defined(USE_IPV6)
  1695. else if (usa->sa.sa_family == AF_INET6) {
  1696. getnameinfo(&usa->sa,
  1697. sizeof(usa->sin6),
  1698. buf,
  1699. (unsigned)len,
  1700. NULL,
  1701. 0,
  1702. NI_NUMERICHOST);
  1703. }
  1704. #endif
  1705. }
  1706. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1707. * included in all responses other than 100, 101, 5xx. */
  1708. static void
  1709. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1710. {
  1711. struct tm *tm;
  1712. tm = ((t != NULL) ? gmtime(t) : NULL);
  1713. if (tm != NULL) {
  1714. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1715. } else {
  1716. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1717. buf[buf_len - 1] = '\0';
  1718. }
  1719. }
  1720. /* difftime for struct timespec. Return value is in seconds. */
  1721. static double
  1722. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1723. {
  1724. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1725. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1726. }
  1727. /* Print error message to the opened error log stream. */
  1728. void
  1729. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1730. {
  1731. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1732. va_list ap;
  1733. struct file fi;
  1734. time_t timestamp;
  1735. va_start(ap, fmt);
  1736. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1737. va_end(ap);
  1738. buf[sizeof(buf) - 1] = 0;
  1739. if (!conn) {
  1740. puts(buf);
  1741. return;
  1742. }
  1743. /* Do not lock when getting the callback value, here and below.
  1744. * I suppose this is fine, since function cannot disappear in the
  1745. * same way string option can. */
  1746. if ((conn->ctx->callbacks.log_message == NULL)
  1747. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1748. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1749. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1750. == 0) {
  1751. fi.fp = NULL;
  1752. }
  1753. } else {
  1754. fi.fp = NULL;
  1755. }
  1756. if (fi.fp != NULL) {
  1757. flockfile(fi.fp);
  1758. timestamp = time(NULL);
  1759. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1760. fprintf(fi.fp,
  1761. "[%010lu] [error] [client %s] ",
  1762. (unsigned long)timestamp,
  1763. src_addr);
  1764. if (conn->request_info.request_method != NULL) {
  1765. fprintf(fi.fp,
  1766. "%s %s: ",
  1767. conn->request_info.request_method,
  1768. conn->request_info.request_uri);
  1769. }
  1770. fprintf(fi.fp, "%s", buf);
  1771. fputc('\n', fi.fp);
  1772. fflush(fi.fp);
  1773. funlockfile(fi.fp);
  1774. mg_fclose(&fi);
  1775. }
  1776. }
  1777. }
  1778. /* Return fake connection structure. Used for logging, if connection
  1779. * is not applicable at the moment of logging. */
  1780. static struct mg_connection *
  1781. fc(struct mg_context *ctx)
  1782. {
  1783. static struct mg_connection fake_connection;
  1784. fake_connection.ctx = ctx;
  1785. return &fake_connection;
  1786. }
  1787. const char *
  1788. mg_version(void)
  1789. {
  1790. return CIVETWEB_VERSION;
  1791. }
  1792. const struct mg_request_info *
  1793. mg_get_request_info(const struct mg_connection *conn)
  1794. {
  1795. if (!conn) {
  1796. return NULL;
  1797. }
  1798. return &conn->request_info;
  1799. }
  1800. /* Skip the characters until one of the delimiters characters found.
  1801. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1802. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1803. * Delimiters can be quoted with quotechar. */
  1804. static char *
  1805. skip_quoted(char **buf,
  1806. const char *delimiters,
  1807. const char *whitespace,
  1808. char quotechar)
  1809. {
  1810. char *p, *begin_word, *end_word, *end_whitespace;
  1811. begin_word = *buf;
  1812. end_word = begin_word + strcspn(begin_word, delimiters);
  1813. /* Check for quotechar */
  1814. if (end_word > begin_word) {
  1815. p = end_word - 1;
  1816. while (*p == quotechar) {
  1817. /* While the delimiter is quoted, look for the next delimiter. */
  1818. /* This happens, e.g., in calls from parse_auth_header,
  1819. * if the user name contains a " character. */
  1820. /* If there is anything beyond end_word, copy it. */
  1821. if (*end_word != '\0') {
  1822. size_t end_off = strcspn(end_word + 1, delimiters);
  1823. memmove(p, end_word, end_off + 1);
  1824. p += end_off; /* p must correspond to end_word - 1 */
  1825. end_word += end_off + 1;
  1826. } else {
  1827. *p = '\0';
  1828. break;
  1829. }
  1830. }
  1831. for (p++; p < end_word; p++) {
  1832. *p = '\0';
  1833. }
  1834. }
  1835. if (*end_word == '\0') {
  1836. *buf = end_word;
  1837. } else {
  1838. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1839. for (p = end_word; p < end_whitespace; p++) {
  1840. *p = '\0';
  1841. }
  1842. *buf = end_whitespace;
  1843. }
  1844. return begin_word;
  1845. }
  1846. /* Simplified version of skip_quoted without quote char
  1847. * and whitespace == delimiters */
  1848. static char *
  1849. skip(char **buf, const char *delimiters)
  1850. {
  1851. return skip_quoted(buf, delimiters, delimiters, 0);
  1852. }
  1853. /* Return HTTP header value, or NULL if not found. */
  1854. static const char *
  1855. get_header(const struct mg_request_info *ri, const char *name)
  1856. {
  1857. int i;
  1858. if (ri) {
  1859. for (i = 0; i < ri->num_headers; i++) {
  1860. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1861. return ri->http_headers[i].value;
  1862. }
  1863. }
  1864. }
  1865. return NULL;
  1866. }
  1867. const char *
  1868. mg_get_header(const struct mg_connection *conn, const char *name)
  1869. {
  1870. if (!conn) {
  1871. return NULL;
  1872. }
  1873. return get_header(&conn->request_info, name);
  1874. }
  1875. /* A helper function for traversing a comma separated list of values.
  1876. * It returns a list pointer shifted to the next value, or NULL if the end
  1877. * of the list found.
  1878. * Value is stored in val vector. If value has form "x=y", then eq_val
  1879. * vector is initialized to point to the "y" part, and val vector length
  1880. * is adjusted to point only to "x". */
  1881. static const char *
  1882. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1883. {
  1884. int end;
  1885. reparse:
  1886. if (val == NULL || list == NULL || *list == '\0') {
  1887. /* End of the list */
  1888. list = NULL;
  1889. } else {
  1890. /* Skip over leading LWS */
  1891. while (*list == ' ' || *list == '\t')
  1892. list++;
  1893. val->ptr = list;
  1894. if ((list = strchr(val->ptr, ',')) != NULL) {
  1895. /* Comma found. Store length and shift the list ptr */
  1896. val->len = ((size_t)(list - val->ptr));
  1897. list++;
  1898. } else {
  1899. /* This value is the last one */
  1900. list = val->ptr + strlen(val->ptr);
  1901. val->len = ((size_t)(list - val->ptr));
  1902. }
  1903. /* Adjust length for trailing LWS */
  1904. end = (int)val->len - 1;
  1905. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1906. end--;
  1907. val->len = (size_t)(end + 1);
  1908. if (val->len == 0) {
  1909. /* Ignore any empty entries. */
  1910. goto reparse;
  1911. }
  1912. if (eq_val != NULL) {
  1913. /* Value has form "x=y", adjust pointers and lengths
  1914. * so that val points to "x", and eq_val points to "y". */
  1915. eq_val->len = 0;
  1916. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1917. if (eq_val->ptr != NULL) {
  1918. eq_val->ptr++; /* Skip over '=' character */
  1919. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1920. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1921. }
  1922. }
  1923. }
  1924. return list;
  1925. }
  1926. /* A helper function for checking if a comma separated list of values contains
  1927. * the given option (case insensitvely).
  1928. * 'header' can be NULL, in which case false is returned. */
  1929. static int
  1930. header_has_option(const char *header, const char *option)
  1931. {
  1932. struct vec opt_vec;
  1933. struct vec eq_vec;
  1934. assert(option != NULL);
  1935. assert(option[0] != '\0');
  1936. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1937. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1938. return 1;
  1939. }
  1940. return 0;
  1941. }
  1942. /* Perform case-insensitive match of string against pattern */
  1943. static int
  1944. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1945. {
  1946. const char *or_str;
  1947. size_t i;
  1948. int j, len, res;
  1949. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1950. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1951. return res > 0 ? res : match_prefix(or_str + 1,
  1952. (size_t)((pattern + pattern_len)
  1953. - (or_str + 1)),
  1954. str);
  1955. }
  1956. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1957. if (pattern[i] == '?' && str[j] != '\0') {
  1958. continue;
  1959. } else if (pattern[i] == '$') {
  1960. return str[j] == '\0' ? j : -1;
  1961. } else if (pattern[i] == '*') {
  1962. i++;
  1963. if (pattern[i] == '*') {
  1964. i++;
  1965. len = (int)strlen(str + j);
  1966. } else {
  1967. len = (int)strcspn(str + j, "/");
  1968. }
  1969. if (i == pattern_len) {
  1970. return j + len;
  1971. }
  1972. do {
  1973. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1974. } while (res == -1 && len-- > 0);
  1975. return res == -1 ? -1 : j + res + len;
  1976. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1977. return -1;
  1978. }
  1979. }
  1980. return j;
  1981. }
  1982. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1983. * This function must tolerate situations when connection info is not
  1984. * set up, for example if request parsing failed. */
  1985. static int
  1986. should_keep_alive(const struct mg_connection *conn)
  1987. {
  1988. if (conn != NULL) {
  1989. const char *http_version = conn->request_info.http_version;
  1990. const char *header = mg_get_header(conn, "Connection");
  1991. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1992. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1993. || (header != NULL && !header_has_option(header, "keep-alive"))
  1994. || (header == NULL && http_version
  1995. && 0 != strcmp(http_version, "1.1"))) {
  1996. return 0;
  1997. }
  1998. return 1;
  1999. }
  2000. return 0;
  2001. }
  2002. static int
  2003. should_decode_url(const struct mg_connection *conn)
  2004. {
  2005. if (!conn || !conn->ctx) {
  2006. return 0;
  2007. }
  2008. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2009. }
  2010. static const char *
  2011. suggest_connection_header(const struct mg_connection *conn)
  2012. {
  2013. return should_keep_alive(conn) ? "keep-alive" : "close";
  2014. }
  2015. static int
  2016. send_no_cache_header(struct mg_connection *conn)
  2017. {
  2018. /* Send all current and obsolete cache opt-out directives. */
  2019. return mg_printf(conn,
  2020. "Cache-Control: no-cache, no-store, "
  2021. "must-revalidate, private, max-age=0\r\n"
  2022. "Pragma: no-cache\r\n"
  2023. "Expires: 0\r\n");
  2024. }
  2025. static int
  2026. send_static_cache_header(struct mg_connection *conn)
  2027. {
  2028. #if !defined(NO_CACHING)
  2029. /* Read the server config to check how long a file may be cached.
  2030. * The configuration is in seconds. */
  2031. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2032. if (max_age <= 0) {
  2033. /* 0 means "do not cache". All values <0 are reserved
  2034. * and may be used differently in the future. */
  2035. /* If a file should not be cached, do not only send
  2036. * max-age=0, but also pragmas and Expires headers. */
  2037. return send_no_cache_header(conn);
  2038. }
  2039. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2040. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2041. /* See also https://www.mnot.net/cache_docs/ */
  2042. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2043. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2044. * year to 31622400 seconds. For the moment, we just send whatever has
  2045. * been configured, still the behavior for >1 year should be considered
  2046. * as undefined. */
  2047. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2048. #else /* NO_CACHING */
  2049. return send_no_cache_header(conn);
  2050. #endif /* !NO_CACHING */
  2051. }
  2052. static void handle_file_based_request(struct mg_connection *conn,
  2053. const char *path,
  2054. struct file *filep);
  2055. static int
  2056. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2057. const char *
  2058. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2059. {
  2060. /* See IANA HTTP status code assignment:
  2061. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2062. */
  2063. switch (response_code) {
  2064. /* RFC2616 Section 10.1 - Informational 1xx */
  2065. case 100:
  2066. return "Continue"; /* RFC2616 Section 10.1.1 */
  2067. case 101:
  2068. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2069. case 102:
  2070. return "Processing"; /* RFC2518 Section 10.1 */
  2071. /* RFC2616 Section 10.2 - Successful 2xx */
  2072. case 200:
  2073. return "OK"; /* RFC2616 Section 10.2.1 */
  2074. case 201:
  2075. return "Created"; /* RFC2616 Section 10.2.2 */
  2076. case 202:
  2077. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2078. case 203:
  2079. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2080. case 204:
  2081. return "No Content"; /* RFC2616 Section 10.2.5 */
  2082. case 205:
  2083. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2084. case 206:
  2085. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2086. case 207:
  2087. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2088. case 208:
  2089. return "Already Reported"; /* RFC5842 Section 7.1 */
  2090. case 226:
  2091. return "IM used"; /* RFC3229 Section 10.4.1 */
  2092. /* RFC2616 Section 10.3 - Redirection 3xx */
  2093. case 300:
  2094. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2095. case 301:
  2096. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2097. case 302:
  2098. return "Found"; /* RFC2616 Section 10.3.3 */
  2099. case 303:
  2100. return "See Other"; /* RFC2616 Section 10.3.4 */
  2101. case 304:
  2102. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2103. case 305:
  2104. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2105. case 307:
  2106. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2107. case 308:
  2108. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2109. /* RFC2616 Section 10.4 - Client Error 4xx */
  2110. case 400:
  2111. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2112. case 401:
  2113. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2114. case 402:
  2115. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2116. case 403:
  2117. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2118. case 404:
  2119. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2120. case 405:
  2121. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2122. case 406:
  2123. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2124. case 407:
  2125. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2126. case 408:
  2127. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2128. case 409:
  2129. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2130. case 410:
  2131. return "Gone"; /* RFC2616 Section 10.4.11 */
  2132. case 411:
  2133. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2134. case 412:
  2135. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2136. case 413:
  2137. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2138. case 414:
  2139. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2140. case 415:
  2141. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2142. case 416:
  2143. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2144. case 417:
  2145. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2146. case 421:
  2147. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2148. case 422:
  2149. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2150. * Section 11.2 */
  2151. case 423:
  2152. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2153. case 424:
  2154. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2155. * Section 11.4 */
  2156. case 426:
  2157. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2158. case 428:
  2159. return "Precondition Required"; /* RFC 6585, Section 3 */
  2160. case 429:
  2161. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2162. case 431:
  2163. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2164. case 451:
  2165. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2166. * Section 3 */
  2167. /* RFC2616 Section 10.5 - Server Error 5xx */
  2168. case 500:
  2169. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2170. case 501:
  2171. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2172. case 502:
  2173. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2174. case 503:
  2175. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2176. case 504:
  2177. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2178. case 505:
  2179. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2180. case 506:
  2181. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2182. case 507:
  2183. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2184. * Section 11.5 */
  2185. case 508:
  2186. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2187. case 510:
  2188. return "Not Extended"; /* RFC 2774, Section 7 */
  2189. case 511:
  2190. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2191. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2192. * E.g., "de facto" standards due to common use, ... */
  2193. case 418:
  2194. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2195. case 419:
  2196. return "Authentication Timeout"; /* common use */
  2197. case 420:
  2198. return "Enhance Your Calm"; /* common use */
  2199. case 440:
  2200. return "Login Timeout"; /* common use */
  2201. case 509:
  2202. return "Bandwidth Limit Exceeded"; /* common use */
  2203. default:
  2204. /* This error code is unknown. This should not happen. */
  2205. if (conn) {
  2206. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2207. }
  2208. /* Return at least a category according to RFC 2616 Section 10. */
  2209. if (response_code >= 100 && response_code < 200) {
  2210. /* Unknown informational status code */
  2211. return "Information";
  2212. }
  2213. if (response_code >= 200 && response_code < 300) {
  2214. /* Unknown success code */
  2215. return "Success";
  2216. }
  2217. if (response_code >= 300 && response_code < 400) {
  2218. /* Unknown redirection code */
  2219. return "Redirection";
  2220. }
  2221. if (response_code >= 400 && response_code < 500) {
  2222. /* Unknown request error code */
  2223. return "Client Error";
  2224. }
  2225. if (response_code >= 500 && response_code < 600) {
  2226. /* Unknown server error code */
  2227. return "Server Error";
  2228. }
  2229. /* Response code not even within reasonable range */
  2230. return "";
  2231. }
  2232. }
  2233. static void send_http_error(struct mg_connection *,
  2234. int,
  2235. PRINTF_FORMAT_STRING(const char *fmt),
  2236. ...) PRINTF_ARGS(3, 4);
  2237. static void
  2238. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2239. {
  2240. char buf[MG_BUF_LEN];
  2241. va_list ap;
  2242. int len, i, page_handler_found, scope, truncated;
  2243. char date[64];
  2244. time_t curtime = time(NULL);
  2245. const char *error_handler = NULL;
  2246. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2247. const char *error_page_file_ext, *tstr;
  2248. const char *status_text = mg_get_response_code_text(conn, status);
  2249. if (conn == NULL) {
  2250. return;
  2251. }
  2252. conn->status_code = status;
  2253. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2254. || conn->ctx->callbacks.http_error(conn, status)) {
  2255. if (!conn->in_error_handler) {
  2256. /* Send user defined error pages, if defined */
  2257. error_handler = conn->ctx->config[ERROR_PAGES];
  2258. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2259. page_handler_found = 0;
  2260. if (error_handler != NULL) {
  2261. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2262. switch (scope) {
  2263. case 1: /* Handler for specific error, e.g. 404 error */
  2264. mg_snprintf(conn,
  2265. &truncated,
  2266. buf,
  2267. sizeof(buf) - 32,
  2268. "%serror%03u.",
  2269. error_handler,
  2270. status);
  2271. break;
  2272. case 2: /* Handler for error group, e.g., 5xx error handler
  2273. * for all server errors (500-599) */
  2274. mg_snprintf(conn,
  2275. &truncated,
  2276. buf,
  2277. sizeof(buf) - 32,
  2278. "%serror%01uxx.",
  2279. error_handler,
  2280. status / 100);
  2281. break;
  2282. default: /* Handler for all errors */
  2283. mg_snprintf(conn,
  2284. &truncated,
  2285. buf,
  2286. sizeof(buf) - 32,
  2287. "%serror.",
  2288. error_handler);
  2289. break;
  2290. }
  2291. /* String truncation in buf may only occur if error_handler
  2292. * is too long. This string is from the config, not from a
  2293. * client. */
  2294. (void)truncated;
  2295. len = (int)strlen(buf);
  2296. tstr = strchr(error_page_file_ext, '.');
  2297. while (tstr) {
  2298. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2299. i++)
  2300. buf[len + i - 1] = tstr[i];
  2301. buf[len + i - 1] = 0;
  2302. if (mg_stat(conn, buf, &error_page_file)) {
  2303. page_handler_found = 1;
  2304. break;
  2305. }
  2306. tstr = strchr(tstr + i, '.');
  2307. }
  2308. }
  2309. }
  2310. if (page_handler_found) {
  2311. conn->in_error_handler = 1;
  2312. handle_file_based_request(conn, buf, &error_page_file);
  2313. conn->in_error_handler = 0;
  2314. return;
  2315. }
  2316. }
  2317. /* No custom error page. Send default error page. */
  2318. gmt_time_string(date, sizeof(date), &curtime);
  2319. conn->must_close = 1;
  2320. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2321. send_no_cache_header(conn);
  2322. mg_printf(conn,
  2323. "Date: %s\r\n"
  2324. "Connection: close\r\n\r\n",
  2325. date);
  2326. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2327. if (status > 199 && status != 204 && status != 304) {
  2328. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2329. if (fmt != NULL) {
  2330. va_start(ap, fmt);
  2331. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2332. va_end(ap);
  2333. mg_write(conn, buf, strlen(buf));
  2334. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2335. }
  2336. } else {
  2337. /* No body allowed. Close the connection. */
  2338. DEBUG_TRACE("Error %i", status);
  2339. }
  2340. }
  2341. }
  2342. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2343. /* Create substitutes for POSIX functions in Win32. */
  2344. #if defined(__MINGW32__)
  2345. /* Show no warning in case system functions are not used. */
  2346. #pragma GCC diagnostic push
  2347. #pragma GCC diagnostic ignored "-Wunused-function"
  2348. #endif
  2349. static int
  2350. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2351. {
  2352. (void)unused;
  2353. *mutex = CreateMutex(NULL, FALSE, NULL);
  2354. return *mutex == NULL ? -1 : 0;
  2355. }
  2356. static int
  2357. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2358. {
  2359. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2360. }
  2361. static int
  2362. pthread_mutex_lock(pthread_mutex_t *mutex)
  2363. {
  2364. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2365. }
  2366. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2367. static int
  2368. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2369. {
  2370. switch (WaitForSingleObject(*mutex, 0)) {
  2371. case WAIT_OBJECT_0:
  2372. return 0;
  2373. case WAIT_TIMEOUT:
  2374. return -2; /* EBUSY */
  2375. }
  2376. return -1;
  2377. }
  2378. #endif
  2379. static int
  2380. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2381. {
  2382. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2383. }
  2384. #ifndef WIN_PTHREADS_TIME_H
  2385. static int
  2386. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2387. {
  2388. FILETIME ft;
  2389. ULARGE_INTEGER li;
  2390. BOOL ok = FALSE;
  2391. double d;
  2392. static double perfcnt_per_sec = 0.0;
  2393. if (tp) {
  2394. memset(tp, 0, sizeof(*tp));
  2395. if (clk_id == CLOCK_REALTIME) {
  2396. GetSystemTimeAsFileTime(&ft);
  2397. li.LowPart = ft.dwLowDateTime;
  2398. li.HighPart = ft.dwHighDateTime;
  2399. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2400. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2401. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2402. ok = TRUE;
  2403. } else if (clk_id == CLOCK_MONOTONIC) {
  2404. if (perfcnt_per_sec == 0.0) {
  2405. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2406. perfcnt_per_sec = 1.0 / li.QuadPart;
  2407. }
  2408. if (perfcnt_per_sec != 0.0) {
  2409. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2410. d = li.QuadPart * perfcnt_per_sec;
  2411. tp->tv_sec = (time_t)d;
  2412. d -= tp->tv_sec;
  2413. tp->tv_nsec = (long)(d * 1.0E9);
  2414. ok = TRUE;
  2415. }
  2416. }
  2417. }
  2418. return ok ? 0 : -1;
  2419. }
  2420. #endif
  2421. static int
  2422. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2423. {
  2424. (void)unused;
  2425. InitializeCriticalSection(&cv->threadIdSec);
  2426. cv->waitingthreadcount = 0;
  2427. cv->waitingthreadhdls =
  2428. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2429. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2430. }
  2431. static int
  2432. pthread_cond_timedwait(pthread_cond_t *cv,
  2433. pthread_mutex_t *mutex,
  2434. const struct timespec *abstime)
  2435. {
  2436. struct mg_workerTLS *tls =
  2437. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2438. int ok;
  2439. struct timespec tsnow;
  2440. int64_t nsnow, nswaitabs, nswaitrel;
  2441. DWORD mswaitrel;
  2442. EnterCriticalSection(&cv->threadIdSec);
  2443. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2444. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2445. tls->pthread_cond_helper_mutex;
  2446. cv->waitingthreadcount++;
  2447. LeaveCriticalSection(&cv->threadIdSec);
  2448. if (abstime) {
  2449. clock_gettime(CLOCK_REALTIME, &tsnow);
  2450. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2451. nswaitabs =
  2452. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2453. nswaitrel = nswaitabs - nsnow;
  2454. if (nswaitrel < 0) {
  2455. nswaitrel = 0;
  2456. }
  2457. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2458. } else {
  2459. mswaitrel = INFINITE;
  2460. }
  2461. pthread_mutex_unlock(mutex);
  2462. ok = (WAIT_OBJECT_0
  2463. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2464. pthread_mutex_lock(mutex);
  2465. return ok ? 0 : -1;
  2466. }
  2467. static int
  2468. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2469. {
  2470. return pthread_cond_timedwait(cv, mutex, NULL);
  2471. }
  2472. static int
  2473. pthread_cond_signal(pthread_cond_t *cv)
  2474. {
  2475. int i;
  2476. HANDLE wkup = NULL;
  2477. BOOL ok = FALSE;
  2478. EnterCriticalSection(&cv->threadIdSec);
  2479. if (cv->waitingthreadcount) {
  2480. wkup = cv->waitingthreadhdls[0];
  2481. ok = SetEvent(wkup);
  2482. for (i = 1; i < cv->waitingthreadcount; i++) {
  2483. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2484. }
  2485. cv->waitingthreadcount--;
  2486. assert(ok);
  2487. }
  2488. LeaveCriticalSection(&cv->threadIdSec);
  2489. return ok ? 0 : 1;
  2490. }
  2491. static int
  2492. pthread_cond_broadcast(pthread_cond_t *cv)
  2493. {
  2494. EnterCriticalSection(&cv->threadIdSec);
  2495. while (cv->waitingthreadcount) {
  2496. pthread_cond_signal(cv);
  2497. }
  2498. LeaveCriticalSection(&cv->threadIdSec);
  2499. return 0;
  2500. }
  2501. static int
  2502. pthread_cond_destroy(pthread_cond_t *cv)
  2503. {
  2504. EnterCriticalSection(&cv->threadIdSec);
  2505. assert(cv->waitingthreadcount == 0);
  2506. mg_free(cv->waitingthreadhdls);
  2507. cv->waitingthreadhdls = 0;
  2508. LeaveCriticalSection(&cv->threadIdSec);
  2509. DeleteCriticalSection(&cv->threadIdSec);
  2510. return 0;
  2511. }
  2512. #if defined(__MINGW32__)
  2513. /* Enable unused function warning again */
  2514. #pragma GCC diagnostic pop
  2515. #endif
  2516. /* For Windows, change all slashes to backslashes in path names. */
  2517. static void
  2518. change_slashes_to_backslashes(char *path)
  2519. {
  2520. int i;
  2521. for (i = 0; path[i] != '\0'; i++) {
  2522. if (path[i] == '/') {
  2523. path[i] = '\\';
  2524. }
  2525. /* remove double backslash (check i > 0 to preserve UNC paths,
  2526. * like \\server\file.txt) */
  2527. if ((path[i] == '\\') && (i > 0)) {
  2528. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2529. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2530. }
  2531. }
  2532. }
  2533. }
  2534. static int
  2535. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2536. {
  2537. int diff;
  2538. do {
  2539. diff = tolower(*s1) - tolower(*s2);
  2540. s1++;
  2541. s2++;
  2542. } while (diff == 0 && s1[-1] != '\0');
  2543. return diff;
  2544. }
  2545. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2546. * wbuf and wbuf_len is a target buffer and its length. */
  2547. static void
  2548. path_to_unicode(const struct mg_connection *conn,
  2549. const char *path,
  2550. wchar_t *wbuf,
  2551. size_t wbuf_len)
  2552. {
  2553. char buf[PATH_MAX], buf2[PATH_MAX];
  2554. wchar_t wbuf2[MAX_PATH + 1];
  2555. DWORD long_len, err;
  2556. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2557. mg_strlcpy(buf, path, sizeof(buf));
  2558. change_slashes_to_backslashes(buf);
  2559. /* Convert to Unicode and back. If doubly-converted string does not
  2560. * match the original, something is fishy, reject. */
  2561. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2562. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2563. WideCharToMultiByte(
  2564. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2565. if (strcmp(buf, buf2) != 0) {
  2566. wbuf[0] = L'\0';
  2567. }
  2568. /* TODO: Add a configuration to switch between case sensitive and
  2569. * case insensitive URIs for Windows server. */
  2570. /*
  2571. if (conn) {
  2572. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2573. fcompare = wcscmp;
  2574. }
  2575. }
  2576. */
  2577. (void)conn; /* conn is currently unused */
  2578. #if !defined(_WIN32_WCE)
  2579. /* Only accept a full file path, not a Windows short (8.3) path. */
  2580. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2581. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2582. if (long_len == 0) {
  2583. err = GetLastError();
  2584. if (err == ERROR_FILE_NOT_FOUND) {
  2585. /* File does not exist. This is not always a problem here. */
  2586. return;
  2587. }
  2588. }
  2589. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2590. /* Short name is used. */
  2591. wbuf[0] = L'\0';
  2592. }
  2593. #else
  2594. (void)long_len;
  2595. (void)wbuf2;
  2596. (void)err;
  2597. if (strchr(path, '~')) {
  2598. wbuf[0] = L'\0';
  2599. }
  2600. #endif
  2601. }
  2602. /* Windows happily opens files with some garbage at the end of file name.
  2603. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2604. * "a.cgi", despite one would expect an error back.
  2605. * This function returns non-0 if path ends with some garbage. */
  2606. static int
  2607. path_cannot_disclose_cgi(const char *path)
  2608. {
  2609. static const char *allowed_last_characters = "_-";
  2610. int last = path[strlen(path) - 1];
  2611. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2612. }
  2613. static int
  2614. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2615. {
  2616. wchar_t wbuf[PATH_MAX];
  2617. WIN32_FILE_ATTRIBUTE_DATA info;
  2618. time_t creation_time;
  2619. if (!filep) {
  2620. return 0;
  2621. }
  2622. memset(filep, 0, sizeof(*filep));
  2623. if (conn && is_file_in_memory(conn, path, filep)) {
  2624. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2625. * memset */
  2626. filep->last_modified = time(NULL);
  2627. /* last_modified = now ... assumes the file may change during runtime,
  2628. * so every mg_fopen call may return different data */
  2629. /* last_modified = conn->ctx.start_time;
  2630. * May be used it the data does not change during runtime. This allows
  2631. * browser caching. Since we do not know, we have to assume the file
  2632. * in memory may change. */
  2633. return 1;
  2634. }
  2635. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2636. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2637. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2638. filep->last_modified =
  2639. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2640. info.ftLastWriteTime.dwHighDateTime);
  2641. /* On Windows, the file creation time can be higher than the
  2642. * modification time, e.g. when a file is copied.
  2643. * Since the Last-Modified timestamp is used for caching
  2644. * it should be based on the most recent timestamp. */
  2645. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2646. info.ftCreationTime.dwHighDateTime);
  2647. if (creation_time > filep->last_modified) {
  2648. filep->last_modified = creation_time;
  2649. }
  2650. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2651. /* If file name is fishy, reset the file structure and return
  2652. * error.
  2653. * Note it is important to reset, not just return the error, cause
  2654. * functions like is_file_opened() check the struct. */
  2655. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2656. memset(filep, 0, sizeof(*filep));
  2657. return 0;
  2658. }
  2659. return 1;
  2660. }
  2661. return 0;
  2662. }
  2663. static int
  2664. mg_remove(const struct mg_connection *conn, const char *path)
  2665. {
  2666. wchar_t wbuf[PATH_MAX];
  2667. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2668. return DeleteFileW(wbuf) ? 0 : -1;
  2669. }
  2670. static int
  2671. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2672. {
  2673. wchar_t wbuf[PATH_MAX];
  2674. (void)mode;
  2675. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2676. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2677. }
  2678. /* Create substitutes for POSIX functions in Win32. */
  2679. #if defined(__MINGW32__)
  2680. /* Show no warning in case system functions are not used. */
  2681. #pragma GCC diagnostic push
  2682. #pragma GCC diagnostic ignored "-Wunused-function"
  2683. #endif
  2684. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2685. static DIR *
  2686. mg_opendir(const struct mg_connection *conn, const char *name)
  2687. {
  2688. DIR *dir = NULL;
  2689. wchar_t wpath[PATH_MAX];
  2690. DWORD attrs;
  2691. if (name == NULL) {
  2692. SetLastError(ERROR_BAD_ARGUMENTS);
  2693. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2694. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2695. } else {
  2696. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2697. attrs = GetFileAttributesW(wpath);
  2698. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2699. == FILE_ATTRIBUTE_DIRECTORY)) {
  2700. (void)wcscat(wpath, L"\\*");
  2701. dir->handle = FindFirstFileW(wpath, &dir->info);
  2702. dir->result.d_name[0] = '\0';
  2703. } else {
  2704. mg_free(dir);
  2705. dir = NULL;
  2706. }
  2707. }
  2708. return dir;
  2709. }
  2710. static int
  2711. mg_closedir(DIR *dir)
  2712. {
  2713. int result = 0;
  2714. if (dir != NULL) {
  2715. if (dir->handle != INVALID_HANDLE_VALUE)
  2716. result = FindClose(dir->handle) ? 0 : -1;
  2717. mg_free(dir);
  2718. } else {
  2719. result = -1;
  2720. SetLastError(ERROR_BAD_ARGUMENTS);
  2721. }
  2722. return result;
  2723. }
  2724. static struct dirent *
  2725. mg_readdir(DIR *dir)
  2726. {
  2727. struct dirent *result = 0;
  2728. if (dir) {
  2729. if (dir->handle != INVALID_HANDLE_VALUE) {
  2730. result = &dir->result;
  2731. (void)WideCharToMultiByte(CP_UTF8,
  2732. 0,
  2733. dir->info.cFileName,
  2734. -1,
  2735. result->d_name,
  2736. sizeof(result->d_name),
  2737. NULL,
  2738. NULL);
  2739. if (!FindNextFileW(dir->handle, &dir->info)) {
  2740. (void)FindClose(dir->handle);
  2741. dir->handle = INVALID_HANDLE_VALUE;
  2742. }
  2743. } else {
  2744. SetLastError(ERROR_FILE_NOT_FOUND);
  2745. }
  2746. } else {
  2747. SetLastError(ERROR_BAD_ARGUMENTS);
  2748. }
  2749. return result;
  2750. }
  2751. #ifndef HAVE_POLL
  2752. static int
  2753. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2754. {
  2755. struct timeval tv;
  2756. fd_set set;
  2757. unsigned int i;
  2758. int result;
  2759. SOCKET maxfd = 0;
  2760. memset(&tv, 0, sizeof(tv));
  2761. tv.tv_sec = milliseconds / 1000;
  2762. tv.tv_usec = (milliseconds % 1000) * 1000;
  2763. FD_ZERO(&set);
  2764. for (i = 0; i < n; i++) {
  2765. FD_SET((SOCKET)pfd[i].fd, &set);
  2766. pfd[i].revents = 0;
  2767. if (pfd[i].fd > maxfd) {
  2768. maxfd = pfd[i].fd;
  2769. }
  2770. }
  2771. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2772. for (i = 0; i < n; i++) {
  2773. if (FD_ISSET(pfd[i].fd, &set)) {
  2774. pfd[i].revents = POLLIN;
  2775. }
  2776. }
  2777. }
  2778. return result;
  2779. }
  2780. #endif /* HAVE_POLL */
  2781. #if defined(__MINGW32__)
  2782. /* Enable unused function warning again */
  2783. #pragma GCC diagnostic pop
  2784. #endif
  2785. static void
  2786. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2787. {
  2788. (void)conn; /* Unused. */
  2789. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2790. }
  2791. int
  2792. mg_start_thread(mg_thread_func_t f, void *p)
  2793. {
  2794. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2795. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2796. */
  2797. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2798. == ((uintptr_t)(-1L)))
  2799. ? -1
  2800. : 0);
  2801. #else
  2802. return (
  2803. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2804. ? -1
  2805. : 0);
  2806. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2807. }
  2808. /* Start a thread storing the thread context. */
  2809. static int
  2810. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2811. void *p,
  2812. pthread_t *threadidptr)
  2813. {
  2814. uintptr_t uip;
  2815. HANDLE threadhandle;
  2816. int result = -1;
  2817. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2818. threadhandle = (HANDLE)uip;
  2819. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2820. *threadidptr = threadhandle;
  2821. result = 0;
  2822. }
  2823. return result;
  2824. }
  2825. /* Wait for a thread to finish. */
  2826. static int
  2827. mg_join_thread(pthread_t threadid)
  2828. {
  2829. int result;
  2830. DWORD dwevent;
  2831. result = -1;
  2832. dwevent = WaitForSingleObject(threadid, INFINITE);
  2833. if (dwevent == WAIT_FAILED) {
  2834. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2835. } else {
  2836. if (dwevent == WAIT_OBJECT_0) {
  2837. CloseHandle(threadid);
  2838. result = 0;
  2839. }
  2840. }
  2841. return result;
  2842. }
  2843. #if !defined(NO_SSL_DL)
  2844. /* Create substitutes for POSIX functions in Win32. */
  2845. #if defined(__MINGW32__)
  2846. /* Show no warning in case system functions are not used. */
  2847. #pragma GCC diagnostic push
  2848. #pragma GCC diagnostic ignored "-Wunused-function"
  2849. #endif
  2850. static HANDLE
  2851. dlopen(const char *dll_name, int flags)
  2852. {
  2853. wchar_t wbuf[PATH_MAX];
  2854. (void)flags;
  2855. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2856. return LoadLibraryW(wbuf);
  2857. }
  2858. static int
  2859. dlclose(void *handle)
  2860. {
  2861. int result;
  2862. if (FreeLibrary((HMODULE)handle) != 0) {
  2863. result = 0;
  2864. } else {
  2865. result = -1;
  2866. }
  2867. return result;
  2868. }
  2869. #if defined(__MINGW32__)
  2870. /* Enable unused function warning again */
  2871. #pragma GCC diagnostic pop
  2872. #endif
  2873. #endif
  2874. #if !defined(NO_CGI)
  2875. #define SIGKILL (0)
  2876. static int
  2877. kill(pid_t pid, int sig_num)
  2878. {
  2879. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2880. (void)CloseHandle((HANDLE)pid);
  2881. return 0;
  2882. }
  2883. static void
  2884. trim_trailing_whitespaces(char *s)
  2885. {
  2886. char *e = s + strlen(s) - 1;
  2887. while (e > s && isspace(*(unsigned char *)e)) {
  2888. *e-- = '\0';
  2889. }
  2890. }
  2891. static pid_t
  2892. spawn_process(struct mg_connection *conn,
  2893. const char *prog,
  2894. char *envblk,
  2895. char *envp[],
  2896. int fdin[2],
  2897. int fdout[2],
  2898. int fderr[2],
  2899. const char *dir)
  2900. {
  2901. HANDLE me;
  2902. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2903. cmdline[PATH_MAX], buf[PATH_MAX];
  2904. int truncated;
  2905. struct file file = STRUCT_FILE_INITIALIZER;
  2906. STARTUPINFOA si;
  2907. PROCESS_INFORMATION pi = {0};
  2908. (void)envp;
  2909. memset(&si, 0, sizeof(si));
  2910. si.cb = sizeof(si);
  2911. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2912. si.wShowWindow = SW_HIDE;
  2913. me = GetCurrentProcess();
  2914. DuplicateHandle(me,
  2915. (HANDLE)_get_osfhandle(fdin[0]),
  2916. me,
  2917. &si.hStdInput,
  2918. 0,
  2919. TRUE,
  2920. DUPLICATE_SAME_ACCESS);
  2921. DuplicateHandle(me,
  2922. (HANDLE)_get_osfhandle(fdout[1]),
  2923. me,
  2924. &si.hStdOutput,
  2925. 0,
  2926. TRUE,
  2927. DUPLICATE_SAME_ACCESS);
  2928. DuplicateHandle(me,
  2929. (HANDLE)_get_osfhandle(fderr[1]),
  2930. me,
  2931. &si.hStdError,
  2932. 0,
  2933. TRUE,
  2934. DUPLICATE_SAME_ACCESS);
  2935. /* Mark handles that should not be inherited. See
  2936. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  2937. */
  2938. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  2939. HANDLE_FLAG_INHERIT,
  2940. 0);
  2941. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  2942. HANDLE_FLAG_INHERIT,
  2943. 0);
  2944. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  2945. HANDLE_FLAG_INHERIT,
  2946. 0);
  2947. /* If CGI file is a script, try to read the interpreter line */
  2948. interp = conn->ctx->config[CGI_INTERPRETER];
  2949. if (interp == NULL) {
  2950. buf[0] = buf[1] = '\0';
  2951. /* Read the first line of the script into the buffer */
  2952. mg_snprintf(
  2953. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2954. if (truncated) {
  2955. pi.hProcess = (pid_t)-1;
  2956. goto spawn_cleanup;
  2957. }
  2958. if (mg_fopen(conn, cmdline, "r", &file)) {
  2959. p = (char *)file.membuf;
  2960. mg_fgets(buf, sizeof(buf), &file, &p);
  2961. mg_fclose(&file);
  2962. buf[sizeof(buf) - 1] = '\0';
  2963. }
  2964. if (buf[0] == '#' && buf[1] == '!') {
  2965. trim_trailing_whitespaces(buf + 2);
  2966. } else {
  2967. buf[2] = '\0';
  2968. }
  2969. interp = buf + 2;
  2970. }
  2971. if (interp[0] != '\0') {
  2972. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2973. interp = full_interp;
  2974. }
  2975. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2976. if (interp[0] != '\0') {
  2977. mg_snprintf(conn,
  2978. &truncated,
  2979. cmdline,
  2980. sizeof(cmdline),
  2981. "\"%s\" \"%s\\%s\"",
  2982. interp,
  2983. full_dir,
  2984. prog);
  2985. } else {
  2986. mg_snprintf(conn,
  2987. &truncated,
  2988. cmdline,
  2989. sizeof(cmdline),
  2990. "\"%s\\%s\"",
  2991. full_dir,
  2992. prog);
  2993. }
  2994. if (truncated) {
  2995. pi.hProcess = (pid_t)-1;
  2996. goto spawn_cleanup;
  2997. }
  2998. DEBUG_TRACE("Running [%s]", cmdline);
  2999. if (CreateProcessA(NULL,
  3000. cmdline,
  3001. NULL,
  3002. NULL,
  3003. TRUE,
  3004. CREATE_NEW_PROCESS_GROUP,
  3005. envblk,
  3006. NULL,
  3007. &si,
  3008. &pi) == 0) {
  3009. mg_cry(
  3010. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3011. pi.hProcess = (pid_t)-1;
  3012. /* goto spawn_cleanup; */
  3013. }
  3014. spawn_cleanup:
  3015. (void)CloseHandle(si.hStdOutput);
  3016. (void)CloseHandle(si.hStdError);
  3017. (void)CloseHandle(si.hStdInput);
  3018. if (pi.hThread != NULL) {
  3019. (void)CloseHandle(pi.hThread);
  3020. }
  3021. return (pid_t)pi.hProcess;
  3022. }
  3023. #endif /* !NO_CGI */
  3024. static int
  3025. set_non_blocking_mode(SOCKET sock)
  3026. {
  3027. unsigned long on = 1;
  3028. return ioctlsocket(sock, (long)FIONBIO, &on);
  3029. }
  3030. #else
  3031. static int
  3032. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3033. {
  3034. struct stat st;
  3035. if (!filep) {
  3036. return 0;
  3037. }
  3038. memset(filep, 0, sizeof(*filep));
  3039. if (conn && is_file_in_memory(conn, path, filep)) {
  3040. return 1;
  3041. }
  3042. if (0 == stat(path, &st)) {
  3043. filep->size = (uint64_t)(st.st_size);
  3044. filep->last_modified = st.st_mtime;
  3045. filep->is_directory = S_ISDIR(st.st_mode);
  3046. return 1;
  3047. }
  3048. return 0;
  3049. }
  3050. static void
  3051. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3052. {
  3053. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3054. if (conn) {
  3055. mg_cry(conn,
  3056. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3057. __func__,
  3058. strerror(ERRNO));
  3059. }
  3060. }
  3061. }
  3062. int
  3063. mg_start_thread(mg_thread_func_t func, void *param)
  3064. {
  3065. pthread_t thread_id;
  3066. pthread_attr_t attr;
  3067. int result;
  3068. (void)pthread_attr_init(&attr);
  3069. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3070. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3071. /* Compile-time option to control stack size,
  3072. * e.g. -DUSE_STACK_SIZE=16384 */
  3073. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3074. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3075. result = pthread_create(&thread_id, &attr, func, param);
  3076. pthread_attr_destroy(&attr);
  3077. return result;
  3078. }
  3079. /* Start a thread storing the thread context. */
  3080. static int
  3081. mg_start_thread_with_id(mg_thread_func_t func,
  3082. void *param,
  3083. pthread_t *threadidptr)
  3084. {
  3085. pthread_t thread_id;
  3086. pthread_attr_t attr;
  3087. int result;
  3088. (void)pthread_attr_init(&attr);
  3089. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3090. /* Compile-time option to control stack size,
  3091. * e.g. -DUSE_STACK_SIZE=16384 */
  3092. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3093. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3094. result = pthread_create(&thread_id, &attr, func, param);
  3095. pthread_attr_destroy(&attr);
  3096. if ((result == 0) && (threadidptr != NULL)) {
  3097. *threadidptr = thread_id;
  3098. }
  3099. return result;
  3100. }
  3101. /* Wait for a thread to finish. */
  3102. static int
  3103. mg_join_thread(pthread_t threadid)
  3104. {
  3105. int result;
  3106. result = pthread_join(threadid, NULL);
  3107. return result;
  3108. }
  3109. #ifndef NO_CGI
  3110. static pid_t
  3111. spawn_process(struct mg_connection *conn,
  3112. const char *prog,
  3113. char *envblk,
  3114. char *envp[],
  3115. int fdin[2],
  3116. int fdout[2],
  3117. int fderr[2],
  3118. const char *dir)
  3119. {
  3120. pid_t pid;
  3121. const char *interp;
  3122. (void)envblk;
  3123. if (conn == NULL) {
  3124. return 0;
  3125. }
  3126. if ((pid = fork()) == -1) {
  3127. /* Parent */
  3128. send_http_error(conn,
  3129. 500,
  3130. "Error: Creating CGI process\nfork(): %s",
  3131. strerror(ERRNO));
  3132. } else if (pid == 0) {
  3133. /* Child */
  3134. if (chdir(dir) != 0) {
  3135. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3136. } else if (dup2(fdin[0], 0) == -1) {
  3137. mg_cry(conn,
  3138. "%s: dup2(%d, 0): %s",
  3139. __func__,
  3140. fdin[0],
  3141. strerror(ERRNO));
  3142. } else if (dup2(fdout[1], 1) == -1) {
  3143. mg_cry(conn,
  3144. "%s: dup2(%d, 1): %s",
  3145. __func__,
  3146. fdout[1],
  3147. strerror(ERRNO));
  3148. } else if (dup2(fderr[1], 2) == -1) {
  3149. mg_cry(conn,
  3150. "%s: dup2(%d, 2): %s",
  3151. __func__,
  3152. fderr[1],
  3153. strerror(ERRNO));
  3154. } else {
  3155. /* Keep stderr and stdout in two different pipes.
  3156. * Stdout will be sent back to the client,
  3157. * stderr should go into a server error log. */
  3158. (void)close(fdin[0]);
  3159. (void)close(fdout[1]);
  3160. (void)close(fderr[1]);
  3161. /* Close write end fdin and read end fdout and fderr */
  3162. (void)close(fdin[1]);
  3163. (void)close(fdout[0]);
  3164. (void)close(fderr[0]);
  3165. /* After exec, all signal handlers are restored to their default
  3166. * values, with one exception of SIGCHLD. According to
  3167. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3168. * leave unchanged after exec if it was set to be ignored. Restore
  3169. * it to default action. */
  3170. signal(SIGCHLD, SIG_DFL);
  3171. interp = conn->ctx->config[CGI_INTERPRETER];
  3172. if (interp == NULL) {
  3173. (void)execle(prog, prog, NULL, envp);
  3174. mg_cry(conn,
  3175. "%s: execle(%s): %s",
  3176. __func__,
  3177. prog,
  3178. strerror(ERRNO));
  3179. } else {
  3180. (void)execle(interp, interp, prog, NULL, envp);
  3181. mg_cry(conn,
  3182. "%s: execle(%s %s): %s",
  3183. __func__,
  3184. interp,
  3185. prog,
  3186. strerror(ERRNO));
  3187. }
  3188. }
  3189. exit(EXIT_FAILURE);
  3190. }
  3191. return pid;
  3192. }
  3193. #endif /* !NO_CGI */
  3194. static int
  3195. set_non_blocking_mode(SOCKET sock)
  3196. {
  3197. int flags;
  3198. flags = fcntl(sock, F_GETFL, 0);
  3199. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3200. return 0;
  3201. }
  3202. #endif /* _WIN32 */
  3203. /* End of initial operating system specific define block. */
  3204. /* Get a random number (independent of C rand function) */
  3205. static uint64_t
  3206. get_random(void)
  3207. {
  3208. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3209. static uint64_t lcg = 0; /* Linear congruential generator */
  3210. struct timespec now;
  3211. memset(&now, 0, sizeof(now));
  3212. clock_gettime(CLOCK_MONOTONIC, &now);
  3213. if (lfsr == 0) {
  3214. /* lfsr will be only 0 if has not been initialized,
  3215. * so this code is called only once. */
  3216. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3217. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3218. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3219. + (uint64_t)(ptrdiff_t)&now;
  3220. } else {
  3221. /* Get the next step of both random number generators. */
  3222. lfsr = (lfsr >> 1)
  3223. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3224. << 63);
  3225. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3226. }
  3227. /* Combining two pseudo-random number generators and a high resolution part
  3228. * of the current server time will make it hard (impossible?) to guess the
  3229. * next number. */
  3230. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3231. }
  3232. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3233. * descriptor. Return number of bytes written. */
  3234. static int
  3235. push(struct mg_context *ctx,
  3236. FILE *fp,
  3237. SOCKET sock,
  3238. SSL *ssl,
  3239. const char *buf,
  3240. int len,
  3241. double timeout)
  3242. {
  3243. struct timespec start, now;
  3244. int n, err;
  3245. #ifdef _WIN32
  3246. typedef int len_t;
  3247. #else
  3248. typedef size_t len_t;
  3249. #endif
  3250. if (timeout > 0) {
  3251. memset(&start, 0, sizeof(start));
  3252. memset(&now, 0, sizeof(now));
  3253. clock_gettime(CLOCK_MONOTONIC, &start);
  3254. }
  3255. if (ctx == NULL) {
  3256. return -1;
  3257. }
  3258. #ifdef NO_SSL
  3259. if (ssl) {
  3260. return -1;
  3261. }
  3262. #endif
  3263. do {
  3264. #ifndef NO_SSL
  3265. if (ssl != NULL) {
  3266. n = SSL_write(ssl, buf, len);
  3267. if (n <= 0) {
  3268. err = SSL_get_error(ssl, n);
  3269. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3270. err = ERRNO;
  3271. } else {
  3272. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3273. return -1;
  3274. }
  3275. } else {
  3276. err = 0;
  3277. }
  3278. } else
  3279. #endif
  3280. if (fp != NULL) {
  3281. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3282. if (ferror(fp)) {
  3283. n = -1;
  3284. err = ERRNO;
  3285. } else {
  3286. err = 0;
  3287. }
  3288. } else {
  3289. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3290. err = (n < 0) ? ERRNO : 0;
  3291. }
  3292. if (ctx->stop_flag) {
  3293. return -1;
  3294. }
  3295. if ((n > 0) || (n == 0 && len == 0)) {
  3296. /* some data has been read, or no data was requested */
  3297. return n;
  3298. }
  3299. if (n == 0) {
  3300. /* shutdown of the socket at client side */
  3301. return -1;
  3302. }
  3303. if (n < 0) {
  3304. /* socket error - check errno */
  3305. DEBUG_TRACE("send() failed, error %d", err);
  3306. /* TODO: error handling depending on the error code.
  3307. * These codes are different between Windows and Linux.
  3308. */
  3309. return -1;
  3310. }
  3311. /* This code is not reached in the moment.
  3312. * ==> Fix the TODOs above first. */
  3313. if (timeout > 0) {
  3314. clock_gettime(CLOCK_MONOTONIC, &now);
  3315. }
  3316. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3317. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3318. used */
  3319. return -1;
  3320. }
  3321. static int64_t
  3322. push_all(struct mg_context *ctx,
  3323. FILE *fp,
  3324. SOCKET sock,
  3325. SSL *ssl,
  3326. const char *buf,
  3327. int64_t len)
  3328. {
  3329. double timeout = -1.0;
  3330. int64_t n, nwritten = 0;
  3331. if (ctx == NULL) {
  3332. return -1;
  3333. }
  3334. if (ctx->config[REQUEST_TIMEOUT]) {
  3335. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3336. }
  3337. while (len > 0 && ctx->stop_flag == 0) {
  3338. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3339. if (n < 0) {
  3340. if (nwritten == 0) {
  3341. nwritten = n; /* Propagate the error */
  3342. }
  3343. break;
  3344. } else if (n == 0) {
  3345. break; /* No more data to write */
  3346. } else {
  3347. nwritten += n;
  3348. len -= n;
  3349. }
  3350. }
  3351. return nwritten;
  3352. }
  3353. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3354. * Return negative value on error, or number of bytes read on success. */
  3355. static int
  3356. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3357. {
  3358. int nread, err;
  3359. struct timespec start, now;
  3360. #ifdef _WIN32
  3361. typedef int len_t;
  3362. #else
  3363. typedef size_t len_t;
  3364. #endif
  3365. if (timeout > 0) {
  3366. memset(&start, 0, sizeof(start));
  3367. memset(&now, 0, sizeof(now));
  3368. clock_gettime(CLOCK_MONOTONIC, &start);
  3369. }
  3370. do {
  3371. if (fp != NULL) {
  3372. #if !defined(_WIN32_WCE)
  3373. /* Use read() instead of fread(), because if we're reading from the
  3374. * CGI pipe, fread() may block until IO buffer is filled up. We
  3375. * cannot afford to block and must pass all read bytes immediately
  3376. * to the client. */
  3377. nread = (int)read(fileno(fp), buf, (size_t)len);
  3378. #else
  3379. /* WinCE does not support CGI pipes */
  3380. nread = (int)fread(buf, 1, (size_t)len, fp);
  3381. #endif
  3382. err = (nread < 0) ? ERRNO : 0;
  3383. #ifndef NO_SSL
  3384. } else if (conn->ssl != NULL) {
  3385. nread = SSL_read(conn->ssl, buf, len);
  3386. if (nread <= 0) {
  3387. err = SSL_get_error(conn->ssl, nread);
  3388. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3389. err = ERRNO;
  3390. } else {
  3391. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3392. return -1;
  3393. }
  3394. } else {
  3395. err = 0;
  3396. }
  3397. #endif
  3398. } else {
  3399. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3400. err = (nread < 0) ? ERRNO : 0;
  3401. }
  3402. if (conn->ctx->stop_flag) {
  3403. return -1;
  3404. }
  3405. if ((nread > 0) || (nread == 0 && len == 0)) {
  3406. /* some data has been read, or no data was requested */
  3407. return nread;
  3408. }
  3409. if (nread == 0) {
  3410. /* shutdown of the socket at client side */
  3411. return -1;
  3412. }
  3413. if (nread < 0) {
  3414. /* socket error - check errno */
  3415. #ifdef _WIN32
  3416. if (err == WSAEWOULDBLOCK) {
  3417. /* standard case if called from close_socket_gracefully */
  3418. return -1;
  3419. } else if (err == WSAETIMEDOUT) {
  3420. /* timeout is handled by the while loop */
  3421. } else {
  3422. DEBUG_TRACE("recv() failed, error %d", err);
  3423. return -1;
  3424. }
  3425. #else
  3426. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3427. * if the timeout is reached and if the socket was set to non-
  3428. * blocking in close_socket_gracefully, so we can not distinguish
  3429. * here. We have to wait for the timeout in both cases for now.
  3430. */
  3431. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3432. /* EAGAIN/EWOULDBLOCK:
  3433. * standard case if called from close_socket_gracefully
  3434. * => should return -1 */
  3435. /* or timeout occured
  3436. * => the code must stay in the while loop */
  3437. /* EINTR can be generated on a socket with a timeout set even
  3438. * when SA_RESTART is effective for all relevant signals
  3439. * (see signal(7)).
  3440. * => stay in the while loop */
  3441. } else {
  3442. DEBUG_TRACE("recv() failed, error %d", err);
  3443. return -1;
  3444. }
  3445. #endif
  3446. }
  3447. if (timeout > 0) {
  3448. clock_gettime(CLOCK_MONOTONIC, &now);
  3449. }
  3450. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3451. /* Timeout occured, but no data available. */
  3452. return -1;
  3453. }
  3454. static int
  3455. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3456. {
  3457. int n, nread = 0;
  3458. double timeout = -1.0;
  3459. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3460. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3461. }
  3462. while (len > 0 && conn->ctx->stop_flag == 0) {
  3463. n = pull(fp, conn, buf + nread, len, timeout);
  3464. if (n < 0) {
  3465. if (nread == 0) {
  3466. nread = n; /* Propagate the error */
  3467. }
  3468. break;
  3469. } else if (n == 0) {
  3470. break; /* No more data to read */
  3471. } else {
  3472. conn->consumed_content += n;
  3473. nread += n;
  3474. len -= n;
  3475. }
  3476. }
  3477. return nread;
  3478. }
  3479. static void
  3480. discard_unread_request_data(struct mg_connection *conn)
  3481. {
  3482. char buf[MG_BUF_LEN];
  3483. size_t to_read;
  3484. int nread;
  3485. if (conn == NULL) {
  3486. return;
  3487. }
  3488. to_read = sizeof(buf);
  3489. if (conn->is_chunked) {
  3490. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3491. * completely */
  3492. while (conn->is_chunked == 1) {
  3493. nread = mg_read(conn, buf, to_read);
  3494. if (nread <= 0) {
  3495. break;
  3496. }
  3497. }
  3498. } else {
  3499. /* Not chunked: content length is known */
  3500. while (conn->consumed_content < conn->content_len) {
  3501. if (to_read
  3502. > (size_t)(conn->content_len - conn->consumed_content)) {
  3503. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3504. }
  3505. nread = mg_read(conn, buf, to_read);
  3506. if (nread <= 0) {
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. }
  3512. static int
  3513. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3514. {
  3515. int64_t n, buffered_len, nread;
  3516. int64_t len64 =
  3517. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3518. * int, we may not read more
  3519. * bytes */
  3520. const char *body;
  3521. if (conn == NULL) {
  3522. return 0;
  3523. }
  3524. /* If Content-Length is not set for a PUT or POST request, read until
  3525. * socket is closed */
  3526. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3527. conn->content_len = INT64_MAX;
  3528. conn->must_close = 1;
  3529. }
  3530. nread = 0;
  3531. if (conn->consumed_content < conn->content_len) {
  3532. /* Adjust number of bytes to read. */
  3533. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3534. if (left_to_read < len64) {
  3535. /* Do not read more than the total content length of the request.
  3536. */
  3537. len64 = left_to_read;
  3538. }
  3539. /* Return buffered data */
  3540. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3541. - conn->consumed_content;
  3542. if (buffered_len > 0) {
  3543. if (len64 < buffered_len) {
  3544. buffered_len = len64;
  3545. }
  3546. body = conn->buf + conn->request_len + conn->consumed_content;
  3547. memcpy(buf, body, (size_t)buffered_len);
  3548. len64 -= buffered_len;
  3549. conn->consumed_content += buffered_len;
  3550. nread += buffered_len;
  3551. buf = (char *)buf + buffered_len;
  3552. }
  3553. /* We have returned all buffered data. Read new data from the remote
  3554. * socket.
  3555. */
  3556. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3557. nread += n;
  3558. } else {
  3559. nread = (nread > 0 ? nread : n);
  3560. }
  3561. }
  3562. return (int)nread;
  3563. }
  3564. static char
  3565. mg_getc(struct mg_connection *conn)
  3566. {
  3567. char c;
  3568. if (conn == NULL) {
  3569. return 0;
  3570. }
  3571. conn->content_len++;
  3572. if (mg_read_inner(conn, &c, 1) <= 0) {
  3573. return (char)0;
  3574. }
  3575. return c;
  3576. }
  3577. int
  3578. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3579. {
  3580. if (len > INT_MAX) {
  3581. len = INT_MAX;
  3582. }
  3583. if (conn == NULL) {
  3584. return 0;
  3585. }
  3586. if (conn->is_chunked) {
  3587. size_t all_read = 0;
  3588. while (len > 0) {
  3589. if (conn->is_chunked == 2) {
  3590. /* No more data left to read */
  3591. return 0;
  3592. }
  3593. if (conn->chunk_remainder) {
  3594. /* copy from the remainder of the last received chunk */
  3595. long read_ret;
  3596. size_t read_now =
  3597. ((conn->chunk_remainder > len) ? (len)
  3598. : (conn->chunk_remainder));
  3599. conn->content_len += (int)read_now;
  3600. read_ret =
  3601. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3602. all_read += (size_t)read_ret;
  3603. conn->chunk_remainder -= read_now;
  3604. len -= read_now;
  3605. if (conn->chunk_remainder == 0) {
  3606. /* the rest of the data in the current chunk has been read
  3607. */
  3608. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3609. /* Protocol violation */
  3610. return -1;
  3611. }
  3612. }
  3613. } else {
  3614. /* fetch a new chunk */
  3615. int i = 0;
  3616. char lenbuf[64];
  3617. char *end = 0;
  3618. unsigned long chunkSize = 0;
  3619. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3620. lenbuf[i] = mg_getc(conn);
  3621. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3622. continue;
  3623. }
  3624. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3625. lenbuf[i + 1] = 0;
  3626. chunkSize = strtoul(lenbuf, &end, 16);
  3627. if (chunkSize == 0) {
  3628. /* regular end of content */
  3629. conn->is_chunked = 2;
  3630. }
  3631. break;
  3632. }
  3633. if (!isalnum(lenbuf[i])) {
  3634. /* illegal character for chunk length */
  3635. return -1;
  3636. }
  3637. }
  3638. if ((end == NULL) || (*end != '\r')) {
  3639. /* chunksize not set correctly */
  3640. return -1;
  3641. }
  3642. if (chunkSize == 0) {
  3643. break;
  3644. }
  3645. conn->chunk_remainder = chunkSize;
  3646. }
  3647. }
  3648. return (int)all_read;
  3649. }
  3650. return mg_read_inner(conn, buf, len);
  3651. }
  3652. int
  3653. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3654. {
  3655. time_t now;
  3656. int64_t n, total, allowed;
  3657. if (conn == NULL) {
  3658. return 0;
  3659. }
  3660. if (conn->throttle > 0) {
  3661. if ((now = time(NULL)) != conn->last_throttle_time) {
  3662. conn->last_throttle_time = now;
  3663. conn->last_throttle_bytes = 0;
  3664. }
  3665. allowed = conn->throttle - conn->last_throttle_bytes;
  3666. if (allowed > (int64_t)len) {
  3667. allowed = (int64_t)len;
  3668. }
  3669. if ((total = push_all(conn->ctx,
  3670. NULL,
  3671. conn->client.sock,
  3672. conn->ssl,
  3673. (const char *)buf,
  3674. (int64_t)allowed)) == allowed) {
  3675. buf = (const char *)buf + total;
  3676. conn->last_throttle_bytes += total;
  3677. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3678. allowed = conn->throttle > (int64_t)len - total
  3679. ? (int64_t)len - total
  3680. : conn->throttle;
  3681. if ((n = push_all(conn->ctx,
  3682. NULL,
  3683. conn->client.sock,
  3684. conn->ssl,
  3685. (const char *)buf,
  3686. (int64_t)allowed)) != allowed) {
  3687. break;
  3688. }
  3689. sleep(1);
  3690. conn->last_throttle_bytes = allowed;
  3691. conn->last_throttle_time = time(NULL);
  3692. buf = (const char *)buf + n;
  3693. total += n;
  3694. }
  3695. }
  3696. } else {
  3697. total = push_all(conn->ctx,
  3698. NULL,
  3699. conn->client.sock,
  3700. conn->ssl,
  3701. (const char *)buf,
  3702. (int64_t)len);
  3703. }
  3704. return (int)total;
  3705. }
  3706. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3707. static int
  3708. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3709. {
  3710. va_list ap_copy;
  3711. size_t size = MG_BUF_LEN / 4;
  3712. int len = -1;
  3713. *buf = NULL;
  3714. while (len < 0) {
  3715. if (*buf) {
  3716. mg_free(*buf);
  3717. }
  3718. size *= 4;
  3719. *buf = (char *)mg_malloc(size);
  3720. if (!*buf) {
  3721. break;
  3722. }
  3723. va_copy(ap_copy, ap);
  3724. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3725. va_end(ap_copy);
  3726. (*buf)[size - 1] = 0;
  3727. }
  3728. return len;
  3729. }
  3730. /* Print message to buffer. If buffer is large enough to hold the message,
  3731. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3732. * and return allocated buffer. */
  3733. static int
  3734. alloc_vprintf(char **out_buf,
  3735. char *prealloc_buf,
  3736. size_t prealloc_size,
  3737. const char *fmt,
  3738. va_list ap)
  3739. {
  3740. va_list ap_copy;
  3741. int len;
  3742. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3743. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3744. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3745. * Therefore, we make two passes: on first pass, get required message
  3746. * length.
  3747. * On second pass, actually print the message. */
  3748. va_copy(ap_copy, ap);
  3749. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3750. va_end(ap_copy);
  3751. if (len < 0) {
  3752. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3753. * Switch to alternative code path that uses incremental allocations.
  3754. */
  3755. va_copy(ap_copy, ap);
  3756. len = alloc_vprintf2(out_buf, fmt, ap);
  3757. va_end(ap_copy);
  3758. } else if ((size_t)(len) >= prealloc_size) {
  3759. /* The pre-allocated buffer not large enough. */
  3760. /* Allocate a new buffer. */
  3761. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3762. if (!*out_buf) {
  3763. /* Allocation failed. Return -1 as "out of memory" error. */
  3764. return -1;
  3765. }
  3766. /* Buffer allocation successful. Store the string there. */
  3767. va_copy(ap_copy, ap);
  3768. IGNORE_UNUSED_RESULT(
  3769. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3770. va_end(ap_copy);
  3771. } else {
  3772. /* The pre-allocated buffer is large enough.
  3773. * Use it to store the string and return the address. */
  3774. va_copy(ap_copy, ap);
  3775. IGNORE_UNUSED_RESULT(
  3776. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3777. va_end(ap_copy);
  3778. *out_buf = prealloc_buf;
  3779. }
  3780. return len;
  3781. }
  3782. static int
  3783. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3784. {
  3785. char mem[MG_BUF_LEN];
  3786. char *buf = NULL;
  3787. int len;
  3788. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3789. len = mg_write(conn, buf, (size_t)len);
  3790. }
  3791. if (buf != mem && buf != NULL) {
  3792. mg_free(buf);
  3793. }
  3794. return len;
  3795. }
  3796. int
  3797. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3798. {
  3799. va_list ap;
  3800. int result;
  3801. va_start(ap, fmt);
  3802. result = mg_vprintf(conn, fmt, ap);
  3803. va_end(ap);
  3804. return result;
  3805. }
  3806. int
  3807. mg_url_decode(const char *src,
  3808. int src_len,
  3809. char *dst,
  3810. int dst_len,
  3811. int is_form_url_encoded)
  3812. {
  3813. int i, j, a, b;
  3814. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3815. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3816. if (i < src_len - 2 && src[i] == '%'
  3817. && isxdigit(*(const unsigned char *)(src + i + 1))
  3818. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3819. a = tolower(*(const unsigned char *)(src + i + 1));
  3820. b = tolower(*(const unsigned char *)(src + i + 2));
  3821. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3822. i += 2;
  3823. } else if (is_form_url_encoded && src[i] == '+') {
  3824. dst[j] = ' ';
  3825. } else {
  3826. dst[j] = src[i];
  3827. }
  3828. }
  3829. dst[j] = '\0'; /* Null-terminate the destination */
  3830. return i >= src_len ? j : -1;
  3831. }
  3832. int
  3833. mg_get_var(const char *data,
  3834. size_t data_len,
  3835. const char *name,
  3836. char *dst,
  3837. size_t dst_len)
  3838. {
  3839. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3840. }
  3841. int
  3842. mg_get_var2(const char *data,
  3843. size_t data_len,
  3844. const char *name,
  3845. char *dst,
  3846. size_t dst_len,
  3847. size_t occurrence)
  3848. {
  3849. const char *p, *e, *s;
  3850. size_t name_len;
  3851. int len;
  3852. if (dst == NULL || dst_len == 0) {
  3853. len = -2;
  3854. } else if (data == NULL || name == NULL || data_len == 0) {
  3855. len = -1;
  3856. dst[0] = '\0';
  3857. } else {
  3858. name_len = strlen(name);
  3859. e = data + data_len;
  3860. len = -1;
  3861. dst[0] = '\0';
  3862. /* data is "var1=val1&var2=val2...". Find variable first */
  3863. for (p = data; p + name_len < e; p++) {
  3864. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3865. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3866. /* Point p to variable value */
  3867. p += name_len + 1;
  3868. /* Point s to the end of the value */
  3869. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3870. if (s == NULL) {
  3871. s = e;
  3872. }
  3873. /* assert(s >= p); */
  3874. if (s < p) {
  3875. return -3;
  3876. }
  3877. /* Decode variable into destination buffer */
  3878. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3879. /* Redirect error code from -1 to -2 (destination buffer too
  3880. * small). */
  3881. if (len == -1) {
  3882. len = -2;
  3883. }
  3884. break;
  3885. }
  3886. }
  3887. }
  3888. return len;
  3889. }
  3890. int
  3891. mg_get_cookie(const char *cookie_header,
  3892. const char *var_name,
  3893. char *dst,
  3894. size_t dst_size)
  3895. {
  3896. const char *s, *p, *end;
  3897. int name_len, len = -1;
  3898. if (dst == NULL || dst_size == 0) {
  3899. len = -2;
  3900. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3901. len = -1;
  3902. dst[0] = '\0';
  3903. } else {
  3904. name_len = (int)strlen(var_name);
  3905. end = s + strlen(s);
  3906. dst[0] = '\0';
  3907. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3908. if (s[name_len] == '=') {
  3909. s += name_len + 1;
  3910. if ((p = strchr(s, ' ')) == NULL) {
  3911. p = end;
  3912. }
  3913. if (p[-1] == ';') {
  3914. p--;
  3915. }
  3916. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3917. s++;
  3918. p--;
  3919. }
  3920. if ((size_t)(p - s) < dst_size) {
  3921. len = (int)(p - s);
  3922. mg_strlcpy(dst, s, (size_t)len + 1);
  3923. } else {
  3924. len = -3;
  3925. }
  3926. break;
  3927. }
  3928. }
  3929. }
  3930. return len;
  3931. }
  3932. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3933. static void
  3934. base64_encode(const unsigned char *src, int src_len, char *dst)
  3935. {
  3936. static const char *b64 =
  3937. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3938. int i, j, a, b, c;
  3939. for (i = j = 0; i < src_len; i += 3) {
  3940. a = src[i];
  3941. b = i + 1 >= src_len ? 0 : src[i + 1];
  3942. c = i + 2 >= src_len ? 0 : src[i + 2];
  3943. dst[j++] = b64[a >> 2];
  3944. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3945. if (i + 1 < src_len) {
  3946. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3947. }
  3948. if (i + 2 < src_len) {
  3949. dst[j++] = b64[c & 63];
  3950. }
  3951. }
  3952. while (j % 4 != 0) {
  3953. dst[j++] = '=';
  3954. }
  3955. dst[j++] = '\0';
  3956. }
  3957. #endif
  3958. #if defined(USE_LUA)
  3959. static unsigned char
  3960. b64reverse(char letter)
  3961. {
  3962. if (letter >= 'A' && letter <= 'Z') {
  3963. return letter - 'A';
  3964. }
  3965. if (letter >= 'a' && letter <= 'z') {
  3966. return letter - 'a' + 26;
  3967. }
  3968. if (letter >= '0' && letter <= '9') {
  3969. return letter - '0' + 52;
  3970. }
  3971. if (letter == '+') {
  3972. return 62;
  3973. }
  3974. if (letter == '/') {
  3975. return 63;
  3976. }
  3977. if (letter == '=') {
  3978. return 255; /* normal end */
  3979. }
  3980. return 254; /* error */
  3981. }
  3982. static int
  3983. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3984. {
  3985. int i;
  3986. unsigned char a, b, c, d;
  3987. *dst_len = 0;
  3988. for (i = 0; i < src_len; i += 4) {
  3989. a = b64reverse(src[i]);
  3990. if (a >= 254) {
  3991. return i;
  3992. }
  3993. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3994. if (b >= 254) {
  3995. return i + 1;
  3996. }
  3997. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3998. if (c == 254) {
  3999. return i + 2;
  4000. }
  4001. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  4002. if (d == 254) {
  4003. return i + 3;
  4004. }
  4005. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4006. if (c != 255) {
  4007. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4008. if (d != 255) {
  4009. dst[(*dst_len)++] = (c << 6) + d;
  4010. }
  4011. }
  4012. }
  4013. return -1;
  4014. }
  4015. #endif
  4016. static int
  4017. is_put_or_delete_method(const struct mg_connection *conn)
  4018. {
  4019. if (conn) {
  4020. const char *s = conn->request_info.request_method;
  4021. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4022. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4023. }
  4024. return 0;
  4025. }
  4026. static void
  4027. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4028. char *filename, /* out: filename */
  4029. size_t filename_buf_len, /* in: size of filename buffer */
  4030. struct file *filep, /* out: file structure */
  4031. int *is_found, /* out: file is found (directly) */
  4032. int *is_script_resource, /* out: handled by a script? */
  4033. int *is_websocket_request, /* out: websocket connetion? */
  4034. int *is_put_or_delete_request /* out: put/delete a file? */
  4035. )
  4036. {
  4037. /* TODO (high): Restructure this function */
  4038. #if !defined(NO_FILES)
  4039. const char *uri = conn->request_info.local_uri;
  4040. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4041. const char *rewrite;
  4042. struct vec a, b;
  4043. int match_len;
  4044. char gz_path[PATH_MAX];
  4045. char const *accept_encoding;
  4046. int truncated;
  4047. #if !defined(NO_CGI) || defined(USE_LUA)
  4048. char *p;
  4049. #endif
  4050. #else
  4051. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4052. #endif
  4053. memset(filep, 0, sizeof(*filep));
  4054. *filename = 0;
  4055. *is_found = 0;
  4056. *is_script_resource = 0;
  4057. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4058. #if defined(USE_WEBSOCKET)
  4059. *is_websocket_request = is_websocket_protocol(conn);
  4060. #if !defined(NO_FILES)
  4061. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4062. root = conn->ctx->config[WEBSOCKET_ROOT];
  4063. }
  4064. #endif /* !NO_FILES */
  4065. #else /* USE_WEBSOCKET */
  4066. *is_websocket_request = 0;
  4067. #endif /* USE_WEBSOCKET */
  4068. #if !defined(NO_FILES)
  4069. /* Note that root == NULL is a regular use case here. This occurs,
  4070. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4071. * config is not required. */
  4072. if (root == NULL) {
  4073. /* all file related outputs have already been set to 0, just return
  4074. */
  4075. return;
  4076. }
  4077. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4078. * of the path one byte on the right.
  4079. * If document_root is NULL, leave the file empty. */
  4080. mg_snprintf(
  4081. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4082. if (truncated) {
  4083. goto interpret_cleanup;
  4084. }
  4085. rewrite = conn->ctx->config[REWRITE];
  4086. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4087. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4088. mg_snprintf(conn,
  4089. &truncated,
  4090. filename,
  4091. filename_buf_len - 1,
  4092. "%.*s%s",
  4093. (int)b.len,
  4094. b.ptr,
  4095. uri + match_len);
  4096. break;
  4097. }
  4098. }
  4099. if (truncated) {
  4100. goto interpret_cleanup;
  4101. }
  4102. /* Local file path and name, corresponding to requested URI
  4103. * is now stored in "filename" variable. */
  4104. if (mg_stat(conn, filename, filep)) {
  4105. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4106. /* File exists. Check if it is a script type. */
  4107. if (0
  4108. #if !defined(NO_CGI)
  4109. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4110. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4111. filename) > 0
  4112. #endif
  4113. #if defined(USE_LUA)
  4114. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4115. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4116. filename) > 0
  4117. #endif
  4118. #if defined(USE_DUKTAPE)
  4119. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4120. strlen(
  4121. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4122. filename) > 0
  4123. #endif
  4124. ) {
  4125. /* The request addresses a CGI script or a Lua script. The URI
  4126. * corresponds to the script itself (like /path/script.cgi),
  4127. * and there is no additional resource path
  4128. * (like /path/script.cgi/something).
  4129. * Requests that modify (replace or delete) a resource, like
  4130. * PUT and DELETE requests, should replace/delete the script
  4131. * file.
  4132. * Requests that read or write from/to a resource, like GET and
  4133. * POST requests, should call the script and return the
  4134. * generated response. */
  4135. *is_script_resource = !*is_put_or_delete_request;
  4136. }
  4137. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4138. *is_found = 1;
  4139. return;
  4140. }
  4141. /* If we can't find the actual file, look for the file
  4142. * with the same name but a .gz extension. If we find it,
  4143. * use that and set the gzipped flag in the file struct
  4144. * to indicate that the response need to have the content-
  4145. * encoding: gzip header.
  4146. * We can only do this if the browser declares support. */
  4147. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4148. if (strstr(accept_encoding, "gzip") != NULL) {
  4149. mg_snprintf(
  4150. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4151. if (truncated) {
  4152. goto interpret_cleanup;
  4153. }
  4154. if (mg_stat(conn, gz_path, filep)) {
  4155. if (filep) {
  4156. filep->gzipped = 1;
  4157. *is_found = 1;
  4158. }
  4159. /* Currently gz files can not be scripts. */
  4160. return;
  4161. }
  4162. }
  4163. }
  4164. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4165. /* Support PATH_INFO for CGI scripts. */
  4166. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4167. if (*p == '/') {
  4168. *p = '\0';
  4169. if ((0
  4170. #if !defined(NO_CGI)
  4171. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4172. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4173. filename) > 0
  4174. #endif
  4175. #if defined(USE_LUA)
  4176. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4177. strlen(
  4178. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4179. filename) > 0
  4180. #endif
  4181. #if defined(USE_DUKTAPE)
  4182. || match_prefix(
  4183. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4184. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4185. filename) > 0
  4186. #endif
  4187. ) && mg_stat(conn, filename, filep)) {
  4188. /* Shift PATH_INFO block one character right, e.g.
  4189. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4190. * conn->path_info is pointing to the local variable "path"
  4191. * declared in handle_request(), so PATH_INFO is not valid
  4192. * after handle_request returns. */
  4193. conn->path_info = p + 1;
  4194. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4195. * trailing \0 */
  4196. p[1] = '/';
  4197. *is_script_resource = 1;
  4198. break;
  4199. } else {
  4200. *p = '/';
  4201. }
  4202. }
  4203. }
  4204. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4205. #endif /* !defined(NO_FILES) */
  4206. return;
  4207. #if !defined(NO_FILES)
  4208. /* Reset all outputs */
  4209. interpret_cleanup:
  4210. memset(filep, 0, sizeof(*filep));
  4211. *filename = 0;
  4212. *is_found = 0;
  4213. *is_script_resource = 0;
  4214. *is_websocket_request = 0;
  4215. *is_put_or_delete_request = 0;
  4216. #endif /* !defined(NO_FILES) */
  4217. }
  4218. /* Check whether full request is buffered. Return:
  4219. * -1 if request is malformed
  4220. * 0 if request is not yet fully buffered
  4221. * >0 actual request length, including last \r\n\r\n */
  4222. static int
  4223. get_request_len(const char *buf, int buflen)
  4224. {
  4225. const char *s, *e;
  4226. int len = 0;
  4227. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4228. /* Control characters are not allowed but >=128 is. */
  4229. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4230. && *(const unsigned char *)s < 128) {
  4231. len = -1;
  4232. break; /* [i_a] abort scan as soon as one malformed character is
  4233. * found; */
  4234. /* don't let subsequent \r\n\r\n win us over anyhow */
  4235. } else if (s[0] == '\n' && s[1] == '\n') {
  4236. len = (int)(s - buf) + 2;
  4237. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4238. len = (int)(s - buf) + 3;
  4239. }
  4240. return len;
  4241. }
  4242. #if !defined(NO_CACHING)
  4243. /* Convert month to the month number. Return -1 on error, or month number */
  4244. static int
  4245. get_month_index(const char *s)
  4246. {
  4247. size_t i;
  4248. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4249. if (!strcmp(s, month_names[i])) {
  4250. return (int)i;
  4251. }
  4252. }
  4253. return -1;
  4254. }
  4255. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4256. static time_t
  4257. parse_date_string(const char *datetime)
  4258. {
  4259. char month_str[32] = {0};
  4260. int second, minute, hour, day, month, year;
  4261. time_t result = (time_t)0;
  4262. struct tm tm;
  4263. if ((sscanf(datetime,
  4264. "%d/%3s/%d %d:%d:%d",
  4265. &day,
  4266. month_str,
  4267. &year,
  4268. &hour,
  4269. &minute,
  4270. &second) == 6) || (sscanf(datetime,
  4271. "%d %3s %d %d:%d:%d",
  4272. &day,
  4273. month_str,
  4274. &year,
  4275. &hour,
  4276. &minute,
  4277. &second) == 6)
  4278. || (sscanf(datetime,
  4279. "%*3s, %d %3s %d %d:%d:%d",
  4280. &day,
  4281. month_str,
  4282. &year,
  4283. &hour,
  4284. &minute,
  4285. &second) == 6) || (sscanf(datetime,
  4286. "%d-%3s-%d %d:%d:%d",
  4287. &day,
  4288. month_str,
  4289. &year,
  4290. &hour,
  4291. &minute,
  4292. &second) == 6)) {
  4293. month = get_month_index(month_str);
  4294. if ((month >= 0) && (year >= 1970)) {
  4295. memset(&tm, 0, sizeof(tm));
  4296. tm.tm_year = year - 1900;
  4297. tm.tm_mon = month;
  4298. tm.tm_mday = day;
  4299. tm.tm_hour = hour;
  4300. tm.tm_min = minute;
  4301. tm.tm_sec = second;
  4302. result = timegm(&tm);
  4303. }
  4304. }
  4305. return result;
  4306. }
  4307. #endif /* !NO_CACHING */
  4308. /* Protect against directory disclosure attack by removing '..',
  4309. * excessive '/' and '\' characters */
  4310. static void
  4311. remove_double_dots_and_double_slashes(char *s)
  4312. {
  4313. char *p = s;
  4314. while (*s != '\0') {
  4315. *p++ = *s++;
  4316. if (s[-1] == '/' || s[-1] == '\\') {
  4317. /* Skip all following slashes, backslashes and double-dots */
  4318. while (s[0] != '\0') {
  4319. if (s[0] == '/' || s[0] == '\\') {
  4320. s++;
  4321. } else if (s[0] == '.' && s[1] == '.') {
  4322. s += 2;
  4323. } else {
  4324. break;
  4325. }
  4326. }
  4327. }
  4328. }
  4329. *p = '\0';
  4330. }
  4331. static const struct {
  4332. const char *extension;
  4333. size_t ext_len;
  4334. const char *mime_type;
  4335. } builtin_mime_types[] = {
  4336. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4337. * application types */
  4338. {".doc", 4, "application/msword"},
  4339. {".eps", 4, "application/postscript"},
  4340. {".exe", 4, "application/octet-stream"},
  4341. {".js", 3, "application/javascript"},
  4342. {".json", 5, "application/json"},
  4343. {".pdf", 4, "application/pdf"},
  4344. {".ps", 3, "application/postscript"},
  4345. {".rtf", 4, "application/rtf"},
  4346. {".xhtml", 6, "application/xhtml+xml"},
  4347. {".xsl", 4, "application/xml"},
  4348. {".xslt", 5, "application/xml"},
  4349. /* fonts */
  4350. {".ttf", 4, "application/font-sfnt"},
  4351. {".cff", 4, "application/font-sfnt"},
  4352. {".otf", 4, "application/font-sfnt"},
  4353. {".aat", 4, "application/font-sfnt"},
  4354. {".sil", 4, "application/font-sfnt"},
  4355. {".pfr", 4, "application/font-tdpfr"},
  4356. {".woff", 5, "application/font-woff"},
  4357. /* audio */
  4358. {".mp3", 4, "audio/mpeg"},
  4359. {".oga", 4, "audio/ogg"},
  4360. {".ogg", 4, "audio/ogg"},
  4361. /* image */
  4362. {".gif", 4, "image/gif"},
  4363. {".ief", 4, "image/ief"},
  4364. {".jpeg", 5, "image/jpeg"},
  4365. {".jpg", 4, "image/jpeg"},
  4366. {".jpm", 4, "image/jpm"},
  4367. {".jpx", 4, "image/jpx"},
  4368. {".png", 4, "image/png"},
  4369. {".svg", 4, "image/svg+xml"},
  4370. {".tif", 4, "image/tiff"},
  4371. {".tiff", 5, "image/tiff"},
  4372. /* model */
  4373. {".wrl", 4, "model/vrml"},
  4374. /* text */
  4375. {".css", 4, "text/css"},
  4376. {".csv", 4, "text/csv"},
  4377. {".htm", 4, "text/html"},
  4378. {".html", 5, "text/html"},
  4379. {".sgm", 4, "text/sgml"},
  4380. {".shtm", 5, "text/html"},
  4381. {".shtml", 6, "text/html"},
  4382. {".txt", 4, "text/plain"},
  4383. {".xml", 4, "text/xml"},
  4384. /* video */
  4385. {".mov", 4, "video/quicktime"},
  4386. {".mp4", 4, "video/mp4"},
  4387. {".mpeg", 5, "video/mpeg"},
  4388. {".mpg", 4, "video/mpeg"},
  4389. {".ogv", 4, "video/ogg"},
  4390. {".qt", 3, "video/quicktime"},
  4391. /* not registered types
  4392. * (http://reference.sitepoint.com/html/mime-types-full,
  4393. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4394. {".arj", 4, "application/x-arj-compressed"},
  4395. {".gz", 3, "application/x-gunzip"},
  4396. {".rar", 4, "application/x-arj-compressed"},
  4397. {".swf", 4, "application/x-shockwave-flash"},
  4398. {".tar", 4, "application/x-tar"},
  4399. {".tgz", 4, "application/x-tar-gz"},
  4400. {".torrent", 8, "application/x-bittorrent"},
  4401. {".ppt", 4, "application/x-mspowerpoint"},
  4402. {".xls", 4, "application/x-msexcel"},
  4403. {".zip", 4, "application/x-zip-compressed"},
  4404. {".aac",
  4405. 4,
  4406. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4407. {".aif", 4, "audio/x-aif"},
  4408. {".m3u", 4, "audio/x-mpegurl"},
  4409. {".mid", 4, "audio/x-midi"},
  4410. {".ra", 3, "audio/x-pn-realaudio"},
  4411. {".ram", 4, "audio/x-pn-realaudio"},
  4412. {".wav", 4, "audio/x-wav"},
  4413. {".bmp", 4, "image/bmp"},
  4414. {".ico", 4, "image/x-icon"},
  4415. {".pct", 4, "image/x-pct"},
  4416. {".pict", 5, "image/pict"},
  4417. {".rgb", 4, "image/x-rgb"},
  4418. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4419. {".asf", 4, "video/x-ms-asf"},
  4420. {".avi", 4, "video/x-msvideo"},
  4421. {".m4v", 4, "video/x-m4v"},
  4422. {NULL, 0, NULL}};
  4423. const char *
  4424. mg_get_builtin_mime_type(const char *path)
  4425. {
  4426. const char *ext;
  4427. size_t i, path_len;
  4428. path_len = strlen(path);
  4429. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4430. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4431. if (path_len > builtin_mime_types[i].ext_len
  4432. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4433. return builtin_mime_types[i].mime_type;
  4434. }
  4435. }
  4436. return "text/plain";
  4437. }
  4438. /* Look at the "path" extension and figure what mime type it has.
  4439. * Store mime type in the vector. */
  4440. static void
  4441. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4442. {
  4443. struct vec ext_vec, mime_vec;
  4444. const char *list, *ext;
  4445. size_t path_len;
  4446. path_len = strlen(path);
  4447. if (ctx == NULL || vec == NULL) {
  4448. return;
  4449. }
  4450. /* Scan user-defined mime types first, in case user wants to
  4451. * override default mime types. */
  4452. list = ctx->config[EXTRA_MIME_TYPES];
  4453. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4454. /* ext now points to the path suffix */
  4455. ext = path + path_len - ext_vec.len;
  4456. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4457. *vec = mime_vec;
  4458. return;
  4459. }
  4460. }
  4461. vec->ptr = mg_get_builtin_mime_type(path);
  4462. vec->len = strlen(vec->ptr);
  4463. }
  4464. /* Stringify binary data. Output buffer must be twice as big as input,
  4465. * because each byte takes 2 bytes in string representation */
  4466. static void
  4467. bin2str(char *to, const unsigned char *p, size_t len)
  4468. {
  4469. static const char *hex = "0123456789abcdef";
  4470. for (; len--; p++) {
  4471. *to++ = hex[p[0] >> 4];
  4472. *to++ = hex[p[0] & 0x0f];
  4473. }
  4474. *to = '\0';
  4475. }
  4476. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4477. char *
  4478. mg_md5(char buf[33], ...)
  4479. {
  4480. md5_byte_t hash[16];
  4481. const char *p;
  4482. va_list ap;
  4483. md5_state_t ctx;
  4484. md5_init(&ctx);
  4485. va_start(ap, buf);
  4486. while ((p = va_arg(ap, const char *)) != NULL) {
  4487. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4488. }
  4489. va_end(ap);
  4490. md5_finish(&ctx, hash);
  4491. bin2str(buf, hash, sizeof(hash));
  4492. return buf;
  4493. }
  4494. /* Check the user's password, return 1 if OK */
  4495. static int
  4496. check_password(const char *method,
  4497. const char *ha1,
  4498. const char *uri,
  4499. const char *nonce,
  4500. const char *nc,
  4501. const char *cnonce,
  4502. const char *qop,
  4503. const char *response)
  4504. {
  4505. char ha2[32 + 1], expected_response[32 + 1];
  4506. /* Some of the parameters may be NULL */
  4507. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4508. || qop == NULL
  4509. || response == NULL) {
  4510. return 0;
  4511. }
  4512. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4513. if (strlen(response) != 32) {
  4514. return 0;
  4515. }
  4516. mg_md5(ha2, method, ":", uri, NULL);
  4517. mg_md5(expected_response,
  4518. ha1,
  4519. ":",
  4520. nonce,
  4521. ":",
  4522. nc,
  4523. ":",
  4524. cnonce,
  4525. ":",
  4526. qop,
  4527. ":",
  4528. ha2,
  4529. NULL);
  4530. return mg_strcasecmp(response, expected_response) == 0;
  4531. }
  4532. /* Use the global passwords file, if specified by auth_gpass option,
  4533. * or search for .htpasswd in the requested directory. */
  4534. static void
  4535. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4536. {
  4537. if (conn != NULL && conn->ctx != NULL) {
  4538. char name[PATH_MAX];
  4539. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4540. struct file file = STRUCT_FILE_INITIALIZER;
  4541. int truncated;
  4542. if (gpass != NULL) {
  4543. /* Use global passwords file */
  4544. if (!mg_fopen(conn, gpass, "r", filep)) {
  4545. #ifdef DEBUG
  4546. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4547. #endif
  4548. }
  4549. /* Important: using local struct file to test path for is_directory
  4550. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4551. * was opened. */
  4552. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4553. mg_snprintf(conn,
  4554. &truncated,
  4555. name,
  4556. sizeof(name),
  4557. "%s/%s",
  4558. path,
  4559. PASSWORDS_FILE_NAME);
  4560. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4561. #ifdef DEBUG
  4562. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4563. #endif
  4564. }
  4565. } else {
  4566. /* Try to find .htpasswd in requested directory. */
  4567. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4568. if (e[0] == '/') {
  4569. break;
  4570. }
  4571. }
  4572. mg_snprintf(conn,
  4573. &truncated,
  4574. name,
  4575. sizeof(name),
  4576. "%.*s/%s",
  4577. (int)(e - p),
  4578. p,
  4579. PASSWORDS_FILE_NAME);
  4580. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4581. #ifdef DEBUG
  4582. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4583. #endif
  4584. }
  4585. }
  4586. }
  4587. }
  4588. /* Parsed Authorization header */
  4589. struct ah {
  4590. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4591. };
  4592. /* Return 1 on success. Always initializes the ah structure. */
  4593. static int
  4594. parse_auth_header(struct mg_connection *conn,
  4595. char *buf,
  4596. size_t buf_size,
  4597. struct ah *ah)
  4598. {
  4599. char *name, *value, *s;
  4600. const char *auth_header;
  4601. uint64_t nonce;
  4602. if (!ah || !conn) {
  4603. return 0;
  4604. }
  4605. (void)memset(ah, 0, sizeof(*ah));
  4606. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4607. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4608. return 0;
  4609. }
  4610. /* Make modifiable copy of the auth header */
  4611. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4612. s = buf;
  4613. /* Parse authorization header */
  4614. for (;;) {
  4615. /* Gobble initial spaces */
  4616. while (isspace(*(unsigned char *)s)) {
  4617. s++;
  4618. }
  4619. name = skip_quoted(&s, "=", " ", 0);
  4620. /* Value is either quote-delimited, or ends at first comma or space. */
  4621. if (s[0] == '\"') {
  4622. s++;
  4623. value = skip_quoted(&s, "\"", " ", '\\');
  4624. if (s[0] == ',') {
  4625. s++;
  4626. }
  4627. } else {
  4628. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4629. * spaces */
  4630. }
  4631. if (*name == '\0') {
  4632. break;
  4633. }
  4634. if (!strcmp(name, "username")) {
  4635. ah->user = value;
  4636. } else if (!strcmp(name, "cnonce")) {
  4637. ah->cnonce = value;
  4638. } else if (!strcmp(name, "response")) {
  4639. ah->response = value;
  4640. } else if (!strcmp(name, "uri")) {
  4641. ah->uri = value;
  4642. } else if (!strcmp(name, "qop")) {
  4643. ah->qop = value;
  4644. } else if (!strcmp(name, "nc")) {
  4645. ah->nc = value;
  4646. } else if (!strcmp(name, "nonce")) {
  4647. ah->nonce = value;
  4648. }
  4649. }
  4650. #ifndef NO_NONCE_CHECK
  4651. /* Read the nonce from the response. */
  4652. if (ah->nonce == NULL) {
  4653. return 0;
  4654. }
  4655. s = NULL;
  4656. nonce = strtoull(ah->nonce, &s, 10);
  4657. if ((s == NULL) || (*s != 0)) {
  4658. return 0;
  4659. }
  4660. /* Convert the nonce from the client to a number. */
  4661. nonce ^= conn->ctx->auth_nonce_mask;
  4662. /* The converted number corresponds to the time the nounce has been
  4663. * created. This should not be earlier than the server start. */
  4664. /* Server side nonce check is valuable in all situations but one:
  4665. * if the server restarts frequently, but the client should not see
  4666. * that, so the server should accept nonces from previous starts. */
  4667. /* However, the reasonable default is to not accept a nonce from a
  4668. * previous start, so if anyone changed the access rights between
  4669. * two restarts, a new login is required. */
  4670. if (nonce < (uint64_t)conn->ctx->start_time) {
  4671. /* nonce is from a previous start of the server and no longer valid
  4672. * (replay attack?) */
  4673. return 0;
  4674. }
  4675. /* Check if the nonce is too high, so it has not (yet) been used by the
  4676. * server. */
  4677. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4678. return 0;
  4679. }
  4680. #else
  4681. (void)nonce;
  4682. #endif
  4683. /* CGI needs it as REMOTE_USER */
  4684. if (ah->user != NULL) {
  4685. conn->request_info.remote_user = mg_strdup(ah->user);
  4686. } else {
  4687. return 0;
  4688. }
  4689. return 1;
  4690. }
  4691. static const char *
  4692. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4693. {
  4694. const char *eof;
  4695. size_t len;
  4696. const char *memend;
  4697. if (!filep) {
  4698. return NULL;
  4699. }
  4700. if (filep->membuf != NULL && *p != NULL) {
  4701. memend = (const char *)&filep->membuf[filep->size];
  4702. /* Search for \n from p till the end of stream */
  4703. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4704. if (eof != NULL) {
  4705. eof += 1; /* Include \n */
  4706. } else {
  4707. eof = memend; /* Copy remaining data */
  4708. }
  4709. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4710. memcpy(buf, *p, len);
  4711. buf[len] = '\0';
  4712. *p += len;
  4713. return len ? eof : NULL;
  4714. } else if (filep->fp != NULL) {
  4715. return fgets(buf, (int)size, filep->fp);
  4716. } else {
  4717. return NULL;
  4718. }
  4719. }
  4720. struct read_auth_file_struct {
  4721. struct mg_connection *conn;
  4722. struct ah ah;
  4723. char *domain;
  4724. char buf[256 + 256 + 40];
  4725. char *f_user;
  4726. char *f_domain;
  4727. char *f_ha1;
  4728. };
  4729. static int
  4730. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4731. {
  4732. char *p;
  4733. int is_authorized = 0;
  4734. struct file fp;
  4735. size_t l;
  4736. if (!filep || !workdata) {
  4737. return 0;
  4738. }
  4739. /* Loop over passwords file */
  4740. p = (char *)filep->membuf;
  4741. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4742. l = strlen(workdata->buf);
  4743. while (l > 0) {
  4744. if (isspace(workdata->buf[l - 1])
  4745. || iscntrl(workdata->buf[l - 1])) {
  4746. l--;
  4747. workdata->buf[l] = 0;
  4748. } else
  4749. break;
  4750. }
  4751. if (l < 1) {
  4752. continue;
  4753. }
  4754. workdata->f_user = workdata->buf;
  4755. if (workdata->f_user[0] == ':') {
  4756. /* user names may not contain a ':' and may not be empty,
  4757. * so lines starting with ':' may be used for a special purpose */
  4758. if (workdata->f_user[1] == '#') {
  4759. /* :# is a comment */
  4760. continue;
  4761. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4762. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4763. is_authorized = read_auth_file(&fp, workdata);
  4764. mg_fclose(&fp);
  4765. } else {
  4766. mg_cry(workdata->conn,
  4767. "%s: cannot open authorization file: %s",
  4768. __func__,
  4769. workdata->buf);
  4770. }
  4771. continue;
  4772. }
  4773. /* everything is invalid for the moment (might change in the
  4774. * future) */
  4775. mg_cry(workdata->conn,
  4776. "%s: syntax error in authorization file: %s",
  4777. __func__,
  4778. workdata->buf);
  4779. continue;
  4780. }
  4781. workdata->f_domain = strchr(workdata->f_user, ':');
  4782. if (workdata->f_domain == NULL) {
  4783. mg_cry(workdata->conn,
  4784. "%s: syntax error in authorization file: %s",
  4785. __func__,
  4786. workdata->buf);
  4787. continue;
  4788. }
  4789. *(workdata->f_domain) = 0;
  4790. (workdata->f_domain)++;
  4791. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4792. if (workdata->f_ha1 == NULL) {
  4793. mg_cry(workdata->conn,
  4794. "%s: syntax error in authorization file: %s",
  4795. __func__,
  4796. workdata->buf);
  4797. continue;
  4798. }
  4799. *(workdata->f_ha1) = 0;
  4800. (workdata->f_ha1)++;
  4801. if (!strcmp(workdata->ah.user, workdata->f_user)
  4802. && !strcmp(workdata->domain, workdata->f_domain)) {
  4803. return check_password(workdata->conn->request_info.request_method,
  4804. workdata->f_ha1,
  4805. workdata->ah.uri,
  4806. workdata->ah.nonce,
  4807. workdata->ah.nc,
  4808. workdata->ah.cnonce,
  4809. workdata->ah.qop,
  4810. workdata->ah.response);
  4811. }
  4812. }
  4813. return is_authorized;
  4814. }
  4815. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4816. static int
  4817. authorize(struct mg_connection *conn, struct file *filep)
  4818. {
  4819. struct read_auth_file_struct workdata;
  4820. char buf[MG_BUF_LEN];
  4821. if (!conn || !conn->ctx) {
  4822. return 0;
  4823. }
  4824. memset(&workdata, 0, sizeof(workdata));
  4825. workdata.conn = conn;
  4826. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4827. return 0;
  4828. }
  4829. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4830. return read_auth_file(filep, &workdata);
  4831. }
  4832. /* Return 1 if request is authorised, 0 otherwise. */
  4833. static int
  4834. check_authorization(struct mg_connection *conn, const char *path)
  4835. {
  4836. char fname[PATH_MAX];
  4837. struct vec uri_vec, filename_vec;
  4838. const char *list;
  4839. struct file file = STRUCT_FILE_INITIALIZER;
  4840. int authorized = 1, truncated;
  4841. if (!conn || !conn->ctx) {
  4842. return 0;
  4843. }
  4844. list = conn->ctx->config[PROTECT_URI];
  4845. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4846. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4847. mg_snprintf(conn,
  4848. &truncated,
  4849. fname,
  4850. sizeof(fname),
  4851. "%.*s",
  4852. (int)filename_vec.len,
  4853. filename_vec.ptr);
  4854. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4855. mg_cry(conn,
  4856. "%s: cannot open %s: %s",
  4857. __func__,
  4858. fname,
  4859. strerror(errno));
  4860. }
  4861. break;
  4862. }
  4863. }
  4864. if (!is_file_opened(&file)) {
  4865. open_auth_file(conn, path, &file);
  4866. }
  4867. if (is_file_opened(&file)) {
  4868. authorized = authorize(conn, &file);
  4869. mg_fclose(&file);
  4870. }
  4871. return authorized;
  4872. }
  4873. static void
  4874. send_authorization_request(struct mg_connection *conn)
  4875. {
  4876. char date[64];
  4877. time_t curtime = time(NULL);
  4878. if (conn && conn->ctx) {
  4879. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4880. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4881. nonce += conn->ctx->nonce_count;
  4882. ++conn->ctx->nonce_count;
  4883. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4884. nonce ^= conn->ctx->auth_nonce_mask;
  4885. conn->status_code = 401;
  4886. conn->must_close = 1;
  4887. gmt_time_string(date, sizeof(date), &curtime);
  4888. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4889. send_no_cache_header(conn);
  4890. mg_printf(conn,
  4891. "Date: %s\r\n"
  4892. "Connection: %s\r\n"
  4893. "Content-Length: 0\r\n"
  4894. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4895. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4896. date,
  4897. suggest_connection_header(conn),
  4898. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4899. nonce);
  4900. }
  4901. }
  4902. #if !defined(NO_FILES)
  4903. static int
  4904. is_authorized_for_put(struct mg_connection *conn)
  4905. {
  4906. if (conn) {
  4907. struct file file = STRUCT_FILE_INITIALIZER;
  4908. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4909. int ret = 0;
  4910. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4911. ret = authorize(conn, &file);
  4912. mg_fclose(&file);
  4913. }
  4914. return ret;
  4915. }
  4916. return 0;
  4917. }
  4918. #endif
  4919. int
  4920. mg_modify_passwords_file(const char *fname,
  4921. const char *domain,
  4922. const char *user,
  4923. const char *pass)
  4924. {
  4925. int found, i;
  4926. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4927. FILE *fp, *fp2;
  4928. found = 0;
  4929. fp = fp2 = NULL;
  4930. /* Regard empty password as no password - remove user record. */
  4931. if (pass != NULL && pass[0] == '\0') {
  4932. pass = NULL;
  4933. }
  4934. /* Other arguments must not be empty */
  4935. if (fname == NULL || domain == NULL || user == NULL) {
  4936. return 0;
  4937. }
  4938. /* Using the given file format, user name and domain must not contain ':'
  4939. */
  4940. if (strchr(user, ':') != NULL) {
  4941. return 0;
  4942. }
  4943. if (strchr(domain, ':') != NULL) {
  4944. return 0;
  4945. }
  4946. /* Do not allow control characters like newline in user name and domain.
  4947. * Do not allow excessively long names either. */
  4948. for (i = 0; i < 255 && user[i] != 0; i++) {
  4949. if (iscntrl(user[i])) {
  4950. return 0;
  4951. }
  4952. }
  4953. if (user[i]) {
  4954. return 0;
  4955. }
  4956. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4957. if (iscntrl(domain[i])) {
  4958. return 0;
  4959. }
  4960. }
  4961. if (domain[i]) {
  4962. return 0;
  4963. }
  4964. /* The maximum length of the path to the password file is limited */
  4965. if ((strlen(fname) + 4) >= PATH_MAX) {
  4966. return 0;
  4967. }
  4968. /* Create a temporary file name. Length has been checked before. */
  4969. strcpy(tmp, fname);
  4970. strcat(tmp, ".tmp");
  4971. /* Create the file if does not exist */
  4972. /* Use of fopen here is OK, since fname is only ASCII */
  4973. if ((fp = fopen(fname, "a+")) != NULL) {
  4974. (void)fclose(fp);
  4975. }
  4976. /* Open the given file and temporary file */
  4977. if ((fp = fopen(fname, "r")) == NULL) {
  4978. return 0;
  4979. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4980. fclose(fp);
  4981. return 0;
  4982. }
  4983. /* Copy the stuff to temporary file */
  4984. while (fgets(line, sizeof(line), fp) != NULL) {
  4985. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4986. continue;
  4987. }
  4988. u[255] = 0;
  4989. d[255] = 0;
  4990. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4991. found++;
  4992. if (pass != NULL) {
  4993. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4994. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4995. }
  4996. } else {
  4997. fprintf(fp2, "%s", line);
  4998. }
  4999. }
  5000. /* If new user, just add it */
  5001. if (!found && pass != NULL) {
  5002. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5003. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5004. }
  5005. /* Close files */
  5006. fclose(fp);
  5007. fclose(fp2);
  5008. /* Put the temp file in place of real file */
  5009. IGNORE_UNUSED_RESULT(remove(fname));
  5010. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5011. return 1;
  5012. }
  5013. static int
  5014. is_valid_port(unsigned long port)
  5015. {
  5016. return port < 0xffff;
  5017. }
  5018. static int
  5019. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5020. {
  5021. struct addrinfo hints, *res, *ressave;
  5022. int func_ret = 0;
  5023. int gai_ret;
  5024. memset(&hints, 0, sizeof(struct addrinfo));
  5025. hints.ai_family = af;
  5026. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5027. if (gai_ret != 0) {
  5028. /* gai_strerror could be used to convert gai_ret to a string */
  5029. /* POSIX return values: see
  5030. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5031. */
  5032. /* Windows return values: see
  5033. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5034. */
  5035. return 0;
  5036. }
  5037. ressave = res;
  5038. while (res) {
  5039. if (dstlen >= res->ai_addrlen) {
  5040. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5041. func_ret = 1;
  5042. }
  5043. res = res->ai_next;
  5044. }
  5045. freeaddrinfo(ressave);
  5046. return func_ret;
  5047. }
  5048. static int
  5049. connect_socket(struct mg_context *ctx /* may be NULL */,
  5050. const char *host,
  5051. int port,
  5052. int use_ssl,
  5053. char *ebuf,
  5054. size_t ebuf_len,
  5055. SOCKET *sock /* output: socket, must not be NULL */,
  5056. union usa *sa /* output: socket address, must not be NULL */
  5057. )
  5058. {
  5059. int ip_ver = 0;
  5060. *sock = INVALID_SOCKET;
  5061. memset(sa, 0, sizeof(*sa));
  5062. if (ebuf_len > 0) {
  5063. *ebuf = 0;
  5064. }
  5065. if (host == NULL) {
  5066. mg_snprintf(NULL,
  5067. NULL, /* No truncation check for ebuf */
  5068. ebuf,
  5069. ebuf_len,
  5070. "%s",
  5071. "NULL host");
  5072. return 0;
  5073. }
  5074. if (port < 0 || !is_valid_port((unsigned)port)) {
  5075. mg_snprintf(NULL,
  5076. NULL, /* No truncation check for ebuf */
  5077. ebuf,
  5078. ebuf_len,
  5079. "%s",
  5080. "invalid port");
  5081. return 0;
  5082. }
  5083. #if !defined(NO_SSL)
  5084. if (use_ssl && (SSLv23_client_method == NULL)) {
  5085. mg_snprintf(NULL,
  5086. NULL, /* No truncation check for ebuf */
  5087. ebuf,
  5088. ebuf_len,
  5089. "%s",
  5090. "SSL is not initialized");
  5091. return 0;
  5092. }
  5093. #else
  5094. (void)use_ssl;
  5095. #endif
  5096. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5097. sa->sin.sin_port = htons((uint16_t)port);
  5098. ip_ver = 4;
  5099. #ifdef USE_IPV6
  5100. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5101. sa->sin6.sin6_port = htons((uint16_t)port);
  5102. ip_ver = 6;
  5103. } else if (host[0] == '[') {
  5104. /* While getaddrinfo on Windows will work with [::1],
  5105. * getaddrinfo on Linux only works with ::1 (without []). */
  5106. size_t l = strlen(host + 1);
  5107. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  5108. if (h) {
  5109. h[l - 1] = 0;
  5110. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5111. sa->sin6.sin6_port = htons((uint16_t)port);
  5112. ip_ver = 6;
  5113. }
  5114. mg_free(h);
  5115. }
  5116. #endif
  5117. }
  5118. if (ip_ver == 0) {
  5119. mg_snprintf(NULL,
  5120. NULL, /* No truncation check for ebuf */
  5121. ebuf,
  5122. ebuf_len,
  5123. "%s",
  5124. "host not found");
  5125. return 0;
  5126. }
  5127. if (ip_ver == 4) {
  5128. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5129. }
  5130. #ifdef USE_IPV6
  5131. else if (ip_ver == 6) {
  5132. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5133. }
  5134. #endif
  5135. if (*sock == INVALID_SOCKET) {
  5136. mg_snprintf(NULL,
  5137. NULL, /* No truncation check for ebuf */
  5138. ebuf,
  5139. ebuf_len,
  5140. "socket(): %s",
  5141. strerror(ERRNO));
  5142. return 0;
  5143. }
  5144. set_close_on_exec(*sock, fc(ctx));
  5145. if ((ip_ver == 4)
  5146. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5147. == 0)) {
  5148. /* connected with IPv4 */
  5149. return 1;
  5150. }
  5151. #ifdef USE_IPV6
  5152. if ((ip_ver == 6)
  5153. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5154. == 0)) {
  5155. /* connected with IPv6 */
  5156. return 1;
  5157. }
  5158. #endif
  5159. /* Not connected */
  5160. mg_snprintf(NULL,
  5161. NULL, /* No truncation check for ebuf */
  5162. ebuf,
  5163. ebuf_len,
  5164. "connect(%s:%d): %s",
  5165. host,
  5166. port,
  5167. strerror(ERRNO));
  5168. closesocket(*sock);
  5169. *sock = INVALID_SOCKET;
  5170. return 0;
  5171. }
  5172. int
  5173. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5174. {
  5175. static const char *dont_escape = "._-$,;~()";
  5176. static const char *hex = "0123456789abcdef";
  5177. char *pos = dst;
  5178. const char *end = dst + dst_len - 1;
  5179. for (; *src != '\0' && pos < end; src++, pos++) {
  5180. if (isalnum(*(const unsigned char *)src)
  5181. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5182. *pos = *src;
  5183. } else if (pos + 2 < end) {
  5184. pos[0] = '%';
  5185. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5186. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5187. pos += 2;
  5188. } else {
  5189. break;
  5190. }
  5191. }
  5192. *pos = '\0';
  5193. return (*src == '\0') ? (int)(pos - dst) : -1;
  5194. }
  5195. static void
  5196. print_dir_entry(struct de *de)
  5197. {
  5198. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5199. struct tm *tm;
  5200. if (de->file.is_directory) {
  5201. mg_snprintf(de->conn,
  5202. NULL, /* Buffer is big enough */
  5203. size,
  5204. sizeof(size),
  5205. "%s",
  5206. "[DIRECTORY]");
  5207. } else {
  5208. /* We use (signed) cast below because MSVC 6 compiler cannot
  5209. * convert unsigned __int64 to double. Sigh. */
  5210. if (de->file.size < 1024) {
  5211. mg_snprintf(de->conn,
  5212. NULL, /* Buffer is big enough */
  5213. size,
  5214. sizeof(size),
  5215. "%d",
  5216. (int)de->file.size);
  5217. } else if (de->file.size < 0x100000) {
  5218. mg_snprintf(de->conn,
  5219. NULL, /* Buffer is big enough */
  5220. size,
  5221. sizeof(size),
  5222. "%.1fk",
  5223. (double)de->file.size / 1024.0);
  5224. } else if (de->file.size < 0x40000000) {
  5225. mg_snprintf(de->conn,
  5226. NULL, /* Buffer is big enough */
  5227. size,
  5228. sizeof(size),
  5229. "%.1fM",
  5230. (double)de->file.size / 1048576);
  5231. } else {
  5232. mg_snprintf(de->conn,
  5233. NULL, /* Buffer is big enough */
  5234. size,
  5235. sizeof(size),
  5236. "%.1fG",
  5237. (double)de->file.size / 1073741824);
  5238. }
  5239. }
  5240. /* Note: mg_snprintf will not cause a buffer overflow above.
  5241. * So, string truncation checks are not required here. */
  5242. tm = localtime(&de->file.last_modified);
  5243. if (tm != NULL) {
  5244. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5245. } else {
  5246. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5247. mod[sizeof(mod) - 1] = '\0';
  5248. }
  5249. mg_url_encode(de->file_name, href, sizeof(href));
  5250. de->conn->num_bytes_sent +=
  5251. mg_printf(de->conn,
  5252. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5253. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5254. de->conn->request_info.local_uri,
  5255. href,
  5256. de->file.is_directory ? "/" : "",
  5257. de->file_name,
  5258. de->file.is_directory ? "/" : "",
  5259. mod,
  5260. size);
  5261. }
  5262. /* This function is called from send_directory() and used for
  5263. * sorting directory entries by size, or name, or modification time.
  5264. * On windows, __cdecl specification is needed in case if project is built
  5265. * with __stdcall convention. qsort always requires __cdels callback. */
  5266. static int WINCDECL
  5267. compare_dir_entries(const void *p1, const void *p2)
  5268. {
  5269. if (p1 && p2) {
  5270. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5271. const char *query_string = a->conn->request_info.query_string;
  5272. int cmp_result = 0;
  5273. if (query_string == NULL) {
  5274. query_string = "na";
  5275. }
  5276. if (a->file.is_directory && !b->file.is_directory) {
  5277. return -1; /* Always put directories on top */
  5278. } else if (!a->file.is_directory && b->file.is_directory) {
  5279. return 1; /* Always put directories on top */
  5280. } else if (*query_string == 'n') {
  5281. cmp_result = strcmp(a->file_name, b->file_name);
  5282. } else if (*query_string == 's') {
  5283. cmp_result = a->file.size == b->file.size
  5284. ? 0
  5285. : a->file.size > b->file.size ? 1 : -1;
  5286. } else if (*query_string == 'd') {
  5287. cmp_result =
  5288. (a->file.last_modified == b->file.last_modified)
  5289. ? 0
  5290. : ((a->file.last_modified > b->file.last_modified) ? 1
  5291. : -1);
  5292. }
  5293. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5294. }
  5295. return 0;
  5296. }
  5297. static int
  5298. must_hide_file(struct mg_connection *conn, const char *path)
  5299. {
  5300. if (conn && conn->ctx) {
  5301. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5302. const char *pattern = conn->ctx->config[HIDE_FILES];
  5303. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5304. || (pattern != NULL
  5305. && match_prefix(pattern, strlen(pattern), path) > 0);
  5306. }
  5307. return 0;
  5308. }
  5309. static int
  5310. scan_directory(struct mg_connection *conn,
  5311. const char *dir,
  5312. void *data,
  5313. void (*cb)(struct de *, void *))
  5314. {
  5315. char path[PATH_MAX];
  5316. struct dirent *dp;
  5317. DIR *dirp;
  5318. struct de de;
  5319. int truncated;
  5320. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5321. return 0;
  5322. } else {
  5323. de.conn = conn;
  5324. while ((dp = mg_readdir(dirp)) != NULL) {
  5325. /* Do not show current dir and hidden files */
  5326. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5327. || must_hide_file(conn, dp->d_name)) {
  5328. continue;
  5329. }
  5330. mg_snprintf(
  5331. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5332. /* If we don't memset stat structure to zero, mtime will have
  5333. * garbage and strftime() will segfault later on in
  5334. * print_dir_entry(). memset is required only if mg_stat()
  5335. * fails. For more details, see
  5336. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5337. memset(&de.file, 0, sizeof(de.file));
  5338. if (truncated) {
  5339. /* If the path is not complete, skip processing. */
  5340. continue;
  5341. }
  5342. if (!mg_stat(conn, path, &de.file)) {
  5343. mg_cry(conn,
  5344. "%s: mg_stat(%s) failed: %s",
  5345. __func__,
  5346. path,
  5347. strerror(ERRNO));
  5348. }
  5349. de.file_name = dp->d_name;
  5350. cb(&de, data);
  5351. }
  5352. (void)mg_closedir(dirp);
  5353. }
  5354. return 1;
  5355. }
  5356. #if !defined(NO_FILES)
  5357. static int
  5358. remove_directory(struct mg_connection *conn, const char *dir)
  5359. {
  5360. char path[PATH_MAX];
  5361. struct dirent *dp;
  5362. DIR *dirp;
  5363. struct de de;
  5364. int truncated;
  5365. int ok = 1;
  5366. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5367. return 0;
  5368. } else {
  5369. de.conn = conn;
  5370. while ((dp = mg_readdir(dirp)) != NULL) {
  5371. /* Do not show current dir (but show hidden files as they will
  5372. * also be removed) */
  5373. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5374. continue;
  5375. }
  5376. mg_snprintf(
  5377. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5378. /* If we don't memset stat structure to zero, mtime will have
  5379. * garbage and strftime() will segfault later on in
  5380. * print_dir_entry(). memset is required only if mg_stat()
  5381. * fails. For more details, see
  5382. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5383. memset(&de.file, 0, sizeof(de.file));
  5384. if (truncated) {
  5385. /* Do not delete anything shorter */
  5386. ok = 0;
  5387. continue;
  5388. }
  5389. if (!mg_stat(conn, path, &de.file)) {
  5390. mg_cry(conn,
  5391. "%s: mg_stat(%s) failed: %s",
  5392. __func__,
  5393. path,
  5394. strerror(ERRNO));
  5395. ok = 0;
  5396. }
  5397. if (de.file.membuf == NULL) {
  5398. /* file is not in memory */
  5399. if (de.file.is_directory) {
  5400. if (remove_directory(conn, path) == 0) {
  5401. ok = 0;
  5402. }
  5403. } else {
  5404. if (mg_remove(conn, path) == 0) {
  5405. ok = 0;
  5406. }
  5407. }
  5408. } else {
  5409. /* file is in memory. It can not be deleted. */
  5410. ok = 0;
  5411. }
  5412. }
  5413. (void)mg_closedir(dirp);
  5414. IGNORE_UNUSED_RESULT(rmdir(dir));
  5415. }
  5416. return ok;
  5417. }
  5418. #endif
  5419. struct dir_scan_data {
  5420. struct de *entries;
  5421. unsigned int num_entries;
  5422. unsigned int arr_size;
  5423. };
  5424. /* Behaves like realloc(), but frees original pointer on failure */
  5425. static void *
  5426. realloc2(void *ptr, size_t size)
  5427. {
  5428. void *new_ptr = mg_realloc(ptr, size);
  5429. if (new_ptr == NULL) {
  5430. mg_free(ptr);
  5431. }
  5432. return new_ptr;
  5433. }
  5434. static void
  5435. dir_scan_callback(struct de *de, void *data)
  5436. {
  5437. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5438. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5439. dsd->arr_size *= 2;
  5440. dsd->entries =
  5441. (struct de *)realloc2(dsd->entries,
  5442. dsd->arr_size * sizeof(dsd->entries[0]));
  5443. }
  5444. if (dsd->entries == NULL) {
  5445. /* TODO(lsm, low): propagate an error to the caller */
  5446. dsd->num_entries = 0;
  5447. } else {
  5448. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5449. dsd->entries[dsd->num_entries].file = de->file;
  5450. dsd->entries[dsd->num_entries].conn = de->conn;
  5451. dsd->num_entries++;
  5452. }
  5453. }
  5454. static void
  5455. handle_directory_request(struct mg_connection *conn, const char *dir)
  5456. {
  5457. unsigned int i;
  5458. int sort_direction;
  5459. struct dir_scan_data data = {NULL, 0, 128};
  5460. char date[64];
  5461. time_t curtime = time(NULL);
  5462. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5463. send_http_error(conn,
  5464. 500,
  5465. "Error: Cannot open directory\nopendir(%s): %s",
  5466. dir,
  5467. strerror(ERRNO));
  5468. return;
  5469. }
  5470. gmt_time_string(date, sizeof(date), &curtime);
  5471. if (!conn) {
  5472. return;
  5473. }
  5474. sort_direction = conn->request_info.query_string != NULL
  5475. && conn->request_info.query_string[1] == 'd'
  5476. ? 'a'
  5477. : 'd';
  5478. conn->must_close = 1;
  5479. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5480. send_static_cache_header(conn);
  5481. mg_printf(conn,
  5482. "Date: %s\r\n"
  5483. "Connection: close\r\n"
  5484. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5485. date);
  5486. conn->num_bytes_sent +=
  5487. mg_printf(conn,
  5488. "<html><head><title>Index of %s</title>"
  5489. "<style>th {text-align: left;}</style></head>"
  5490. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5491. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5492. "<th><a href=\"?d%c\">Modified</a></th>"
  5493. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5494. "<tr><td colspan=\"3\"><hr></td></tr>",
  5495. conn->request_info.local_uri,
  5496. conn->request_info.local_uri,
  5497. sort_direction,
  5498. sort_direction,
  5499. sort_direction);
  5500. /* Print first entry - link to a parent directory */
  5501. conn->num_bytes_sent +=
  5502. mg_printf(conn,
  5503. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5504. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5505. conn->request_info.local_uri,
  5506. "..",
  5507. "Parent directory",
  5508. "-",
  5509. "-");
  5510. /* Sort and print directory entries */
  5511. if (data.entries != NULL) {
  5512. qsort(data.entries,
  5513. (size_t)data.num_entries,
  5514. sizeof(data.entries[0]),
  5515. compare_dir_entries);
  5516. for (i = 0; i < data.num_entries; i++) {
  5517. print_dir_entry(&data.entries[i]);
  5518. mg_free(data.entries[i].file_name);
  5519. }
  5520. mg_free(data.entries);
  5521. }
  5522. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5523. conn->status_code = 200;
  5524. }
  5525. /* Send len bytes from the opened file to the client. */
  5526. static void
  5527. send_file_data(struct mg_connection *conn,
  5528. struct file *filep,
  5529. int64_t offset,
  5530. int64_t len)
  5531. {
  5532. char buf[MG_BUF_LEN];
  5533. int to_read, num_read, num_written;
  5534. int64_t size;
  5535. if (!filep || !conn) {
  5536. return;
  5537. }
  5538. /* Sanity check the offset */
  5539. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5540. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5541. if (len > 0 && filep->membuf != NULL && size > 0) {
  5542. /* file stored in memory */
  5543. if (len > size - offset) {
  5544. len = size - offset;
  5545. }
  5546. mg_write(conn, filep->membuf + offset, (size_t)len);
  5547. } else if (len > 0 && filep->fp != NULL) {
  5548. /* file stored on disk */
  5549. #if defined(__linux__)
  5550. /* sendfile is only available for Linux */
  5551. if (conn->throttle == 0 && conn->ssl == 0) {
  5552. off_t sf_offs = (off_t)offset;
  5553. ssize_t sf_sent;
  5554. int sf_file = fileno(filep->fp);
  5555. int loop_cnt = 0;
  5556. do {
  5557. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5558. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5559. size_t sf_tosend =
  5560. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5561. sf_sent =
  5562. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5563. if (sf_sent > 0) {
  5564. conn->num_bytes_sent += sf_sent;
  5565. len -= sf_sent;
  5566. offset += sf_sent;
  5567. } else if (loop_cnt == 0) {
  5568. /* This file can not be sent using sendfile.
  5569. * This might be the case for pseudo-files in the
  5570. * /sys/ and /proc/ file system.
  5571. * Use the regular user mode copy code instead. */
  5572. break;
  5573. } else if (sf_sent == 0) {
  5574. /* No error, but 0 bytes sent. May be EOF? */
  5575. return;
  5576. }
  5577. loop_cnt++;
  5578. } while ((len > 0) && (sf_sent >= 0));
  5579. if (sf_sent > 0) {
  5580. return; /* OK */
  5581. }
  5582. /* sf_sent<0 means error, thus fall back to the classic way */
  5583. /* This is always the case, if sf_file is not a "normal" file,
  5584. * e.g., for sending data from the output of a CGI process. */
  5585. offset = (int64_t)sf_offs;
  5586. }
  5587. #endif
  5588. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5589. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5590. send_http_error(
  5591. conn,
  5592. 500,
  5593. "%s",
  5594. "Error: Unable to access file at requested position.");
  5595. } else {
  5596. while (len > 0) {
  5597. /* Calculate how much to read from the file in the buffer */
  5598. to_read = sizeof(buf);
  5599. if ((int64_t)to_read > len) {
  5600. to_read = (int)len;
  5601. }
  5602. /* Read from file, exit the loop on error */
  5603. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5604. <= 0) {
  5605. break;
  5606. }
  5607. /* Send read bytes to the client, exit the loop on error */
  5608. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5609. != num_read) {
  5610. break;
  5611. }
  5612. /* Both read and were successful, adjust counters */
  5613. conn->num_bytes_sent += num_written;
  5614. len -= num_written;
  5615. }
  5616. }
  5617. }
  5618. }
  5619. static int
  5620. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5621. {
  5622. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5623. }
  5624. static void
  5625. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5626. {
  5627. if (filep != NULL && buf != NULL) {
  5628. mg_snprintf(NULL,
  5629. NULL, /* All calls to construct_etag use 64 byte buffer */
  5630. buf,
  5631. buf_len,
  5632. "\"%lx.%" INT64_FMT "\"",
  5633. (unsigned long)filep->last_modified,
  5634. filep->size);
  5635. }
  5636. }
  5637. static void
  5638. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5639. {
  5640. if (filep != NULL && filep->fp != NULL) {
  5641. #ifdef _WIN32
  5642. (void)conn; /* Unused. */
  5643. #else
  5644. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5645. mg_cry(conn,
  5646. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5647. __func__,
  5648. strerror(ERRNO));
  5649. }
  5650. #endif
  5651. }
  5652. }
  5653. static void
  5654. handle_static_file_request(struct mg_connection *conn,
  5655. const char *path,
  5656. struct file *filep,
  5657. const char *mime_type)
  5658. {
  5659. char date[64], lm[64], etag[64];
  5660. char range[128]; /* large enough, so there will be no overflow */
  5661. const char *msg = "OK", *hdr;
  5662. time_t curtime = time(NULL);
  5663. int64_t cl, r1, r2;
  5664. struct vec mime_vec;
  5665. int n, truncated;
  5666. char gz_path[PATH_MAX];
  5667. const char *encoding = "";
  5668. const char *cors1, *cors2, *cors3;
  5669. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5670. return;
  5671. }
  5672. if (mime_type == NULL) {
  5673. get_mime_type(conn->ctx, path, &mime_vec);
  5674. } else {
  5675. mime_vec.ptr = mime_type;
  5676. mime_vec.len = strlen(mime_type);
  5677. }
  5678. if (filep->size > INT64_MAX) {
  5679. send_http_error(conn,
  5680. 500,
  5681. "Error: File size is too large to send\n%" INT64_FMT,
  5682. filep->size);
  5683. }
  5684. cl = (int64_t)filep->size;
  5685. conn->status_code = 200;
  5686. range[0] = '\0';
  5687. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5688. * it's important to rewrite the filename after resolving
  5689. * the mime type from it, to preserve the actual file's type */
  5690. if (filep->gzipped) {
  5691. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5692. if (truncated) {
  5693. send_http_error(conn,
  5694. 500,
  5695. "Error: Path of zipped file too long (%s)",
  5696. path);
  5697. return;
  5698. }
  5699. path = gz_path;
  5700. encoding = "Content-Encoding: gzip\r\n";
  5701. }
  5702. if (!mg_fopen(conn, path, "rb", filep)) {
  5703. send_http_error(conn,
  5704. 500,
  5705. "Error: Cannot open file\nfopen(%s): %s",
  5706. path,
  5707. strerror(ERRNO));
  5708. return;
  5709. }
  5710. fclose_on_exec(filep, conn);
  5711. /* If Range: header specified, act accordingly */
  5712. r1 = r2 = 0;
  5713. hdr = mg_get_header(conn, "Range");
  5714. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5715. && r2 >= 0) {
  5716. /* actually, range requests don't play well with a pre-gzipped
  5717. * file (since the range is specified in the uncompressed space) */
  5718. if (filep->gzipped) {
  5719. send_http_error(
  5720. conn,
  5721. 501,
  5722. "%s",
  5723. "Error: Range requests in gzipped files are not supported");
  5724. mg_fclose(filep);
  5725. return;
  5726. }
  5727. conn->status_code = 206;
  5728. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5729. mg_snprintf(conn,
  5730. NULL, /* range buffer is big enough */
  5731. range,
  5732. sizeof(range),
  5733. "Content-Range: bytes "
  5734. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5735. r1,
  5736. r1 + cl - 1,
  5737. filep->size);
  5738. msg = "Partial Content";
  5739. }
  5740. hdr = mg_get_header(conn, "Origin");
  5741. if (hdr) {
  5742. /* Cross-origin resource sharing (CORS), see
  5743. * http://www.html5rocks.com/en/tutorials/cors/,
  5744. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5745. * preflight is not supported for files. */
  5746. cors1 = "Access-Control-Allow-Origin: ";
  5747. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5748. cors3 = "\r\n";
  5749. } else {
  5750. cors1 = cors2 = cors3 = "";
  5751. }
  5752. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5753. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5754. gmt_time_string(date, sizeof(date), &curtime);
  5755. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5756. construct_etag(etag, sizeof(etag), filep);
  5757. (void)mg_printf(conn,
  5758. "HTTP/1.1 %d %s\r\n"
  5759. "%s%s%s"
  5760. "Date: %s\r\n",
  5761. conn->status_code,
  5762. msg,
  5763. cors1,
  5764. cors2,
  5765. cors3,
  5766. date);
  5767. send_static_cache_header(conn);
  5768. (void)mg_printf(conn,
  5769. "Last-Modified: %s\r\n"
  5770. "Etag: %s\r\n"
  5771. "Content-Type: %.*s\r\n"
  5772. "Content-Length: %" INT64_FMT "\r\n"
  5773. "Connection: %s\r\n"
  5774. "Accept-Ranges: bytes\r\n"
  5775. "%s%s\r\n",
  5776. lm,
  5777. etag,
  5778. (int)mime_vec.len,
  5779. mime_vec.ptr,
  5780. cl,
  5781. suggest_connection_header(conn),
  5782. range,
  5783. encoding);
  5784. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5785. send_file_data(conn, filep, r1, cl);
  5786. }
  5787. mg_fclose(filep);
  5788. }
  5789. static void
  5790. handle_not_modified_static_file_request(struct mg_connection *conn,
  5791. struct file *filep)
  5792. {
  5793. char date[64], lm[64], etag[64];
  5794. time_t curtime = time(NULL);
  5795. if (conn == NULL || filep == NULL) {
  5796. return;
  5797. }
  5798. conn->status_code = 304;
  5799. gmt_time_string(date, sizeof(date), &curtime);
  5800. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5801. construct_etag(etag, sizeof(etag), filep);
  5802. (void)mg_printf(conn,
  5803. "HTTP/1.1 %d %s\r\n"
  5804. "Date: %s\r\n",
  5805. conn->status_code,
  5806. mg_get_response_code_text(conn, conn->status_code),
  5807. date);
  5808. send_static_cache_header(conn);
  5809. (void)mg_printf(conn,
  5810. "Last-Modified: %s\r\n"
  5811. "Etag: %s\r\n"
  5812. "Connection: %s\r\n"
  5813. "\r\n",
  5814. lm,
  5815. etag,
  5816. suggest_connection_header(conn));
  5817. }
  5818. void
  5819. mg_send_file(struct mg_connection *conn, const char *path)
  5820. {
  5821. mg_send_mime_file(conn, path, NULL);
  5822. }
  5823. void
  5824. mg_send_mime_file(struct mg_connection *conn,
  5825. const char *path,
  5826. const char *mime_type)
  5827. {
  5828. struct file file = STRUCT_FILE_INITIALIZER;
  5829. if (mg_stat(conn, path, &file)) {
  5830. if (file.is_directory) {
  5831. if (!conn) {
  5832. return;
  5833. }
  5834. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5835. "yes")) {
  5836. handle_directory_request(conn, path);
  5837. } else {
  5838. send_http_error(conn,
  5839. 403,
  5840. "%s",
  5841. "Error: Directory listing denied");
  5842. }
  5843. } else {
  5844. handle_static_file_request(conn, path, &file, mime_type);
  5845. }
  5846. } else {
  5847. send_http_error(conn, 404, "%s", "Error: File not found");
  5848. }
  5849. }
  5850. /* For a given PUT path, create all intermediate subdirectories.
  5851. * Return 0 if the path itself is a directory.
  5852. * Return 1 if the path leads to a file.
  5853. * Return -1 for if the path is too long.
  5854. * Return -2 if path can not be created.
  5855. */
  5856. static int
  5857. put_dir(struct mg_connection *conn, const char *path)
  5858. {
  5859. char buf[PATH_MAX];
  5860. const char *s, *p;
  5861. struct file file = STRUCT_FILE_INITIALIZER;
  5862. size_t len;
  5863. int res = 1;
  5864. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5865. len = (size_t)(p - path);
  5866. if (len >= sizeof(buf)) {
  5867. /* path too long */
  5868. res = -1;
  5869. break;
  5870. }
  5871. memcpy(buf, path, len);
  5872. buf[len] = '\0';
  5873. /* Try to create intermediate directory */
  5874. DEBUG_TRACE("mkdir(%s)", buf);
  5875. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  5876. /* path does not exixt and can not be created */
  5877. res = -2;
  5878. break;
  5879. }
  5880. /* Is path itself a directory? */
  5881. if (p[1] == '\0') {
  5882. res = 0;
  5883. }
  5884. }
  5885. return res;
  5886. }
  5887. static void
  5888. remove_bad_file(const struct mg_connection *conn, const char *path)
  5889. {
  5890. int r = mg_remove(conn, path);
  5891. if (r != 0) {
  5892. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5893. }
  5894. }
  5895. long long
  5896. mg_store_body(struct mg_connection *conn, const char *path)
  5897. {
  5898. char buf[MG_BUF_LEN];
  5899. long long len = 0;
  5900. int ret, n;
  5901. struct file fi;
  5902. if (conn->consumed_content != 0) {
  5903. mg_cry(conn, "%s: Contents already consumed", __func__);
  5904. return -11;
  5905. }
  5906. ret = put_dir(conn, path);
  5907. if (ret < 0) {
  5908. /* -1 for path too long,
  5909. * -2 for path can not be created. */
  5910. return ret;
  5911. }
  5912. if (ret != 1) {
  5913. /* Return 0 means, path itself is a directory. */
  5914. return 0;
  5915. }
  5916. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5917. return -12;
  5918. }
  5919. ret = mg_read(conn, buf, sizeof(buf));
  5920. while (ret > 0) {
  5921. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5922. if (n != ret) {
  5923. mg_fclose(&fi);
  5924. remove_bad_file(conn, path);
  5925. return -13;
  5926. }
  5927. ret = mg_read(conn, buf, sizeof(buf));
  5928. }
  5929. /* TODO: mg_fclose should return an error,
  5930. * and every caller should check and handle it. */
  5931. if (fclose(fi.fp) != 0) {
  5932. remove_bad_file(conn, path);
  5933. return -14;
  5934. }
  5935. return len;
  5936. }
  5937. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5938. * where parsing stopped. */
  5939. static void
  5940. parse_http_headers(char **buf, struct mg_request_info *ri)
  5941. {
  5942. int i;
  5943. if (!ri) {
  5944. return;
  5945. }
  5946. ri->num_headers = 0;
  5947. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5948. char *dp = *buf;
  5949. while ((*dp != ':') && (*dp >= 32) && (*dp <= 126)) {
  5950. dp++;
  5951. }
  5952. if ((dp == *buf) || (*dp != ':')) {
  5953. /* This is not a valid field. */
  5954. break;
  5955. } else {
  5956. /* (*dp == ':') */
  5957. *dp = 0;
  5958. ri->http_headers[i].name = *buf;
  5959. do {
  5960. dp++;
  5961. } while (*dp == ' ');
  5962. ri->http_headers[i].value = dp;
  5963. *buf = dp + strcspn(dp, "\r\n");
  5964. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  5965. *buf = NULL;
  5966. }
  5967. }
  5968. ri->num_headers = i + 1;
  5969. if (*buf) {
  5970. (*buf)[0] = 0;
  5971. (*buf)[1] = 0;
  5972. *buf += 2;
  5973. } else {
  5974. *buf = dp;
  5975. break;
  5976. }
  5977. if ((*buf)[0] == '\r') {
  5978. /* This is the end of the header */
  5979. break;
  5980. }
  5981. }
  5982. }
  5983. static int
  5984. is_valid_http_method(const char *method)
  5985. {
  5986. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5987. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5988. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5989. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5990. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5991. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5992. /* TRACE method (RFC 2616) is not supported for security reasons */
  5993. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5994. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5995. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5996. /* Unsupported WEBDAV Methods: */
  5997. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5998. /* + 11 methods from RFC 3253 */
  5999. /* ORDERPATCH (RFC 3648) */
  6000. /* ACL (RFC 3744) */
  6001. /* SEARCH (RFC 5323) */
  6002. /* + MicroSoft extensions
  6003. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6004. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6005. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6006. }
  6007. /* Parse HTTP request, fill in mg_request_info structure.
  6008. * This function modifies the buffer by NUL-terminating
  6009. * HTTP request components, header names and header values. */
  6010. static int
  6011. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6012. {
  6013. int is_request, request_length;
  6014. char *start_line;
  6015. if (!ri) {
  6016. return 0;
  6017. }
  6018. request_length = get_request_len(buf, len);
  6019. if (request_length > 0) {
  6020. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6021. * remote_port */
  6022. ri->remote_user = ri->request_method = ri->request_uri =
  6023. ri->http_version = NULL;
  6024. ri->num_headers = 0;
  6025. buf[request_length - 1] = '\0';
  6026. /* RFC says that all initial whitespaces should be ingored */
  6027. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6028. buf++;
  6029. }
  6030. start_line = skip(&buf, "\r\n");
  6031. ri->request_method = skip(&start_line, " ");
  6032. ri->request_uri = skip(&start_line, " ");
  6033. ri->http_version = start_line;
  6034. /* HTTP message could be either HTTP request or HTTP response, e.g.
  6035. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  6036. is_request = is_valid_http_method(ri->request_method);
  6037. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6038. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6039. request_length = -1;
  6040. } else {
  6041. if (is_request) {
  6042. ri->http_version += 5;
  6043. }
  6044. parse_http_headers(&buf, ri);
  6045. }
  6046. }
  6047. return request_length;
  6048. }
  6049. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6050. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6051. * buffer (which marks the end of HTTP request). Buffer buf may already
  6052. * have some data. The length of the data is stored in nread.
  6053. * Upon every read operation, increase nread by the number of bytes read. */
  6054. static int
  6055. read_request(FILE *fp,
  6056. struct mg_connection *conn,
  6057. char *buf,
  6058. int bufsiz,
  6059. int *nread)
  6060. {
  6061. int request_len, n = 0;
  6062. struct timespec last_action_time;
  6063. double request_timeout;
  6064. if (!conn) {
  6065. return 0;
  6066. }
  6067. memset(&last_action_time, 0, sizeof(last_action_time));
  6068. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6069. /* value of request_timeout is in seconds, config in milliseconds */
  6070. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6071. } else {
  6072. request_timeout = -1.0;
  6073. }
  6074. request_len = get_request_len(buf, *nread);
  6075. /* first time reading from this connection */
  6076. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6077. while (
  6078. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6079. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6080. <= request_timeout) || (request_timeout < 0))
  6081. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6082. > 0)) {
  6083. *nread += n;
  6084. /* assert(*nread <= bufsiz); */
  6085. if (*nread > bufsiz) {
  6086. return -2;
  6087. }
  6088. request_len = get_request_len(buf, *nread);
  6089. if (request_timeout > 0.0) {
  6090. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6091. }
  6092. }
  6093. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  6094. }
  6095. #if !defined(NO_FILES)
  6096. /* For given directory path, substitute it to valid index file.
  6097. * Return 1 if index file has been found, 0 if not found.
  6098. * If the file is found, it's stats is returned in stp. */
  6099. static int
  6100. substitute_index_file(struct mg_connection *conn,
  6101. char *path,
  6102. size_t path_len,
  6103. struct file *filep)
  6104. {
  6105. if (conn && conn->ctx) {
  6106. const char *list = conn->ctx->config[INDEX_FILES];
  6107. struct file file = STRUCT_FILE_INITIALIZER;
  6108. struct vec filename_vec;
  6109. size_t n = strlen(path);
  6110. int found = 0;
  6111. /* The 'path' given to us points to the directory. Remove all trailing
  6112. * directory separator characters from the end of the path, and
  6113. * then append single directory separator character. */
  6114. while (n > 0 && path[n - 1] == '/') {
  6115. n--;
  6116. }
  6117. path[n] = '/';
  6118. /* Traverse index files list. For each entry, append it to the given
  6119. * path and see if the file exists. If it exists, break the loop */
  6120. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6121. /* Ignore too long entries that may overflow path buffer */
  6122. if (filename_vec.len > path_len - (n + 2)) {
  6123. continue;
  6124. }
  6125. /* Prepare full path to the index file */
  6126. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6127. /* Does it exist? */
  6128. if (mg_stat(conn, path, &file)) {
  6129. /* Yes it does, break the loop */
  6130. *filep = file;
  6131. found = 1;
  6132. break;
  6133. }
  6134. }
  6135. /* If no index file exists, restore directory path */
  6136. if (!found) {
  6137. path[n] = '\0';
  6138. }
  6139. return found;
  6140. }
  6141. return 0;
  6142. }
  6143. #endif
  6144. #if !defined(NO_CACHING)
  6145. /* Return True if we should reply 304 Not Modified. */
  6146. static int
  6147. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6148. {
  6149. char etag[64];
  6150. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6151. const char *inm = mg_get_header(conn, "If-None-Match");
  6152. construct_etag(etag, sizeof(etag), filep);
  6153. if (!filep) {
  6154. return 0;
  6155. }
  6156. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6157. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6158. }
  6159. #endif /* !NO_CACHING */
  6160. #if !defined(NO_CGI) || !defined(NO_FILES)
  6161. static int
  6162. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6163. {
  6164. const char *expect, *body;
  6165. char buf[MG_BUF_LEN];
  6166. int to_read, nread, success = 0;
  6167. int64_t buffered_len;
  6168. double timeout = -1.0;
  6169. if (!conn) {
  6170. return 0;
  6171. }
  6172. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6173. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6174. }
  6175. expect = mg_get_header(conn, "Expect");
  6176. /* assert(fp != NULL); */
  6177. if (!fp) {
  6178. send_http_error(conn, 500, "%s", "Error: NULL File");
  6179. return 0;
  6180. }
  6181. if (conn->content_len == -1 && !conn->is_chunked) {
  6182. /* Content length is not specified by the client. */
  6183. send_http_error(conn,
  6184. 411,
  6185. "%s",
  6186. "Error: Client did not specify content length");
  6187. } else if ((expect != NULL)
  6188. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6189. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6190. send_http_error(conn,
  6191. 417,
  6192. "Error: Can not fulfill expectation %s",
  6193. expect);
  6194. } else {
  6195. if (expect != NULL) {
  6196. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6197. conn->status_code = 100;
  6198. } else {
  6199. conn->status_code = 200;
  6200. }
  6201. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6202. - conn->consumed_content;
  6203. /* assert(buffered_len >= 0); */
  6204. /* assert(conn->consumed_content == 0); */
  6205. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6206. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6207. return 0;
  6208. }
  6209. if (buffered_len > 0) {
  6210. if ((int64_t)buffered_len > conn->content_len) {
  6211. buffered_len = (int)conn->content_len;
  6212. }
  6213. body = conn->buf + conn->request_len + conn->consumed_content;
  6214. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6215. conn->consumed_content += buffered_len;
  6216. }
  6217. nread = 0;
  6218. while (conn->consumed_content < conn->content_len) {
  6219. to_read = sizeof(buf);
  6220. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6221. to_read = (int)(conn->content_len - conn->consumed_content);
  6222. }
  6223. nread = pull(NULL, conn, buf, to_read, timeout);
  6224. if (nread <= 0
  6225. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6226. break;
  6227. }
  6228. conn->consumed_content += nread;
  6229. }
  6230. if (conn->consumed_content == conn->content_len) {
  6231. success = (nread >= 0);
  6232. }
  6233. /* Each error code path in this function must send an error */
  6234. if (!success) {
  6235. /* NOTE: Maybe some data has already been sent. */
  6236. /* TODO (low): If some data has been sent, a correct error
  6237. * reply can no longer be sent, so just close the connection */
  6238. send_http_error(conn, 500, "%s", "");
  6239. }
  6240. }
  6241. return success;
  6242. }
  6243. #endif
  6244. #if !defined(NO_CGI)
  6245. /* This structure helps to create an environment for the spawned CGI program.
  6246. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6247. * last element must be NULL.
  6248. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6249. * strings must reside in a contiguous buffer. The end of the buffer is
  6250. * marked by two '\0' characters.
  6251. * We satisfy both worlds: we create an envp array (which is vars), all
  6252. * entries are actually pointers inside buf. */
  6253. struct cgi_environment {
  6254. struct mg_connection *conn;
  6255. /* Data block */
  6256. char *buf; /* Environment buffer */
  6257. size_t buflen; /* Space available in buf */
  6258. size_t bufused; /* Space taken in buf */
  6259. /* Index block */
  6260. char **var; /* char **envp */
  6261. size_t varlen; /* Number of variables available in var */
  6262. size_t varused; /* Number of variables stored in var */
  6263. };
  6264. static void addenv(struct cgi_environment *env,
  6265. PRINTF_FORMAT_STRING(const char *fmt),
  6266. ...) PRINTF_ARGS(2, 3);
  6267. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6268. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6269. static void
  6270. addenv(struct cgi_environment *env, const char *fmt, ...)
  6271. {
  6272. size_t n, space;
  6273. int truncated;
  6274. char *added;
  6275. va_list ap;
  6276. /* Calculate how much space is left in the buffer */
  6277. space = (env->buflen - env->bufused);
  6278. /* Calculate an estimate for the required space */
  6279. n = strlen(fmt) + 2 + 128;
  6280. do {
  6281. if (space <= n) {
  6282. /* Allocate new buffer */
  6283. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6284. added = (char *)mg_realloc(env->buf, n);
  6285. if (!added) {
  6286. /* Out of memory */
  6287. mg_cry(env->conn,
  6288. "%s: Cannot allocate memory for CGI variable [%s]",
  6289. __func__,
  6290. fmt);
  6291. return;
  6292. }
  6293. env->buf = added;
  6294. env->buflen = n;
  6295. space = (env->buflen - env->bufused);
  6296. }
  6297. /* Make a pointer to the free space int the buffer */
  6298. added = env->buf + env->bufused;
  6299. /* Copy VARIABLE=VALUE\0 string into the free space */
  6300. va_start(ap, fmt);
  6301. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6302. va_end(ap);
  6303. /* Do not add truncated strings to the environment */
  6304. if (truncated) {
  6305. /* Reallocate the buffer */
  6306. space = 0;
  6307. n = 1;
  6308. }
  6309. } while (truncated);
  6310. /* Calculate number of bytes added to the environment */
  6311. n = strlen(added) + 1;
  6312. env->bufused += n;
  6313. /* Now update the variable index */
  6314. space = (env->varlen - env->varused);
  6315. if (space < 2) {
  6316. mg_cry(env->conn,
  6317. "%s: Cannot register CGI variable [%s]",
  6318. __func__,
  6319. fmt);
  6320. return;
  6321. }
  6322. /* Append a pointer to the added string into the envp array */
  6323. env->var[env->varused] = added;
  6324. env->varused++;
  6325. }
  6326. static void
  6327. prepare_cgi_environment(struct mg_connection *conn,
  6328. const char *prog,
  6329. struct cgi_environment *env)
  6330. {
  6331. const char *s;
  6332. struct vec var_vec;
  6333. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6334. int i, truncated;
  6335. if (conn == NULL || prog == NULL || env == NULL) {
  6336. return;
  6337. }
  6338. env->conn = conn;
  6339. env->buflen = CGI_ENVIRONMENT_SIZE;
  6340. env->bufused = 0;
  6341. env->buf = (char *)mg_malloc(env->buflen);
  6342. env->varlen = MAX_CGI_ENVIR_VARS;
  6343. env->varused = 0;
  6344. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6345. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6346. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6347. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6348. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6349. /* Prepare the environment block */
  6350. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6351. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6352. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6353. #if defined(USE_IPV6)
  6354. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6355. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6356. } else
  6357. #endif
  6358. {
  6359. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6360. }
  6361. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6362. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6363. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6364. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6365. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6366. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6367. /* SCRIPT_NAME */
  6368. addenv(env,
  6369. "SCRIPT_NAME=%.*s",
  6370. (int)strlen(conn->request_info.local_uri)
  6371. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6372. conn->request_info.local_uri);
  6373. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6374. if (conn->path_info == NULL) {
  6375. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6376. } else {
  6377. addenv(env,
  6378. "PATH_TRANSLATED=%s%s",
  6379. conn->ctx->config[DOCUMENT_ROOT],
  6380. conn->path_info);
  6381. }
  6382. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6383. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6384. addenv(env, "CONTENT_TYPE=%s", s);
  6385. }
  6386. if (conn->request_info.query_string != NULL) {
  6387. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6388. }
  6389. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6390. addenv(env, "CONTENT_LENGTH=%s", s);
  6391. }
  6392. if ((s = getenv("PATH")) != NULL) {
  6393. addenv(env, "PATH=%s", s);
  6394. }
  6395. if (conn->path_info != NULL) {
  6396. addenv(env, "PATH_INFO=%s", conn->path_info);
  6397. }
  6398. if (conn->status_code > 0) {
  6399. /* CGI error handler should show the status code */
  6400. addenv(env, "STATUS=%d", conn->status_code);
  6401. }
  6402. #if defined(_WIN32)
  6403. if ((s = getenv("COMSPEC")) != NULL) {
  6404. addenv(env, "COMSPEC=%s", s);
  6405. }
  6406. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6407. addenv(env, "SYSTEMROOT=%s", s);
  6408. }
  6409. if ((s = getenv("SystemDrive")) != NULL) {
  6410. addenv(env, "SystemDrive=%s", s);
  6411. }
  6412. if ((s = getenv("ProgramFiles")) != NULL) {
  6413. addenv(env, "ProgramFiles=%s", s);
  6414. }
  6415. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6416. addenv(env, "ProgramFiles(x86)=%s", s);
  6417. }
  6418. #else
  6419. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6420. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6421. }
  6422. #endif /* _WIN32 */
  6423. if ((s = getenv("PERLLIB")) != NULL) {
  6424. addenv(env, "PERLLIB=%s", s);
  6425. }
  6426. if (conn->request_info.remote_user != NULL) {
  6427. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6428. addenv(env, "%s", "AUTH_TYPE=Digest");
  6429. }
  6430. /* Add all headers as HTTP_* variables */
  6431. for (i = 0; i < conn->request_info.num_headers; i++) {
  6432. (void)mg_snprintf(conn,
  6433. &truncated,
  6434. http_var_name,
  6435. sizeof(http_var_name),
  6436. "HTTP_%s",
  6437. conn->request_info.http_headers[i].name);
  6438. if (truncated) {
  6439. mg_cry(conn,
  6440. "%s: HTTP header variable too long [%s]",
  6441. __func__,
  6442. conn->request_info.http_headers[i].name);
  6443. continue;
  6444. }
  6445. /* Convert variable name into uppercase, and change - to _ */
  6446. for (p = http_var_name; *p != '\0'; p++) {
  6447. if (*p == '-') {
  6448. *p = '_';
  6449. }
  6450. *p = (char)toupper(*(unsigned char *)p);
  6451. }
  6452. addenv(env,
  6453. "%s=%s",
  6454. http_var_name,
  6455. conn->request_info.http_headers[i].value);
  6456. }
  6457. /* Add user-specified variables */
  6458. s = conn->ctx->config[CGI_ENVIRONMENT];
  6459. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6460. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6461. }
  6462. env->var[env->varused] = NULL;
  6463. env->buf[env->bufused] = '\0';
  6464. }
  6465. static void
  6466. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6467. {
  6468. char *buf;
  6469. size_t buflen;
  6470. int headers_len, data_len, i, truncated;
  6471. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6472. const char *status, *status_text, *connection_state;
  6473. char *pbuf, dir[PATH_MAX], *p;
  6474. struct mg_request_info ri;
  6475. struct cgi_environment blk;
  6476. FILE *in = NULL, *out = NULL, *err = NULL;
  6477. struct file fout = STRUCT_FILE_INITIALIZER;
  6478. pid_t pid = (pid_t)-1;
  6479. if (conn == NULL) {
  6480. return;
  6481. }
  6482. buf = NULL;
  6483. buflen = 16384;
  6484. prepare_cgi_environment(conn, prog, &blk);
  6485. /* CGI must be executed in its own directory. 'dir' must point to the
  6486. * directory containing executable program, 'p' must point to the
  6487. * executable program name relative to 'dir'. */
  6488. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6489. if (truncated) {
  6490. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6491. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6492. goto done;
  6493. }
  6494. if ((p = strrchr(dir, '/')) != NULL) {
  6495. *p++ = '\0';
  6496. } else {
  6497. dir[0] = '.', dir[1] = '\0';
  6498. p = (char *)prog;
  6499. }
  6500. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6501. status = strerror(ERRNO);
  6502. mg_cry(conn,
  6503. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6504. prog,
  6505. status);
  6506. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6507. goto done;
  6508. }
  6509. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6510. if (pid == (pid_t)-1) {
  6511. status = strerror(ERRNO);
  6512. mg_cry(conn,
  6513. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6514. prog,
  6515. status);
  6516. send_http_error(conn,
  6517. 500,
  6518. "Error: Cannot spawn CGI process [%s]: %s",
  6519. prog,
  6520. status);
  6521. goto done;
  6522. }
  6523. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6524. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6525. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6526. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6527. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6528. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6529. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6530. /* Parent closes only one side of the pipes.
  6531. * If we don't mark them as closed, close() attempt before
  6532. * return from this function throws an exception on Windows.
  6533. * Windows does not like when closed descriptor is closed again. */
  6534. (void)close(fdin[0]);
  6535. (void)close(fdout[1]);
  6536. (void)close(fderr[1]);
  6537. fdin[0] = fdout[1] = fderr[1] = -1;
  6538. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6539. status = strerror(ERRNO);
  6540. mg_cry(conn,
  6541. "Error: CGI program \"%s\": Can not open stdin: %s",
  6542. prog,
  6543. status);
  6544. send_http_error(conn,
  6545. 500,
  6546. "Error: CGI can not open fdin\nfopen: %s",
  6547. status);
  6548. goto done;
  6549. }
  6550. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6551. status = strerror(ERRNO);
  6552. mg_cry(conn,
  6553. "Error: CGI program \"%s\": Can not open stdout: %s",
  6554. prog,
  6555. status);
  6556. send_http_error(conn,
  6557. 500,
  6558. "Error: CGI can not open fdout\nfopen: %s",
  6559. status);
  6560. goto done;
  6561. }
  6562. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6563. status = strerror(ERRNO);
  6564. mg_cry(conn,
  6565. "Error: CGI program \"%s\": Can not open stderr: %s",
  6566. prog,
  6567. status);
  6568. send_http_error(conn,
  6569. 500,
  6570. "Error: CGI can not open fdout\nfopen: %s",
  6571. status);
  6572. goto done;
  6573. }
  6574. setbuf(in, NULL);
  6575. setbuf(out, NULL);
  6576. setbuf(err, NULL);
  6577. fout.fp = out;
  6578. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6579. /* This is a POST/PUT request, or another request with body data. */
  6580. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6581. /* Error sending the body data */
  6582. mg_cry(conn,
  6583. "Error: CGI program \"%s\": Forward body data failed",
  6584. prog);
  6585. goto done;
  6586. }
  6587. }
  6588. /* Close so child gets an EOF. */
  6589. fclose(in);
  6590. in = NULL;
  6591. fdin[1] = -1;
  6592. /* Now read CGI reply into a buffer. We need to set correct
  6593. * status code, thus we need to see all HTTP headers first.
  6594. * Do not send anything back to client, until we buffer in all
  6595. * HTTP headers. */
  6596. data_len = 0;
  6597. buf = (char *)mg_malloc(buflen);
  6598. if (buf == NULL) {
  6599. send_http_error(conn,
  6600. 500,
  6601. "Error: Not enough memory for CGI buffer (%u bytes)",
  6602. (unsigned int)buflen);
  6603. mg_cry(conn,
  6604. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6605. "bytes)",
  6606. prog,
  6607. (unsigned int)buflen);
  6608. goto done;
  6609. }
  6610. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6611. if (headers_len <= 0) {
  6612. /* Could not parse the CGI response. Check if some error message on
  6613. * stderr. */
  6614. i = pull_all(err, conn, buf, (int)buflen);
  6615. if (i > 0) {
  6616. mg_cry(conn,
  6617. "Error: CGI program \"%s\" sent error "
  6618. "message: [%.*s]",
  6619. prog,
  6620. i,
  6621. buf);
  6622. send_http_error(conn,
  6623. 500,
  6624. "Error: CGI program \"%s\" sent error "
  6625. "message: [%.*s]",
  6626. prog,
  6627. i,
  6628. buf);
  6629. } else {
  6630. mg_cry(conn,
  6631. "Error: CGI program sent malformed or too big "
  6632. "(>%u bytes) HTTP headers: [%.*s]",
  6633. (unsigned)buflen,
  6634. data_len,
  6635. buf);
  6636. send_http_error(conn,
  6637. 500,
  6638. "Error: CGI program sent malformed or too big "
  6639. "(>%u bytes) HTTP headers: [%.*s]",
  6640. (unsigned)buflen,
  6641. data_len,
  6642. buf);
  6643. }
  6644. goto done;
  6645. }
  6646. pbuf = buf;
  6647. buf[headers_len - 1] = '\0';
  6648. parse_http_headers(&pbuf, &ri);
  6649. /* Make up and send the status line */
  6650. status_text = "OK";
  6651. if ((status = get_header(&ri, "Status")) != NULL) {
  6652. conn->status_code = atoi(status);
  6653. status_text = status;
  6654. while (isdigit(*(const unsigned char *)status_text)
  6655. || *status_text == ' ') {
  6656. status_text++;
  6657. }
  6658. } else if (get_header(&ri, "Location") != NULL) {
  6659. conn->status_code = 302;
  6660. } else {
  6661. conn->status_code = 200;
  6662. }
  6663. connection_state = get_header(&ri, "Connection");
  6664. if (!header_has_option(connection_state, "keep-alive")) {
  6665. conn->must_close = 1;
  6666. }
  6667. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6668. /* Send headers */
  6669. for (i = 0; i < ri.num_headers; i++) {
  6670. mg_printf(conn,
  6671. "%s: %s\r\n",
  6672. ri.http_headers[i].name,
  6673. ri.http_headers[i].value);
  6674. }
  6675. mg_write(conn, "\r\n", 2);
  6676. /* Send chunk of data that may have been read after the headers */
  6677. conn->num_bytes_sent +=
  6678. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6679. /* Read the rest of CGI output and send to the client */
  6680. send_file_data(conn, &fout, 0, INT64_MAX);
  6681. done:
  6682. mg_free(blk.var);
  6683. mg_free(blk.buf);
  6684. if (pid != (pid_t)-1) {
  6685. kill(pid, SIGKILL);
  6686. #if !defined(_WIN32)
  6687. {
  6688. int st;
  6689. while (waitpid(pid, &st, 0) != -1)
  6690. ; /* clean zombies */
  6691. }
  6692. #endif
  6693. }
  6694. if (fdin[0] != -1) {
  6695. close(fdin[0]);
  6696. }
  6697. if (fdout[1] != -1) {
  6698. close(fdout[1]);
  6699. }
  6700. if (in != NULL) {
  6701. fclose(in);
  6702. } else if (fdin[1] != -1) {
  6703. close(fdin[1]);
  6704. }
  6705. if (out != NULL) {
  6706. fclose(out);
  6707. } else if (fdout[0] != -1) {
  6708. close(fdout[0]);
  6709. }
  6710. if (err != NULL) {
  6711. fclose(err);
  6712. } else if (fderr[0] != -1) {
  6713. close(fderr[0]);
  6714. }
  6715. if (buf != NULL) {
  6716. mg_free(buf);
  6717. }
  6718. }
  6719. #endif /* !NO_CGI */
  6720. #if !defined(NO_FILES)
  6721. static void
  6722. mkcol(struct mg_connection *conn, const char *path)
  6723. {
  6724. int rc, body_len;
  6725. struct de de;
  6726. char date[64];
  6727. time_t curtime = time(NULL);
  6728. if (conn == NULL) {
  6729. return;
  6730. }
  6731. /* TODO (mid): Check the send_http_error situations in this function */
  6732. memset(&de.file, 0, sizeof(de.file));
  6733. if (!mg_stat(conn, path, &de.file)) {
  6734. mg_cry(conn,
  6735. "%s: mg_stat(%s) failed: %s",
  6736. __func__,
  6737. path,
  6738. strerror(ERRNO));
  6739. }
  6740. if (de.file.last_modified) {
  6741. /* TODO (high): This check does not seem to make any sense ! */
  6742. send_http_error(
  6743. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6744. return;
  6745. }
  6746. body_len = conn->data_len - conn->request_len;
  6747. if (body_len > 0) {
  6748. send_http_error(
  6749. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6750. return;
  6751. }
  6752. rc = mg_mkdir(conn, path, 0755);
  6753. if (rc == 0) {
  6754. conn->status_code = 201;
  6755. gmt_time_string(date, sizeof(date), &curtime);
  6756. mg_printf(conn,
  6757. "HTTP/1.1 %d Created\r\n"
  6758. "Date: %s\r\n",
  6759. conn->status_code,
  6760. date);
  6761. send_static_cache_header(conn);
  6762. mg_printf(conn,
  6763. "Content-Length: 0\r\n"
  6764. "Connection: %s\r\n\r\n",
  6765. suggest_connection_header(conn));
  6766. } else if (rc == -1) {
  6767. if (errno == EEXIST) {
  6768. send_http_error(
  6769. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6770. } else if (errno == EACCES) {
  6771. send_http_error(
  6772. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6773. } else if (errno == ENOENT) {
  6774. send_http_error(
  6775. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6776. } else {
  6777. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6778. }
  6779. }
  6780. }
  6781. static void
  6782. put_file(struct mg_connection *conn, const char *path)
  6783. {
  6784. struct file file = STRUCT_FILE_INITIALIZER;
  6785. const char *range;
  6786. int64_t r1, r2;
  6787. int rc;
  6788. char date[64];
  6789. time_t curtime = time(NULL);
  6790. if (conn == NULL) {
  6791. return;
  6792. }
  6793. if (mg_stat(conn, path, &file)) {
  6794. /* File already exists */
  6795. conn->status_code = 200;
  6796. if (file.is_directory) {
  6797. /* This is an already existing directory,
  6798. * so there is nothing to do for the server. */
  6799. rc = 0;
  6800. } else {
  6801. /* File exists and is not a directory. */
  6802. /* Can it be replaced? */
  6803. if (file.membuf != NULL) {
  6804. /* This is an "in-memory" file, that can not be replaced */
  6805. send_http_error(
  6806. conn,
  6807. 405,
  6808. "Error: Put not possible\nReplacing %s is not supported",
  6809. path);
  6810. return;
  6811. }
  6812. /* Check if the server may write this file */
  6813. if (access(path, W_OK) == 0) {
  6814. /* Access granted */
  6815. conn->status_code = 200;
  6816. rc = 1;
  6817. } else {
  6818. send_http_error(
  6819. conn,
  6820. 403,
  6821. "Error: Put not possible\nReplacing %s is not allowed",
  6822. path);
  6823. return;
  6824. }
  6825. }
  6826. } else {
  6827. /* File should be created */
  6828. conn->status_code = 201;
  6829. rc = put_dir(conn, path);
  6830. }
  6831. if (rc == 0) {
  6832. /* put_dir returns 0 if path is a directory */
  6833. gmt_time_string(date, sizeof(date), &curtime);
  6834. mg_printf(conn,
  6835. "HTTP/1.1 %d %s\r\n",
  6836. conn->status_code,
  6837. mg_get_response_code_text(NULL, conn->status_code));
  6838. send_no_cache_header(conn);
  6839. mg_printf(conn,
  6840. "Date: %s\r\n"
  6841. "Content-Length: 0\r\n"
  6842. "Connection: %s\r\n\r\n",
  6843. date,
  6844. suggest_connection_header(conn));
  6845. /* Request to create a directory has been fulfilled successfully.
  6846. * No need to put a file. */
  6847. return;
  6848. }
  6849. if (rc == -1) {
  6850. /* put_dir returns -1 if the path is too long */
  6851. send_http_error(conn,
  6852. 414,
  6853. "Error: Path too long\nput_dir(%s): %s",
  6854. path,
  6855. strerror(ERRNO));
  6856. return;
  6857. }
  6858. if (rc == -2) {
  6859. /* put_dir returns -2 if the directory can not be created */
  6860. send_http_error(conn,
  6861. 500,
  6862. "Error: Can not create directory\nput_dir(%s): %s",
  6863. path,
  6864. strerror(ERRNO));
  6865. return;
  6866. }
  6867. /* A file should be created or overwritten. */
  6868. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6869. mg_fclose(&file);
  6870. send_http_error(conn,
  6871. 500,
  6872. "Error: Can not create file\nfopen(%s): %s",
  6873. path,
  6874. strerror(ERRNO));
  6875. return;
  6876. }
  6877. fclose_on_exec(&file, conn);
  6878. range = mg_get_header(conn, "Content-Range");
  6879. r1 = r2 = 0;
  6880. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6881. conn->status_code = 206; /* Partial content */
  6882. fseeko(file.fp, r1, SEEK_SET);
  6883. }
  6884. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6885. /* forward_body_data failed.
  6886. * The error code has already been sent to the client,
  6887. * and conn->status_code is already set. */
  6888. mg_fclose(&file);
  6889. return;
  6890. }
  6891. gmt_time_string(date, sizeof(date), &curtime);
  6892. mg_printf(conn,
  6893. "HTTP/1.1 %d %s\r\n",
  6894. conn->status_code,
  6895. mg_get_response_code_text(NULL, conn->status_code));
  6896. send_no_cache_header(conn);
  6897. mg_printf(conn,
  6898. "Date: %s\r\n"
  6899. "Content-Length: 0\r\n"
  6900. "Connection: %s\r\n\r\n",
  6901. date,
  6902. suggest_connection_header(conn));
  6903. mg_fclose(&file);
  6904. }
  6905. static void
  6906. delete_file(struct mg_connection *conn, const char *path)
  6907. {
  6908. struct de de;
  6909. memset(&de.file, 0, sizeof(de.file));
  6910. if (!mg_stat(conn, path, &de.file)) {
  6911. /* mg_stat returns 0 if the file does not exist */
  6912. send_http_error(conn,
  6913. 404,
  6914. "Error: Cannot delete file\nFile %s not found",
  6915. path);
  6916. return;
  6917. }
  6918. if (de.file.membuf != NULL) {
  6919. /* the file is cached in memory */
  6920. send_http_error(
  6921. conn,
  6922. 405,
  6923. "Error: Delete not possible\nDeleting %s is not supported",
  6924. path);
  6925. return;
  6926. }
  6927. if (de.file.is_directory) {
  6928. if (remove_directory(conn, path)) {
  6929. /* Delete is successful: Return 204 without content. */
  6930. send_http_error(conn, 204, "%s", "");
  6931. } else {
  6932. /* Delete is not successful: Return 500 (Server error). */
  6933. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6934. }
  6935. return;
  6936. }
  6937. /* This is an existing file (not a directory).
  6938. * Check if write permission is granted. */
  6939. if (access(path, W_OK) != 0) {
  6940. /* File is read only */
  6941. send_http_error(
  6942. conn,
  6943. 403,
  6944. "Error: Delete not possible\nDeleting %s is not allowed",
  6945. path);
  6946. return;
  6947. }
  6948. /* Try to delete it. */
  6949. if (mg_remove(conn, path) == 0) {
  6950. /* Delete was successful: Return 204 without content. */
  6951. send_http_error(conn, 204, "%s", "");
  6952. } else {
  6953. /* Delete not successful (file locked). */
  6954. send_http_error(conn,
  6955. 423,
  6956. "Error: Cannot delete file\nremove(%s): %s",
  6957. path,
  6958. strerror(ERRNO));
  6959. }
  6960. }
  6961. #endif /* !NO_FILES */
  6962. static void
  6963. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6964. static void
  6965. do_ssi_include(struct mg_connection *conn,
  6966. const char *ssi,
  6967. char *tag,
  6968. int include_level)
  6969. {
  6970. char file_name[MG_BUF_LEN], path[512], *p;
  6971. struct file file = STRUCT_FILE_INITIALIZER;
  6972. size_t len;
  6973. int truncated = 0;
  6974. if (conn == NULL) {
  6975. return;
  6976. }
  6977. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6978. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6979. * always < MG_BUF_LEN. */
  6980. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6981. /* File name is relative to the webserver root */
  6982. file_name[511] = 0;
  6983. (void)mg_snprintf(conn,
  6984. &truncated,
  6985. path,
  6986. sizeof(path),
  6987. "%s/%s",
  6988. conn->ctx->config[DOCUMENT_ROOT],
  6989. file_name);
  6990. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6991. /* File name is relative to the webserver working directory
  6992. * or it is absolute system path */
  6993. file_name[511] = 0;
  6994. (void)
  6995. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6996. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6997. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6998. /* File name is relative to the currect document */
  6999. file_name[511] = 0;
  7000. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7001. if (!truncated) {
  7002. if ((p = strrchr(path, '/')) != NULL) {
  7003. p[1] = '\0';
  7004. }
  7005. len = strlen(path);
  7006. (void)mg_snprintf(conn,
  7007. &truncated,
  7008. path + len,
  7009. sizeof(path) - len,
  7010. "%s",
  7011. file_name);
  7012. }
  7013. } else {
  7014. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7015. return;
  7016. }
  7017. if (truncated) {
  7018. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7019. return;
  7020. }
  7021. if (!mg_fopen(conn, path, "rb", &file)) {
  7022. mg_cry(conn,
  7023. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7024. tag,
  7025. path,
  7026. strerror(ERRNO));
  7027. } else {
  7028. fclose_on_exec(&file, conn);
  7029. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7030. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7031. path) > 0) {
  7032. send_ssi_file(conn, path, &file, include_level + 1);
  7033. } else {
  7034. send_file_data(conn, &file, 0, INT64_MAX);
  7035. }
  7036. mg_fclose(&file);
  7037. }
  7038. }
  7039. #if !defined(NO_POPEN)
  7040. static void
  7041. do_ssi_exec(struct mg_connection *conn, char *tag)
  7042. {
  7043. char cmd[1024] = "";
  7044. struct file file = STRUCT_FILE_INITIALIZER;
  7045. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7046. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7047. } else {
  7048. cmd[1023] = 0;
  7049. if ((file.fp = popen(cmd, "r")) == NULL) {
  7050. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7051. } else {
  7052. send_file_data(conn, &file, 0, INT64_MAX);
  7053. pclose(file.fp);
  7054. }
  7055. }
  7056. }
  7057. #endif /* !NO_POPEN */
  7058. static int
  7059. mg_fgetc(struct file *filep, int offset)
  7060. {
  7061. if (filep == NULL) {
  7062. return EOF;
  7063. }
  7064. if (filep->membuf != NULL && offset >= 0
  7065. && ((unsigned int)(offset)) < filep->size) {
  7066. return ((const unsigned char *)filep->membuf)[offset];
  7067. } else if (filep->fp != NULL) {
  7068. return fgetc(filep->fp);
  7069. } else {
  7070. return EOF;
  7071. }
  7072. }
  7073. static void
  7074. send_ssi_file(struct mg_connection *conn,
  7075. const char *path,
  7076. struct file *filep,
  7077. int include_level)
  7078. {
  7079. char buf[MG_BUF_LEN];
  7080. int ch, offset, len, in_ssi_tag;
  7081. if (include_level > 10) {
  7082. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7083. return;
  7084. }
  7085. in_ssi_tag = len = offset = 0;
  7086. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7087. if (in_ssi_tag && ch == '>') {
  7088. in_ssi_tag = 0;
  7089. buf[len++] = (char)ch;
  7090. buf[len] = '\0';
  7091. /* assert(len <= (int) sizeof(buf)); */
  7092. if (len > (int)sizeof(buf)) {
  7093. break;
  7094. }
  7095. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7096. /* Not an SSI tag, pass it */
  7097. (void)mg_write(conn, buf, (size_t)len);
  7098. } else {
  7099. if (!memcmp(buf + 5, "include", 7)) {
  7100. do_ssi_include(conn, path, buf + 12, include_level);
  7101. #if !defined(NO_POPEN)
  7102. } else if (!memcmp(buf + 5, "exec", 4)) {
  7103. do_ssi_exec(conn, buf + 9);
  7104. #endif /* !NO_POPEN */
  7105. } else {
  7106. mg_cry(conn,
  7107. "%s: unknown SSI "
  7108. "command: \"%s\"",
  7109. path,
  7110. buf);
  7111. }
  7112. }
  7113. len = 0;
  7114. } else if (in_ssi_tag) {
  7115. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7116. /* Not an SSI tag */
  7117. in_ssi_tag = 0;
  7118. } else if (len == (int)sizeof(buf) - 2) {
  7119. mg_cry(conn, "%s: SSI tag is too large", path);
  7120. len = 0;
  7121. }
  7122. buf[len++] = (char)(ch & 0xff);
  7123. } else if (ch == '<') {
  7124. in_ssi_tag = 1;
  7125. if (len > 0) {
  7126. mg_write(conn, buf, (size_t)len);
  7127. }
  7128. len = 0;
  7129. buf[len++] = (char)(ch & 0xff);
  7130. } else {
  7131. buf[len++] = (char)(ch & 0xff);
  7132. if (len == (int)sizeof(buf)) {
  7133. mg_write(conn, buf, (size_t)len);
  7134. len = 0;
  7135. }
  7136. }
  7137. }
  7138. /* Send the rest of buffered data */
  7139. if (len > 0) {
  7140. mg_write(conn, buf, (size_t)len);
  7141. }
  7142. }
  7143. static void
  7144. handle_ssi_file_request(struct mg_connection *conn,
  7145. const char *path,
  7146. struct file *filep)
  7147. {
  7148. char date[64];
  7149. time_t curtime = time(NULL);
  7150. const char *cors1, *cors2, *cors3;
  7151. if (conn == NULL || path == NULL || filep == NULL) {
  7152. return;
  7153. }
  7154. if (mg_get_header(conn, "Origin")) {
  7155. /* Cross-origin resource sharing (CORS). */
  7156. cors1 = "Access-Control-Allow-Origin: ";
  7157. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7158. cors3 = "\r\n";
  7159. } else {
  7160. cors1 = cors2 = cors3 = "";
  7161. }
  7162. if (!mg_fopen(conn, path, "rb", filep)) {
  7163. /* File exists (precondition for calling this function),
  7164. * but can not be opened by the server. */
  7165. send_http_error(conn,
  7166. 500,
  7167. "Error: Cannot read file\nfopen(%s): %s",
  7168. path,
  7169. strerror(ERRNO));
  7170. } else {
  7171. conn->must_close = 1;
  7172. gmt_time_string(date, sizeof(date), &curtime);
  7173. fclose_on_exec(filep, conn);
  7174. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7175. send_no_cache_header(conn);
  7176. mg_printf(conn,
  7177. "%s%s%s"
  7178. "Date: %s\r\n"
  7179. "Content-Type: text/html\r\n"
  7180. "Connection: %s\r\n\r\n",
  7181. cors1,
  7182. cors2,
  7183. cors3,
  7184. date,
  7185. suggest_connection_header(conn));
  7186. send_ssi_file(conn, path, filep, 0);
  7187. mg_fclose(filep);
  7188. }
  7189. }
  7190. #if !defined(NO_FILES)
  7191. static void
  7192. send_options(struct mg_connection *conn)
  7193. {
  7194. char date[64];
  7195. time_t curtime = time(NULL);
  7196. if (!conn) {
  7197. return;
  7198. }
  7199. conn->status_code = 200;
  7200. conn->must_close = 1;
  7201. gmt_time_string(date, sizeof(date), &curtime);
  7202. mg_printf(conn,
  7203. "HTTP/1.1 200 OK\r\n"
  7204. "Date: %s\r\n"
  7205. /* TODO: "Cache-Control" (?) */
  7206. "Connection: %s\r\n"
  7207. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7208. "PROPFIND, MKCOL\r\n"
  7209. "DAV: 1\r\n\r\n",
  7210. date,
  7211. suggest_connection_header(conn));
  7212. }
  7213. /* Writes PROPFIND properties for a collection element */
  7214. static void
  7215. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7216. {
  7217. char mtime[64];
  7218. if (conn == NULL || uri == NULL || filep == NULL) {
  7219. return;
  7220. }
  7221. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7222. conn->num_bytes_sent +=
  7223. mg_printf(conn,
  7224. "<d:response>"
  7225. "<d:href>%s</d:href>"
  7226. "<d:propstat>"
  7227. "<d:prop>"
  7228. "<d:resourcetype>%s</d:resourcetype>"
  7229. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7230. "<d:getlastmodified>%s</d:getlastmodified>"
  7231. "</d:prop>"
  7232. "<d:status>HTTP/1.1 200 OK</d:status>"
  7233. "</d:propstat>"
  7234. "</d:response>\n",
  7235. uri,
  7236. filep->is_directory ? "<d:collection/>" : "",
  7237. filep->size,
  7238. mtime);
  7239. }
  7240. static void
  7241. print_dav_dir_entry(struct de *de, void *data)
  7242. {
  7243. char href[PATH_MAX];
  7244. char href_encoded[PATH_MAX * 3 /* worst case */];
  7245. int truncated;
  7246. struct mg_connection *conn = (struct mg_connection *)data;
  7247. if (!de || !conn) {
  7248. return;
  7249. }
  7250. mg_snprintf(conn,
  7251. &truncated,
  7252. href,
  7253. sizeof(href),
  7254. "%s%s",
  7255. conn->request_info.local_uri,
  7256. de->file_name);
  7257. if (!truncated) {
  7258. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7259. print_props(conn, href_encoded, &de->file);
  7260. }
  7261. }
  7262. static void
  7263. handle_propfind(struct mg_connection *conn,
  7264. const char *path,
  7265. struct file *filep)
  7266. {
  7267. const char *depth = mg_get_header(conn, "Depth");
  7268. char date[64];
  7269. time_t curtime = time(NULL);
  7270. gmt_time_string(date, sizeof(date), &curtime);
  7271. if (!conn || !path || !filep || !conn->ctx) {
  7272. return;
  7273. }
  7274. conn->must_close = 1;
  7275. conn->status_code = 207;
  7276. mg_printf(conn,
  7277. "HTTP/1.1 207 Multi-Status\r\n"
  7278. "Date: %s\r\n",
  7279. date);
  7280. send_static_cache_header(conn);
  7281. mg_printf(conn,
  7282. "Connection: %s\r\n"
  7283. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7284. suggest_connection_header(conn));
  7285. conn->num_bytes_sent +=
  7286. mg_printf(conn,
  7287. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7288. "<d:multistatus xmlns:d='DAV:'>\n");
  7289. /* Print properties for the requested resource itself */
  7290. print_props(conn, conn->request_info.local_uri, filep);
  7291. /* If it is a directory, print directory entries too if Depth is not 0 */
  7292. if (filep && filep->is_directory
  7293. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7294. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7295. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7296. }
  7297. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7298. }
  7299. #endif
  7300. void
  7301. mg_lock_connection(struct mg_connection *conn)
  7302. {
  7303. if (conn) {
  7304. (void)pthread_mutex_lock(&conn->mutex);
  7305. }
  7306. }
  7307. void
  7308. mg_unlock_connection(struct mg_connection *conn)
  7309. {
  7310. if (conn) {
  7311. (void)pthread_mutex_unlock(&conn->mutex);
  7312. }
  7313. }
  7314. void
  7315. mg_lock_context(struct mg_context *ctx)
  7316. {
  7317. if (ctx) {
  7318. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7319. }
  7320. }
  7321. void
  7322. mg_unlock_context(struct mg_context *ctx)
  7323. {
  7324. if (ctx) {
  7325. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7326. }
  7327. }
  7328. #if defined(USE_TIMERS)
  7329. #include "timer.inl"
  7330. #endif /* USE_TIMERS */
  7331. #ifdef USE_LUA
  7332. #include "mod_lua.inl"
  7333. #endif /* USE_LUA */
  7334. #ifdef USE_DUKTAPE
  7335. #include "mod_duktape.inl"
  7336. #endif /* USE_DUKTAPE */
  7337. #if defined(USE_WEBSOCKET)
  7338. /* START OF SHA-1 code
  7339. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7340. #define SHA1HANDSOFF
  7341. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7342. *
  7343. * #if defined(__sun)
  7344. * #include "solarisfixes.h"
  7345. * #endif
  7346. */
  7347. static int
  7348. is_big_endian(void)
  7349. {
  7350. static const int n = 1;
  7351. return ((char *)&n)[0] == 0;
  7352. }
  7353. union char64long16 {
  7354. unsigned char c[64];
  7355. uint32_t l[16];
  7356. };
  7357. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7358. static uint32_t
  7359. blk0(union char64long16 *block, int i)
  7360. {
  7361. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7362. if (!is_big_endian()) {
  7363. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7364. | (rol(block->l[i], 8) & 0x00FF00FF);
  7365. }
  7366. return block->l[i];
  7367. }
  7368. #define blk(i) \
  7369. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7370. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7371. 1))
  7372. #define R0(v, w, x, y, z, i) \
  7373. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7374. w = rol(w, 30);
  7375. #define R1(v, w, x, y, z, i) \
  7376. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7377. w = rol(w, 30);
  7378. #define R2(v, w, x, y, z, i) \
  7379. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7380. w = rol(w, 30);
  7381. #define R3(v, w, x, y, z, i) \
  7382. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7383. w = rol(w, 30);
  7384. #define R4(v, w, x, y, z, i) \
  7385. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7386. w = rol(w, 30);
  7387. typedef struct {
  7388. uint32_t state[5];
  7389. uint32_t count[2];
  7390. unsigned char buffer[64];
  7391. } SHA1_CTX;
  7392. static void
  7393. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7394. {
  7395. uint32_t a, b, c, d, e;
  7396. union char64long16 block[1];
  7397. memcpy(block, buffer, 64);
  7398. a = state[0];
  7399. b = state[1];
  7400. c = state[2];
  7401. d = state[3];
  7402. e = state[4];
  7403. R0(a, b, c, d, e, 0);
  7404. R0(e, a, b, c, d, 1);
  7405. R0(d, e, a, b, c, 2);
  7406. R0(c, d, e, a, b, 3);
  7407. R0(b, c, d, e, a, 4);
  7408. R0(a, b, c, d, e, 5);
  7409. R0(e, a, b, c, d, 6);
  7410. R0(d, e, a, b, c, 7);
  7411. R0(c, d, e, a, b, 8);
  7412. R0(b, c, d, e, a, 9);
  7413. R0(a, b, c, d, e, 10);
  7414. R0(e, a, b, c, d, 11);
  7415. R0(d, e, a, b, c, 12);
  7416. R0(c, d, e, a, b, 13);
  7417. R0(b, c, d, e, a, 14);
  7418. R0(a, b, c, d, e, 15);
  7419. R1(e, a, b, c, d, 16);
  7420. R1(d, e, a, b, c, 17);
  7421. R1(c, d, e, a, b, 18);
  7422. R1(b, c, d, e, a, 19);
  7423. R2(a, b, c, d, e, 20);
  7424. R2(e, a, b, c, d, 21);
  7425. R2(d, e, a, b, c, 22);
  7426. R2(c, d, e, a, b, 23);
  7427. R2(b, c, d, e, a, 24);
  7428. R2(a, b, c, d, e, 25);
  7429. R2(e, a, b, c, d, 26);
  7430. R2(d, e, a, b, c, 27);
  7431. R2(c, d, e, a, b, 28);
  7432. R2(b, c, d, e, a, 29);
  7433. R2(a, b, c, d, e, 30);
  7434. R2(e, a, b, c, d, 31);
  7435. R2(d, e, a, b, c, 32);
  7436. R2(c, d, e, a, b, 33);
  7437. R2(b, c, d, e, a, 34);
  7438. R2(a, b, c, d, e, 35);
  7439. R2(e, a, b, c, d, 36);
  7440. R2(d, e, a, b, c, 37);
  7441. R2(c, d, e, a, b, 38);
  7442. R2(b, c, d, e, a, 39);
  7443. R3(a, b, c, d, e, 40);
  7444. R3(e, a, b, c, d, 41);
  7445. R3(d, e, a, b, c, 42);
  7446. R3(c, d, e, a, b, 43);
  7447. R3(b, c, d, e, a, 44);
  7448. R3(a, b, c, d, e, 45);
  7449. R3(e, a, b, c, d, 46);
  7450. R3(d, e, a, b, c, 47);
  7451. R3(c, d, e, a, b, 48);
  7452. R3(b, c, d, e, a, 49);
  7453. R3(a, b, c, d, e, 50);
  7454. R3(e, a, b, c, d, 51);
  7455. R3(d, e, a, b, c, 52);
  7456. R3(c, d, e, a, b, 53);
  7457. R3(b, c, d, e, a, 54);
  7458. R3(a, b, c, d, e, 55);
  7459. R3(e, a, b, c, d, 56);
  7460. R3(d, e, a, b, c, 57);
  7461. R3(c, d, e, a, b, 58);
  7462. R3(b, c, d, e, a, 59);
  7463. R4(a, b, c, d, e, 60);
  7464. R4(e, a, b, c, d, 61);
  7465. R4(d, e, a, b, c, 62);
  7466. R4(c, d, e, a, b, 63);
  7467. R4(b, c, d, e, a, 64);
  7468. R4(a, b, c, d, e, 65);
  7469. R4(e, a, b, c, d, 66);
  7470. R4(d, e, a, b, c, 67);
  7471. R4(c, d, e, a, b, 68);
  7472. R4(b, c, d, e, a, 69);
  7473. R4(a, b, c, d, e, 70);
  7474. R4(e, a, b, c, d, 71);
  7475. R4(d, e, a, b, c, 72);
  7476. R4(c, d, e, a, b, 73);
  7477. R4(b, c, d, e, a, 74);
  7478. R4(a, b, c, d, e, 75);
  7479. R4(e, a, b, c, d, 76);
  7480. R4(d, e, a, b, c, 77);
  7481. R4(c, d, e, a, b, 78);
  7482. R4(b, c, d, e, a, 79);
  7483. state[0] += a;
  7484. state[1] += b;
  7485. state[2] += c;
  7486. state[3] += d;
  7487. state[4] += e;
  7488. a = b = c = d = e = 0;
  7489. memset(block, '\0', sizeof(block));
  7490. }
  7491. static void
  7492. SHA1Init(SHA1_CTX *context)
  7493. {
  7494. context->state[0] = 0x67452301;
  7495. context->state[1] = 0xEFCDAB89;
  7496. context->state[2] = 0x98BADCFE;
  7497. context->state[3] = 0x10325476;
  7498. context->state[4] = 0xC3D2E1F0;
  7499. context->count[0] = context->count[1] = 0;
  7500. }
  7501. static void
  7502. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7503. {
  7504. uint32_t i, j;
  7505. j = context->count[0];
  7506. if ((context->count[0] += len << 3) < j) {
  7507. context->count[1]++;
  7508. }
  7509. context->count[1] += (len >> 29);
  7510. j = (j >> 3) & 63;
  7511. if ((j + len) > 63) {
  7512. memcpy(&context->buffer[j], data, (i = 64 - j));
  7513. SHA1Transform(context->state, context->buffer);
  7514. for (; i + 63 < len; i += 64) {
  7515. SHA1Transform(context->state, &data[i]);
  7516. }
  7517. j = 0;
  7518. } else
  7519. i = 0;
  7520. memcpy(&context->buffer[j], &data[i], len - i);
  7521. }
  7522. static void
  7523. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7524. {
  7525. unsigned i;
  7526. unsigned char finalcount[8], c;
  7527. for (i = 0; i < 8; i++) {
  7528. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7529. >> ((3 - (i & 3)) * 8)) & 255);
  7530. }
  7531. c = 0200;
  7532. SHA1Update(context, &c, 1);
  7533. while ((context->count[0] & 504) != 448) {
  7534. c = 0000;
  7535. SHA1Update(context, &c, 1);
  7536. }
  7537. SHA1Update(context, finalcount, 8);
  7538. for (i = 0; i < 20; i++) {
  7539. digest[i] = (unsigned char)((context->state[i >> 2]
  7540. >> ((3 - (i & 3)) * 8)) & 255);
  7541. }
  7542. memset(context, '\0', sizeof(*context));
  7543. memset(&finalcount, '\0', sizeof(finalcount));
  7544. }
  7545. /* END OF SHA1 CODE */
  7546. static int
  7547. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7548. {
  7549. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7550. const char *protocol = NULL;
  7551. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7552. SHA1_CTX sha_ctx;
  7553. int truncated;
  7554. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7555. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7556. if (truncated) {
  7557. conn->must_close = 1;
  7558. return 0;
  7559. }
  7560. SHA1Init(&sha_ctx);
  7561. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7562. SHA1Final((unsigned char *)sha, &sha_ctx);
  7563. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7564. mg_printf(conn,
  7565. "HTTP/1.1 101 Switching Protocols\r\n"
  7566. "Upgrade: websocket\r\n"
  7567. "Connection: Upgrade\r\n"
  7568. "Sec-WebSocket-Accept: %s\r\n",
  7569. b64_sha);
  7570. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7571. if (protocol) {
  7572. /* The protocol is a comma seperated list of names. */
  7573. /* The server must only return one value from this list. */
  7574. /* First check if it is a list or just a single value. */
  7575. const char *sep = strchr(protocol, ',');
  7576. if (sep == NULL) {
  7577. /* Just a single protocol -> accept it. */
  7578. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7579. } else {
  7580. /* Multiple protocols -> accept the first one. */
  7581. /* This is just a quick fix if the client offers multiple
  7582. * protocols. In order to get the behavior intended by
  7583. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7584. * required to have a list of websocket subprotocols accepted
  7585. * by the server. Then the server must either select a subprotocol
  7586. * supported by client and server, or the server has to abort the
  7587. * handshake by not returning a Sec-Websocket-Protocol header if
  7588. * no subprotocol is acceptable.
  7589. */
  7590. mg_printf(conn,
  7591. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7592. (int)(sep - protocol),
  7593. protocol);
  7594. }
  7595. /* TODO: Real subprotocol negotiation instead of just taking the first
  7596. * websocket subprotocol suggested by the client. */
  7597. } else {
  7598. mg_printf(conn, "%s", "\r\n");
  7599. }
  7600. return 1;
  7601. }
  7602. static void
  7603. read_websocket(struct mg_connection *conn,
  7604. mg_websocket_data_handler ws_data_handler,
  7605. void *callback_data)
  7606. {
  7607. /* Pointer to the beginning of the portion of the incoming websocket
  7608. * message queue.
  7609. * The original websocket upgrade request is never removed, so the queue
  7610. * begins after it. */
  7611. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7612. int n, error, exit_by_callback;
  7613. /* body_len is the length of the entire queue in bytes
  7614. * len is the length of the current message
  7615. * data_len is the length of the current message's data payload
  7616. * header_len is the length of the current message's header */
  7617. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7618. /* "The masking key is a 32-bit value chosen at random by the client."
  7619. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7620. */
  7621. unsigned char mask[4];
  7622. /* data points to the place where the message is stored when passed to
  7623. * the
  7624. * websocket_data callback. This is either mem on the stack, or a
  7625. * dynamically allocated buffer if it is too large. */
  7626. char mem[4096];
  7627. char *data = mem;
  7628. unsigned char mop; /* mask flag and opcode */
  7629. double timeout = -1.0;
  7630. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7631. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7632. }
  7633. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7634. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7635. }
  7636. mg_set_thread_name("wsock");
  7637. /* Loop continuously, reading messages from the socket, invoking the
  7638. * callback, and waiting repeatedly until an error occurs. */
  7639. while (!conn->ctx->stop_flag) {
  7640. header_len = 0;
  7641. assert(conn->data_len >= conn->request_len);
  7642. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7643. len = buf[1] & 127;
  7644. mask_len = buf[1] & 128 ? 4 : 0;
  7645. if (len < 126 && body_len >= mask_len) {
  7646. data_len = len;
  7647. header_len = 2 + mask_len;
  7648. } else if (len == 126 && body_len >= 4 + mask_len) {
  7649. header_len = 4 + mask_len;
  7650. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7651. } else if (body_len >= 10 + mask_len) {
  7652. header_len = 10 + mask_len;
  7653. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7654. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7655. }
  7656. }
  7657. if (header_len > 0 && body_len >= header_len) {
  7658. /* Allocate space to hold websocket payload */
  7659. data = mem;
  7660. if (data_len > sizeof(mem)) {
  7661. data = (char *)mg_malloc(data_len);
  7662. if (data == NULL) {
  7663. /* Allocation failed, exit the loop and then close the
  7664. * connection */
  7665. mg_cry(conn, "websocket out of memory; closing connection");
  7666. break;
  7667. }
  7668. }
  7669. /* Copy the mask before we shift the queue and destroy it */
  7670. if (mask_len > 0) {
  7671. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7672. } else {
  7673. memset(mask, 0, sizeof(mask));
  7674. }
  7675. /* Read frame payload from the first message in the queue into
  7676. * data and advance the queue by moving the memory in place. */
  7677. assert(body_len >= header_len);
  7678. if (data_len + header_len > body_len) {
  7679. mop = buf[0]; /* current mask and opcode */
  7680. /* Overflow case */
  7681. len = body_len - header_len;
  7682. memcpy(data, buf + header_len, len);
  7683. error = 0;
  7684. while (len < data_len) {
  7685. n = pull(
  7686. NULL, conn, data + len, (int)(data_len - len), timeout);
  7687. if (n <= 0) {
  7688. error = 1;
  7689. break;
  7690. }
  7691. len += (size_t)n;
  7692. }
  7693. if (error) {
  7694. mg_cry(conn, "Websocket pull failed; closing connection");
  7695. break;
  7696. }
  7697. conn->data_len = conn->request_len;
  7698. } else {
  7699. mop = buf[0]; /* current mask and opcode, overwritten by
  7700. * memmove() */
  7701. /* Length of the message being read at the front of the
  7702. * queue */
  7703. len = data_len + header_len;
  7704. /* Copy the data payload into the data pointer for the
  7705. * callback */
  7706. memcpy(data, buf + header_len, data_len);
  7707. /* Move the queue forward len bytes */
  7708. memmove(buf, buf + len, body_len - len);
  7709. /* Mark the queue as advanced */
  7710. conn->data_len -= (int)len;
  7711. }
  7712. /* Apply mask if necessary */
  7713. if (mask_len > 0) {
  7714. for (i = 0; i < data_len; ++i) {
  7715. data[i] ^= mask[i & 3];
  7716. }
  7717. }
  7718. /* Exit the loop if callback signals to exit (server side),
  7719. * or "connection close" opcode received (client side). */
  7720. exit_by_callback = 0;
  7721. if ((ws_data_handler != NULL)
  7722. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7723. exit_by_callback = 1;
  7724. }
  7725. if (data != mem) {
  7726. mg_free(data);
  7727. }
  7728. if (exit_by_callback
  7729. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7730. /* Opcode == 8, connection close */
  7731. break;
  7732. }
  7733. /* Not breaking the loop, process next websocket frame. */
  7734. } else {
  7735. /* Read from the socket into the next available location in the
  7736. * message queue. */
  7737. if ((n = pull(NULL,
  7738. conn,
  7739. conn->buf + conn->data_len,
  7740. conn->buf_size - conn->data_len,
  7741. timeout)) <= 0) {
  7742. /* Error, no bytes read */
  7743. break;
  7744. }
  7745. conn->data_len += n;
  7746. }
  7747. }
  7748. mg_set_thread_name("worker");
  7749. }
  7750. static int
  7751. mg_websocket_write_exec(struct mg_connection *conn,
  7752. int opcode,
  7753. const char *data,
  7754. size_t dataLen,
  7755. uint32_t masking_key)
  7756. {
  7757. unsigned char header[14];
  7758. size_t headerLen = 1;
  7759. int retval = -1;
  7760. header[0] = 0x80 + (opcode & 0xF);
  7761. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7762. if (dataLen < 126) {
  7763. /* inline 7-bit length field */
  7764. header[1] = (unsigned char)dataLen;
  7765. headerLen = 2;
  7766. } else if (dataLen <= 0xFFFF) {
  7767. /* 16-bit length field */
  7768. header[1] = 126;
  7769. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7770. headerLen = 4;
  7771. } else {
  7772. /* 64-bit length field */
  7773. header[1] = 127;
  7774. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7775. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7776. headerLen = 10;
  7777. }
  7778. if (masking_key) {
  7779. /* add mask */
  7780. header[1] |= 0x80;
  7781. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7782. headerLen += 4;
  7783. }
  7784. /* Note that POSIX/Winsock's send() is threadsafe
  7785. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7786. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7787. * push(), although that is only a problem if the packet is large or
  7788. * outgoing buffer is full). */
  7789. (void)mg_lock_connection(conn);
  7790. retval = mg_write(conn, header, headerLen);
  7791. if (dataLen > 0) {
  7792. retval = mg_write(conn, data, dataLen);
  7793. }
  7794. mg_unlock_connection(conn);
  7795. return retval;
  7796. }
  7797. int
  7798. mg_websocket_write(struct mg_connection *conn,
  7799. int opcode,
  7800. const char *data,
  7801. size_t dataLen)
  7802. {
  7803. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7804. }
  7805. static void
  7806. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7807. {
  7808. size_t i = 0;
  7809. i = 0;
  7810. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7811. /* Convert in 32 bit words, if data is 4 byte aligned */
  7812. while (i < (in_len - 3)) {
  7813. *(uint32_t *)(void *)(out + i) =
  7814. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7815. i += 4;
  7816. }
  7817. }
  7818. if (i != in_len) {
  7819. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7820. while (i < in_len) {
  7821. *(uint8_t *)(void *)(out + i) =
  7822. *(uint8_t *)(void *)(in + i)
  7823. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7824. i++;
  7825. }
  7826. }
  7827. }
  7828. int
  7829. mg_websocket_client_write(struct mg_connection *conn,
  7830. int opcode,
  7831. const char *data,
  7832. size_t dataLen)
  7833. {
  7834. int retval = -1;
  7835. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7836. uint32_t masking_key = (uint32_t)get_random();
  7837. if (masked_data == NULL) {
  7838. /* Return -1 in an error case */
  7839. mg_cry(conn,
  7840. "Cannot allocate buffer for masked websocket response: "
  7841. "Out of memory");
  7842. return -1;
  7843. }
  7844. mask_data(data, dataLen, masking_key, masked_data);
  7845. retval = mg_websocket_write_exec(
  7846. conn, opcode, masked_data, dataLen, masking_key);
  7847. mg_free(masked_data);
  7848. return retval;
  7849. }
  7850. static void
  7851. handle_websocket_request(struct mg_connection *conn,
  7852. const char *path,
  7853. int is_callback_resource,
  7854. mg_websocket_connect_handler ws_connect_handler,
  7855. mg_websocket_ready_handler ws_ready_handler,
  7856. mg_websocket_data_handler ws_data_handler,
  7857. mg_websocket_close_handler ws_close_handler,
  7858. void *cbData)
  7859. {
  7860. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7861. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7862. int lua_websock = 0;
  7863. #if !defined(USE_LUA)
  7864. (void)path;
  7865. #endif
  7866. /* Step 1: Check websocket protocol version. */
  7867. /* Step 1.1: Check Sec-WebSocket-Key. */
  7868. if (!websock_key) {
  7869. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7870. * requires a Sec-WebSocket-Key header.
  7871. */
  7872. /* It could be the hixie draft version
  7873. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7874. */
  7875. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7876. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7877. char key3[8];
  7878. if ((key1 != NULL) && (key2 != NULL)) {
  7879. /* This version uses 8 byte body data in a GET request */
  7880. conn->content_len = 8;
  7881. if (8 == mg_read(conn, key3, 8)) {
  7882. /* This is the hixie version */
  7883. send_http_error(conn,
  7884. 426,
  7885. "%s",
  7886. "Protocol upgrade to RFC 6455 required");
  7887. return;
  7888. }
  7889. }
  7890. /* This is an unknown version */
  7891. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7892. return;
  7893. }
  7894. /* Step 1.2: Check websocket protocol version. */
  7895. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7896. if (version == NULL || strcmp(version, "13") != 0) {
  7897. /* Reject wrong versions */
  7898. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7899. return;
  7900. }
  7901. /* Step 1.3: Could check for "Host", but we do not really nead this
  7902. * value for anything, so just ignore it. */
  7903. /* Step 2: If a callback is responsible, call it. */
  7904. if (is_callback_resource) {
  7905. if (ws_connect_handler != NULL
  7906. && ws_connect_handler(conn, cbData) != 0) {
  7907. /* C callback has returned non-zero, do not proceed with
  7908. * handshake.
  7909. */
  7910. /* Note that C callbacks are no longer called when Lua is
  7911. * responsible, so C can no longer filter callbacks for Lua. */
  7912. return;
  7913. }
  7914. }
  7915. #if defined(USE_LUA)
  7916. /* Step 3: No callback. Check if Lua is responsible. */
  7917. else {
  7918. /* Step 3.1: Check if Lua is responsible. */
  7919. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7920. lua_websock =
  7921. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7922. strlen(
  7923. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7924. path);
  7925. }
  7926. if (lua_websock) {
  7927. /* Step 3.2: Lua is responsible: call it. */
  7928. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7929. if (!conn->lua_websocket_state) {
  7930. /* Lua rejected the new client */
  7931. return;
  7932. }
  7933. }
  7934. }
  7935. #endif
  7936. /* Step 4: Check if there is a responsible websocket handler. */
  7937. if (!is_callback_resource && !lua_websock) {
  7938. /* There is no callback, an Lua is not responsible either. */
  7939. /* Reply with a 404 Not Found or with nothing at all?
  7940. * TODO (mid): check the websocket standards, how to reply to
  7941. * requests to invalid websocket addresses. */
  7942. send_http_error(conn, 404, "%s", "Not found");
  7943. return;
  7944. }
  7945. /* Step 5: The websocket connection has been accepted */
  7946. if (!send_websocket_handshake(conn, websock_key)) {
  7947. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7948. return;
  7949. }
  7950. /* Step 6: Call the ready handler */
  7951. if (is_callback_resource) {
  7952. if (ws_ready_handler != NULL) {
  7953. ws_ready_handler(conn, cbData);
  7954. }
  7955. #if defined(USE_LUA)
  7956. } else if (lua_websock) {
  7957. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7958. /* the ready handler returned false */
  7959. return;
  7960. }
  7961. #endif
  7962. }
  7963. /* Step 7: Enter the read loop */
  7964. if (is_callback_resource) {
  7965. read_websocket(conn, ws_data_handler, cbData);
  7966. #if defined(USE_LUA)
  7967. } else if (lua_websock) {
  7968. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7969. #endif
  7970. }
  7971. /* Step 8: Call the close handler */
  7972. if (ws_close_handler) {
  7973. ws_close_handler(conn, cbData);
  7974. }
  7975. }
  7976. static int
  7977. is_websocket_protocol(const struct mg_connection *conn)
  7978. {
  7979. const char *upgrade, *connection;
  7980. /* A websocket protocoll has the following HTTP headers:
  7981. *
  7982. * Connection: Upgrade
  7983. * Upgrade: Websocket
  7984. */
  7985. upgrade = mg_get_header(conn, "Upgrade");
  7986. if (upgrade == NULL) {
  7987. return 0; /* fail early, don't waste time checking other header
  7988. * fields
  7989. */
  7990. }
  7991. if (!mg_strcasestr(upgrade, "websocket")) {
  7992. return 0;
  7993. }
  7994. connection = mg_get_header(conn, "Connection");
  7995. if (connection == NULL) {
  7996. return 0;
  7997. }
  7998. if (!mg_strcasestr(connection, "upgrade")) {
  7999. return 0;
  8000. }
  8001. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8002. * "Sec-WebSocket-Version" are also required.
  8003. * Don't check them here, since even an unsupported websocket protocol
  8004. * request still IS a websocket request (in contrast to a standard HTTP
  8005. * request). It will fail later in handle_websocket_request.
  8006. */
  8007. return 1;
  8008. }
  8009. #endif /* !USE_WEBSOCKET */
  8010. static int
  8011. isbyte(int n)
  8012. {
  8013. return n >= 0 && n <= 255;
  8014. }
  8015. static int
  8016. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8017. {
  8018. int n, a, b, c, d, slash = 32, len = 0;
  8019. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8020. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8021. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8022. && slash < 33) {
  8023. len = n;
  8024. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8025. | (uint32_t)d;
  8026. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  8027. }
  8028. return len;
  8029. }
  8030. static int
  8031. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8032. {
  8033. int throttle = 0;
  8034. struct vec vec, val;
  8035. uint32_t net, mask;
  8036. char mult;
  8037. double v;
  8038. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8039. mult = ',';
  8040. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8041. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8042. && mult != ',')) {
  8043. continue;
  8044. }
  8045. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  8046. : 1;
  8047. if (vec.len == 1 && vec.ptr[0] == '*') {
  8048. throttle = (int)v;
  8049. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8050. if ((remote_ip & mask) == net) {
  8051. throttle = (int)v;
  8052. }
  8053. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8054. throttle = (int)v;
  8055. }
  8056. }
  8057. return throttle;
  8058. }
  8059. static uint32_t
  8060. get_remote_ip(const struct mg_connection *conn)
  8061. {
  8062. if (!conn) {
  8063. return 0;
  8064. }
  8065. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8066. }
  8067. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8068. #include "handle_form.inl"
  8069. #if defined(MG_LEGACY_INTERFACE)
  8070. /* Implement the deprecated mg_upload function by calling the new
  8071. * mg_handle_form_request function. While mg_upload could only handle
  8072. * HTML forms sent as POST request in multipart/form-data format
  8073. * containing only file input elements, mg_handle_form_request can
  8074. * handle all form input elements and all standard request methods. */
  8075. struct mg_upload_user_data {
  8076. struct mg_connection *conn;
  8077. const char *destination_dir;
  8078. int num_uploaded_files;
  8079. };
  8080. /* Helper function for deprecated mg_upload. */
  8081. static int
  8082. mg_upload_field_found(const char *key,
  8083. const char *filename,
  8084. char *path,
  8085. size_t pathlen,
  8086. void *user_data)
  8087. {
  8088. int truncated = 0;
  8089. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8090. (void)key;
  8091. if (!filename) {
  8092. mg_cry(fud->conn, "%s: No filename set", __func__);
  8093. return FORM_FIELD_STORAGE_ABORT;
  8094. }
  8095. mg_snprintf(fud->conn,
  8096. &truncated,
  8097. path,
  8098. pathlen - 1,
  8099. "%s/%s",
  8100. fud->destination_dir,
  8101. filename);
  8102. if (!truncated) {
  8103. mg_cry(fud->conn, "%s: File path too long", __func__);
  8104. return FORM_FIELD_STORAGE_ABORT;
  8105. }
  8106. return FORM_FIELD_STORAGE_STORE;
  8107. }
  8108. /* Helper function for deprecated mg_upload. */
  8109. static int
  8110. mg_upload_field_get(const char *key,
  8111. const char *value,
  8112. size_t value_size,
  8113. void *user_data)
  8114. {
  8115. /* Function should never be called */
  8116. (void)key;
  8117. (void)value;
  8118. (void)value_size;
  8119. (void)user_data;
  8120. return 0;
  8121. }
  8122. /* Helper function for deprecated mg_upload. */
  8123. static int
  8124. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8125. {
  8126. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8127. (void)file_size;
  8128. fud->num_uploaded_files++;
  8129. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8130. return 0;
  8131. }
  8132. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8133. int
  8134. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8135. {
  8136. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8137. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8138. mg_upload_field_get,
  8139. mg_upload_field_stored,
  8140. 0};
  8141. int ret;
  8142. fdh.user_data = (void *)&fud;
  8143. ret = mg_handle_form_request(conn, &fdh);
  8144. if (ret < 0) {
  8145. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8146. }
  8147. return fud.num_uploaded_files;
  8148. }
  8149. #endif
  8150. static int
  8151. get_first_ssl_listener_index(const struct mg_context *ctx)
  8152. {
  8153. unsigned int i;
  8154. int idx = -1;
  8155. if (ctx) {
  8156. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8157. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8158. }
  8159. }
  8160. return idx;
  8161. }
  8162. static void
  8163. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8164. {
  8165. char host[1025];
  8166. const char *host_header;
  8167. size_t hostlen;
  8168. host_header = mg_get_header(conn, "Host");
  8169. hostlen = sizeof(host);
  8170. if (host_header != NULL) {
  8171. char *pos;
  8172. mg_strlcpy(host, host_header, hostlen);
  8173. host[hostlen - 1] = '\0';
  8174. pos = strchr(host, ':');
  8175. if (pos != NULL) {
  8176. *pos = '\0';
  8177. }
  8178. } else {
  8179. /* Cannot get host from the Host: header.
  8180. * Fallback to our IP address. */
  8181. if (conn) {
  8182. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8183. }
  8184. }
  8185. /* Send host, port, uri and (if it exists) ?query_string */
  8186. if (conn) {
  8187. mg_printf(conn,
  8188. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8189. host,
  8190. (int)ntohs(
  8191. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  8192. conn->request_info.local_uri,
  8193. (conn->request_info.query_string == NULL) ? "" : "?",
  8194. (conn->request_info.query_string == NULL)
  8195. ? ""
  8196. : conn->request_info.query_string);
  8197. }
  8198. }
  8199. static void
  8200. mg_set_handler_type(struct mg_context *ctx,
  8201. const char *uri,
  8202. int handler_type,
  8203. int is_delete_request,
  8204. mg_request_handler handler,
  8205. mg_websocket_connect_handler connect_handler,
  8206. mg_websocket_ready_handler ready_handler,
  8207. mg_websocket_data_handler data_handler,
  8208. mg_websocket_close_handler close_handler,
  8209. mg_authorization_handler auth_handler,
  8210. void *cbdata)
  8211. {
  8212. struct mg_handler_info *tmp_rh, **lastref;
  8213. size_t urilen = strlen(uri);
  8214. if (handler_type == WEBSOCKET_HANDLER) {
  8215. /* assert(handler == NULL); */
  8216. /* assert(is_delete_request || connect_handler!=NULL ||
  8217. * ready_handler!=NULL || data_handler!=NULL ||
  8218. * close_handler!=NULL);
  8219. */
  8220. /* assert(auth_handler == NULL); */
  8221. if (handler != NULL) {
  8222. return;
  8223. }
  8224. if (!is_delete_request && connect_handler == NULL
  8225. && ready_handler == NULL
  8226. && data_handler == NULL
  8227. && close_handler == NULL) {
  8228. return;
  8229. }
  8230. if (auth_handler != NULL) {
  8231. return;
  8232. }
  8233. } else if (handler_type == REQUEST_HANDLER) {
  8234. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8235. * data_handler==NULL && close_handler==NULL); */
  8236. /* assert(is_delete_request || (handler!=NULL));
  8237. */
  8238. /* assert(auth_handler == NULL); */
  8239. if (connect_handler != NULL || ready_handler != NULL
  8240. || data_handler != NULL
  8241. || close_handler != NULL) {
  8242. return;
  8243. }
  8244. if (!is_delete_request && (handler == NULL)) {
  8245. return;
  8246. }
  8247. if (auth_handler != NULL) {
  8248. return;
  8249. }
  8250. } else { /* AUTH_HANDLER */
  8251. /* assert(handler == NULL); */
  8252. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8253. * data_handler==NULL && close_handler==NULL); */
  8254. /* assert(auth_handler != NULL); */
  8255. if (handler != NULL) {
  8256. return;
  8257. }
  8258. if (connect_handler != NULL || ready_handler != NULL
  8259. || data_handler != NULL
  8260. || close_handler != NULL) {
  8261. return;
  8262. }
  8263. if (!is_delete_request && (auth_handler == NULL)) {
  8264. return;
  8265. }
  8266. }
  8267. if (!ctx) {
  8268. return;
  8269. }
  8270. mg_lock_context(ctx);
  8271. /* first try to find an existing handler */
  8272. lastref = &(ctx->handlers);
  8273. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8274. if (tmp_rh->handler_type == handler_type) {
  8275. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8276. if (!is_delete_request) {
  8277. /* update existing handler */
  8278. if (handler_type == REQUEST_HANDLER) {
  8279. tmp_rh->handler = handler;
  8280. } else if (handler_type == WEBSOCKET_HANDLER) {
  8281. tmp_rh->connect_handler = connect_handler;
  8282. tmp_rh->ready_handler = ready_handler;
  8283. tmp_rh->data_handler = data_handler;
  8284. tmp_rh->close_handler = close_handler;
  8285. } else { /* AUTH_HANDLER */
  8286. tmp_rh->auth_handler = auth_handler;
  8287. }
  8288. tmp_rh->cbdata = cbdata;
  8289. } else {
  8290. /* remove existing handler */
  8291. *lastref = tmp_rh->next;
  8292. mg_free(tmp_rh->uri);
  8293. mg_free(tmp_rh);
  8294. }
  8295. mg_unlock_context(ctx);
  8296. return;
  8297. }
  8298. }
  8299. lastref = &(tmp_rh->next);
  8300. }
  8301. if (is_delete_request) {
  8302. /* no handler to set, this was a remove request to a non-existing
  8303. * handler */
  8304. mg_unlock_context(ctx);
  8305. return;
  8306. }
  8307. tmp_rh =
  8308. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8309. if (tmp_rh == NULL) {
  8310. mg_unlock_context(ctx);
  8311. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8312. return;
  8313. }
  8314. tmp_rh->uri = mg_strdup(uri);
  8315. if (!tmp_rh->uri) {
  8316. mg_unlock_context(ctx);
  8317. mg_free(tmp_rh);
  8318. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8319. return;
  8320. }
  8321. tmp_rh->uri_len = urilen;
  8322. if (handler_type == REQUEST_HANDLER) {
  8323. tmp_rh->handler = handler;
  8324. } else if (handler_type == WEBSOCKET_HANDLER) {
  8325. tmp_rh->connect_handler = connect_handler;
  8326. tmp_rh->ready_handler = ready_handler;
  8327. tmp_rh->data_handler = data_handler;
  8328. tmp_rh->close_handler = close_handler;
  8329. } else { /* AUTH_HANDLER */
  8330. tmp_rh->auth_handler = auth_handler;
  8331. }
  8332. tmp_rh->cbdata = cbdata;
  8333. tmp_rh->handler_type = handler_type;
  8334. tmp_rh->next = NULL;
  8335. *lastref = tmp_rh;
  8336. mg_unlock_context(ctx);
  8337. }
  8338. void
  8339. mg_set_request_handler(struct mg_context *ctx,
  8340. const char *uri,
  8341. mg_request_handler handler,
  8342. void *cbdata)
  8343. {
  8344. mg_set_handler_type(ctx,
  8345. uri,
  8346. REQUEST_HANDLER,
  8347. handler == NULL,
  8348. handler,
  8349. NULL,
  8350. NULL,
  8351. NULL,
  8352. NULL,
  8353. NULL,
  8354. cbdata);
  8355. }
  8356. void
  8357. mg_set_websocket_handler(struct mg_context *ctx,
  8358. const char *uri,
  8359. mg_websocket_connect_handler connect_handler,
  8360. mg_websocket_ready_handler ready_handler,
  8361. mg_websocket_data_handler data_handler,
  8362. mg_websocket_close_handler close_handler,
  8363. void *cbdata)
  8364. {
  8365. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8366. && (data_handler == NULL)
  8367. && (close_handler == NULL);
  8368. mg_set_handler_type(ctx,
  8369. uri,
  8370. WEBSOCKET_HANDLER,
  8371. is_delete_request,
  8372. NULL,
  8373. connect_handler,
  8374. ready_handler,
  8375. data_handler,
  8376. close_handler,
  8377. NULL,
  8378. cbdata);
  8379. }
  8380. void
  8381. mg_set_auth_handler(struct mg_context *ctx,
  8382. const char *uri,
  8383. mg_request_handler handler,
  8384. void *cbdata)
  8385. {
  8386. mg_set_handler_type(ctx,
  8387. uri,
  8388. AUTH_HANDLER,
  8389. handler == NULL,
  8390. NULL,
  8391. NULL,
  8392. NULL,
  8393. NULL,
  8394. NULL,
  8395. handler,
  8396. cbdata);
  8397. }
  8398. static int
  8399. get_request_handler(struct mg_connection *conn,
  8400. int handler_type,
  8401. mg_request_handler *handler,
  8402. mg_websocket_connect_handler *connect_handler,
  8403. mg_websocket_ready_handler *ready_handler,
  8404. mg_websocket_data_handler *data_handler,
  8405. mg_websocket_close_handler *close_handler,
  8406. mg_authorization_handler *auth_handler,
  8407. void **cbdata)
  8408. {
  8409. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8410. if (request_info) {
  8411. const char *uri = request_info->local_uri;
  8412. size_t urilen = strlen(uri);
  8413. struct mg_handler_info *tmp_rh;
  8414. if (!conn || !conn->ctx) {
  8415. return 0;
  8416. }
  8417. mg_lock_context(conn->ctx);
  8418. /* first try for an exact match */
  8419. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8420. tmp_rh = tmp_rh->next) {
  8421. if (tmp_rh->handler_type == handler_type) {
  8422. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8423. if (handler_type == WEBSOCKET_HANDLER) {
  8424. *connect_handler = tmp_rh->connect_handler;
  8425. *ready_handler = tmp_rh->ready_handler;
  8426. *data_handler = tmp_rh->data_handler;
  8427. *close_handler = tmp_rh->close_handler;
  8428. } else if (handler_type == REQUEST_HANDLER) {
  8429. *handler = tmp_rh->handler;
  8430. } else { /* AUTH_HANDLER */
  8431. *auth_handler = tmp_rh->auth_handler;
  8432. }
  8433. *cbdata = tmp_rh->cbdata;
  8434. mg_unlock_context(conn->ctx);
  8435. return 1;
  8436. }
  8437. }
  8438. }
  8439. /* next try for a partial match, we will accept uri/something */
  8440. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8441. tmp_rh = tmp_rh->next) {
  8442. if (tmp_rh->handler_type == handler_type) {
  8443. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8444. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8445. if (handler_type == WEBSOCKET_HANDLER) {
  8446. *connect_handler = tmp_rh->connect_handler;
  8447. *ready_handler = tmp_rh->ready_handler;
  8448. *data_handler = tmp_rh->data_handler;
  8449. *close_handler = tmp_rh->close_handler;
  8450. } else if (handler_type == REQUEST_HANDLER) {
  8451. *handler = tmp_rh->handler;
  8452. } else { /* AUTH_HANDLER */
  8453. *auth_handler = tmp_rh->auth_handler;
  8454. }
  8455. *cbdata = tmp_rh->cbdata;
  8456. mg_unlock_context(conn->ctx);
  8457. return 1;
  8458. }
  8459. }
  8460. }
  8461. /* finally try for pattern match */
  8462. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8463. tmp_rh = tmp_rh->next) {
  8464. if (tmp_rh->handler_type == handler_type) {
  8465. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8466. if (handler_type == WEBSOCKET_HANDLER) {
  8467. *connect_handler = tmp_rh->connect_handler;
  8468. *ready_handler = tmp_rh->ready_handler;
  8469. *data_handler = tmp_rh->data_handler;
  8470. *close_handler = tmp_rh->close_handler;
  8471. } else if (handler_type == REQUEST_HANDLER) {
  8472. *handler = tmp_rh->handler;
  8473. } else { /* AUTH_HANDLER */
  8474. *auth_handler = tmp_rh->auth_handler;
  8475. }
  8476. *cbdata = tmp_rh->cbdata;
  8477. mg_unlock_context(conn->ctx);
  8478. return 1;
  8479. }
  8480. }
  8481. }
  8482. mg_unlock_context(conn->ctx);
  8483. }
  8484. return 0; /* none found */
  8485. }
  8486. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8487. static int
  8488. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8489. void *cbdata)
  8490. {
  8491. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8492. if (pcallbacks->websocket_connect) {
  8493. return pcallbacks->websocket_connect(conn);
  8494. }
  8495. /* No handler set - assume "OK" */
  8496. return 0;
  8497. }
  8498. static void
  8499. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8500. {
  8501. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8502. if (pcallbacks->websocket_ready) {
  8503. pcallbacks->websocket_ready(conn);
  8504. }
  8505. }
  8506. static int
  8507. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8508. int bits,
  8509. char *data,
  8510. size_t len,
  8511. void *cbdata)
  8512. {
  8513. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8514. if (pcallbacks->websocket_data) {
  8515. return pcallbacks->websocket_data(conn, bits, data, len);
  8516. }
  8517. /* No handler set - assume "OK" */
  8518. return 1;
  8519. }
  8520. #endif
  8521. /* This is the heart of the Civetweb's logic.
  8522. * This function is called when the request is read, parsed and validated,
  8523. * and Civetweb must decide what action to take: serve a file, or
  8524. * a directory, or call embedded function, etcetera. */
  8525. static void
  8526. handle_request(struct mg_connection *conn)
  8527. {
  8528. if (conn) {
  8529. struct mg_request_info *ri = &conn->request_info;
  8530. char path[PATH_MAX];
  8531. int uri_len, ssl_index;
  8532. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8533. is_put_or_delete_request = 0, is_callback_resource = 0;
  8534. int i;
  8535. struct file file = STRUCT_FILE_INITIALIZER;
  8536. mg_request_handler callback_handler = NULL;
  8537. mg_websocket_connect_handler ws_connect_handler = NULL;
  8538. mg_websocket_ready_handler ws_ready_handler = NULL;
  8539. mg_websocket_data_handler ws_data_handler = NULL;
  8540. mg_websocket_close_handler ws_close_handler = NULL;
  8541. void *callback_data = NULL;
  8542. mg_authorization_handler auth_handler = NULL;
  8543. void *auth_callback_data = NULL;
  8544. #if !defined(NO_FILES)
  8545. time_t curtime = time(NULL);
  8546. char date[64];
  8547. #endif
  8548. path[0] = 0;
  8549. if (!ri) {
  8550. return;
  8551. }
  8552. /* 1. get the request url */
  8553. /* 1.1. split into url and query string */
  8554. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8555. != NULL) {
  8556. *((char *)conn->request_info.query_string++) = '\0';
  8557. }
  8558. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8559. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8560. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8561. if (ssl_index >= 0) {
  8562. redirect_to_https_port(conn, ssl_index);
  8563. } else {
  8564. /* A http to https forward port has been specified,
  8565. * but no https port to forward to. */
  8566. send_http_error(conn,
  8567. 503,
  8568. "%s",
  8569. "Error: SSL forward not configured properly");
  8570. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8571. }
  8572. return;
  8573. }
  8574. uri_len = (int)strlen(ri->local_uri);
  8575. /* 1.3. decode url (if config says so) */
  8576. if (should_decode_url(conn)) {
  8577. mg_url_decode(
  8578. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8579. }
  8580. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8581. * not possible */
  8582. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8583. /* step 1. completed, the url is known now */
  8584. DEBUG_TRACE("URL: %s", ri->local_uri);
  8585. /* 3. if this ip has limited speed, set it for this connection */
  8586. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8587. get_remote_ip(conn),
  8588. ri->local_uri);
  8589. /* 4. call a "handle everything" callback, if registered */
  8590. if (conn->ctx->callbacks.begin_request != NULL) {
  8591. /* Note that since V1.7 the "begin_request" function is called
  8592. * before an authorization check. If an authorization check is
  8593. * required, use a request_handler instead. */
  8594. i = conn->ctx->callbacks.begin_request(conn);
  8595. if (i > 0) {
  8596. /* callback already processed the request. Store the
  8597. return value as a status code for the access log. */
  8598. conn->status_code = i;
  8599. return;
  8600. } else if (i == 0) {
  8601. /* civetweb should process the request */
  8602. } else {
  8603. /* unspecified - may change with the next version */
  8604. return;
  8605. }
  8606. }
  8607. /* request not yet handled by a handler or redirect, so the request
  8608. * is processed here */
  8609. /* 5. interpret the url to find out how the request must be handled
  8610. */
  8611. /* 5.1. first test, if the request targets the regular http(s)://
  8612. * protocol namespace or the websocket ws(s):// protocol namespace.
  8613. */
  8614. is_websocket_request = is_websocket_protocol(conn);
  8615. /* 5.2. check if the request will be handled by a callback */
  8616. if (get_request_handler(conn,
  8617. is_websocket_request ? WEBSOCKET_HANDLER
  8618. : REQUEST_HANDLER,
  8619. &callback_handler,
  8620. &ws_connect_handler,
  8621. &ws_ready_handler,
  8622. &ws_data_handler,
  8623. &ws_close_handler,
  8624. NULL,
  8625. &callback_data)) {
  8626. /* 5.2.1. A callback will handle this request. All requests
  8627. * handled
  8628. * by a callback have to be considered as requests to a script
  8629. * resource. */
  8630. is_callback_resource = 1;
  8631. is_script_resource = 1;
  8632. is_put_or_delete_request = is_put_or_delete_method(conn);
  8633. } else {
  8634. no_callback_resource:
  8635. /* 5.2.2. No callback is responsible for this request. The URI
  8636. * addresses a file based resource (static content or Lua/cgi
  8637. * scripts in the file system). */
  8638. is_callback_resource = 0;
  8639. interpret_uri(conn,
  8640. path,
  8641. sizeof(path),
  8642. &file,
  8643. &is_found,
  8644. &is_script_resource,
  8645. &is_websocket_request,
  8646. &is_put_or_delete_request);
  8647. }
  8648. /* 6. authorization check */
  8649. /* 6.1. a custom authorization handler is installed */
  8650. if (get_request_handler(conn,
  8651. AUTH_HANDLER,
  8652. NULL,
  8653. NULL,
  8654. NULL,
  8655. NULL,
  8656. NULL,
  8657. &auth_handler,
  8658. &auth_callback_data)) {
  8659. if (!auth_handler(conn, auth_callback_data)) {
  8660. return;
  8661. }
  8662. } else if (is_put_or_delete_request && !is_script_resource
  8663. && !is_callback_resource) {
  8664. /* 6.2. this request is a PUT/DELETE to a real file */
  8665. /* 6.2.1. thus, the server must have real files */
  8666. #if defined(NO_FILES)
  8667. if (1) {
  8668. #else
  8669. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8670. #endif
  8671. /* This server does not have any real files, thus the
  8672. * PUT/DELETE methods are not valid. */
  8673. send_http_error(conn,
  8674. 405,
  8675. "%s method not allowed",
  8676. conn->request_info.request_method);
  8677. return;
  8678. }
  8679. #if !defined(NO_FILES)
  8680. /* 6.2.2. Check if put authorization for static files is
  8681. * available.
  8682. */
  8683. if (!is_authorized_for_put(conn)) {
  8684. send_authorization_request(conn);
  8685. return;
  8686. }
  8687. #endif
  8688. } else {
  8689. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8690. * or it is a PUT or DELETE request to a resource that does not
  8691. * correspond to a file. Check authorization. */
  8692. if (!check_authorization(conn, path)) {
  8693. send_authorization_request(conn);
  8694. return;
  8695. }
  8696. }
  8697. /* request is authorized or does not need authorization */
  8698. /* 7. check if there are request handlers for this uri */
  8699. if (is_callback_resource) {
  8700. if (!is_websocket_request) {
  8701. i = callback_handler(conn, callback_data);
  8702. if (i > 0) {
  8703. /* Do nothing, callback has served the request. Store
  8704. * the
  8705. * return value as status code for the log and discard
  8706. * all
  8707. * data from the client not used by the callback. */
  8708. conn->status_code = i;
  8709. discard_unread_request_data(conn);
  8710. } else {
  8711. /* TODO (high): what if the handler did NOT handle the
  8712. * request */
  8713. /* The last version did handle this as a file request,
  8714. * but
  8715. * since a file request is not always a script resource,
  8716. * the authorization check might be different */
  8717. interpret_uri(conn,
  8718. path,
  8719. sizeof(path),
  8720. &file,
  8721. &is_found,
  8722. &is_script_resource,
  8723. &is_websocket_request,
  8724. &is_put_or_delete_request);
  8725. callback_handler = NULL;
  8726. /* TODO (very low): goto is deprecated but for the
  8727. * moment,
  8728. * a goto is simpler than some curious loop. */
  8729. /* The situation "callback does not handle the request"
  8730. * needs to be reconsidered anyway. */
  8731. goto no_callback_resource;
  8732. }
  8733. } else {
  8734. #if defined(USE_WEBSOCKET)
  8735. handle_websocket_request(conn,
  8736. path,
  8737. is_callback_resource,
  8738. ws_connect_handler,
  8739. ws_ready_handler,
  8740. ws_data_handler,
  8741. ws_close_handler,
  8742. callback_data);
  8743. #endif
  8744. }
  8745. return;
  8746. }
  8747. /* 8. handle websocket requests */
  8748. #if defined(USE_WEBSOCKET)
  8749. if (is_websocket_request) {
  8750. if (is_script_resource) {
  8751. /* Websocket Lua script */
  8752. handle_websocket_request(conn,
  8753. path,
  8754. 0 /* Lua Script */,
  8755. NULL,
  8756. NULL,
  8757. NULL,
  8758. NULL,
  8759. &conn->ctx->callbacks);
  8760. } else {
  8761. #if defined(MG_LEGACY_INTERFACE)
  8762. handle_websocket_request(
  8763. conn,
  8764. path,
  8765. !is_script_resource /* could be deprecated global callback */,
  8766. deprecated_websocket_connect_wrapper,
  8767. deprecated_websocket_ready_wrapper,
  8768. deprecated_websocket_data_wrapper,
  8769. NULL,
  8770. &conn->ctx->callbacks);
  8771. #else
  8772. send_http_error(conn, 404, "%s", "Not found");
  8773. #endif
  8774. }
  8775. return;
  8776. } else
  8777. #endif
  8778. #if defined(NO_FILES)
  8779. /* 9a. In case the server uses only callbacks, this uri is
  8780. * unknown.
  8781. * Then, all request handling ends here. */
  8782. send_http_error(conn, 404, "%s", "Not Found");
  8783. #else
  8784. /* 9b. This request is either for a static file or resource handled
  8785. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8786. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8787. send_http_error(conn, 404, "%s", "Not Found");
  8788. return;
  8789. }
  8790. /* 10. File is handled by a script. */
  8791. if (is_script_resource) {
  8792. handle_file_based_request(conn, path, &file);
  8793. return;
  8794. }
  8795. /* 11. Handle put/delete/mkcol requests */
  8796. if (is_put_or_delete_request) {
  8797. /* 11.1. PUT method */
  8798. if (!strcmp(ri->request_method, "PUT")) {
  8799. put_file(conn, path);
  8800. return;
  8801. }
  8802. /* 11.2. DELETE method */
  8803. if (!strcmp(ri->request_method, "DELETE")) {
  8804. delete_file(conn, path);
  8805. return;
  8806. }
  8807. /* 11.3. MKCOL method */
  8808. if (!strcmp(ri->request_method, "MKCOL")) {
  8809. mkcol(conn, path);
  8810. return;
  8811. }
  8812. /* 11.4. PATCH method
  8813. * This method is not supported for static resources,
  8814. * only for scripts (Lua, CGI) and callbacks. */
  8815. send_http_error(conn,
  8816. 405,
  8817. "%s method not allowed",
  8818. conn->request_info.request_method);
  8819. return;
  8820. }
  8821. /* 11. File does not exist, or it was configured that it should be
  8822. * hidden */
  8823. if (!is_found || (must_hide_file(conn, path))) {
  8824. send_http_error(conn, 404, "%s", "Not found");
  8825. return;
  8826. }
  8827. /* 12. Directory uris should end with a slash */
  8828. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8829. gmt_time_string(date, sizeof(date), &curtime);
  8830. mg_printf(conn,
  8831. "HTTP/1.1 301 Moved Permanently\r\n"
  8832. "Location: %s/\r\n"
  8833. "Date: %s\r\n"
  8834. /* "Cache-Control: private\r\n" (= default) */
  8835. "Content-Length: 0\r\n"
  8836. "Connection: %s\r\n\r\n",
  8837. ri->request_uri,
  8838. date,
  8839. suggest_connection_header(conn));
  8840. return;
  8841. }
  8842. /* 13. Handle other methods than GET/HEAD */
  8843. /* 13.1. Handle PROPFIND */
  8844. if (!strcmp(ri->request_method, "PROPFIND")) {
  8845. handle_propfind(conn, path, &file);
  8846. return;
  8847. }
  8848. /* 13.2. Handle OPTIONS for files */
  8849. if (!strcmp(ri->request_method, "OPTIONS")) {
  8850. /* This standard handler is only used for real files.
  8851. * Scripts should support the OPTIONS method themselves, to allow a
  8852. * maximum flexibility.
  8853. * Lua and CGI scripts may fully support CORS this way (including
  8854. * preflights). */
  8855. send_options(conn);
  8856. return;
  8857. }
  8858. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8859. if (0 != strcmp(ri->request_method, "GET")
  8860. && 0 != strcmp(ri->request_method, "HEAD")) {
  8861. send_http_error(conn,
  8862. 405,
  8863. "%s method not allowed",
  8864. conn->request_info.request_method);
  8865. return;
  8866. }
  8867. /* 14. directories */
  8868. if (file.is_directory) {
  8869. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8870. /* 14.1. use a substitute file */
  8871. /* TODO (high): substitute index may be a script resource.
  8872. * define what should be possible in this case. */
  8873. } else {
  8874. /* 14.2. no substitute file */
  8875. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8876. "yes")) {
  8877. handle_directory_request(conn, path);
  8878. } else {
  8879. send_http_error(conn,
  8880. 403,
  8881. "%s",
  8882. "Error: Directory listing denied");
  8883. }
  8884. return;
  8885. }
  8886. }
  8887. handle_file_based_request(conn, path, &file);
  8888. #endif /* !defined(NO_FILES) */
  8889. #if 0
  8890. /* Perform redirect and auth checks before calling begin_request()
  8891. * handler.
  8892. * Otherwise, begin_request() would need to perform auth checks and
  8893. * redirects. */
  8894. #endif
  8895. }
  8896. return;
  8897. }
  8898. static void
  8899. handle_file_based_request(struct mg_connection *conn,
  8900. const char *path,
  8901. struct file *file)
  8902. {
  8903. if (!conn || !conn->ctx) {
  8904. return;
  8905. }
  8906. if (0) {
  8907. #ifdef USE_LUA
  8908. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8909. strlen(
  8910. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8911. path) > 0) {
  8912. /* Lua server page: an SSI like page containing mostly plain html
  8913. * code
  8914. * plus some tags with server generated contents. */
  8915. handle_lsp_request(conn, path, file, NULL);
  8916. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8917. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8918. path) > 0) {
  8919. /* Lua in-server module script: a CGI like script used to generate
  8920. * the
  8921. * entire reply. */
  8922. mg_exec_lua_script(conn, path, NULL);
  8923. #endif
  8924. #if defined(USE_DUKTAPE)
  8925. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8926. strlen(
  8927. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8928. path) > 0) {
  8929. /* Call duktape to generate the page */
  8930. mg_exec_duktape_script(conn, path);
  8931. #endif
  8932. #if !defined(NO_CGI)
  8933. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8934. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8935. path) > 0) {
  8936. /* CGI scripts may support all HTTP methods */
  8937. handle_cgi_request(conn, path);
  8938. #endif /* !NO_CGI */
  8939. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8940. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8941. path) > 0) {
  8942. handle_ssi_file_request(conn, path, file);
  8943. #if !defined(NO_CACHING)
  8944. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8945. /* Send 304 "Not Modified" - this must not send any body data */
  8946. handle_not_modified_static_file_request(conn, file);
  8947. #endif /* !NO_CACHING */
  8948. } else {
  8949. handle_static_file_request(conn, path, file, NULL);
  8950. }
  8951. }
  8952. static void
  8953. close_all_listening_sockets(struct mg_context *ctx)
  8954. {
  8955. unsigned int i;
  8956. if (!ctx) {
  8957. return;
  8958. }
  8959. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8960. closesocket(ctx->listening_sockets[i].sock);
  8961. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8962. }
  8963. mg_free(ctx->listening_sockets);
  8964. ctx->listening_sockets = NULL;
  8965. mg_free(ctx->listening_ports);
  8966. ctx->listening_ports = NULL;
  8967. }
  8968. /* Valid listening port specification is: [ip_address:]port[s]
  8969. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8970. * Examples for IPv6: [::]:80, [::1]:80,
  8971. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8972. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8973. static int
  8974. parse_port_string(const struct vec *vec, struct socket *so)
  8975. {
  8976. unsigned int a, b, c, d, port;
  8977. int ch, len;
  8978. #if defined(USE_IPV6)
  8979. char buf[100] = {0};
  8980. #endif
  8981. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8982. * Also, all-zeroes in the socket address means binding to all addresses
  8983. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8984. memset(so, 0, sizeof(*so));
  8985. so->lsa.sin.sin_family = AF_INET;
  8986. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8987. == 5) {
  8988. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8989. so->lsa.sin.sin_addr.s_addr =
  8990. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8991. so->lsa.sin.sin_port = htons((uint16_t)port);
  8992. #if defined(USE_IPV6)
  8993. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8994. && mg_inet_pton(
  8995. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8996. /* IPv6 address, examples: see above */
  8997. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8998. */
  8999. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9000. #endif
  9001. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9002. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9003. so->lsa.sin.sin_port = htons((uint16_t)port);
  9004. } else {
  9005. /* Parsing failure. Make port invalid. */
  9006. port = 0;
  9007. len = 0;
  9008. }
  9009. /* sscanf and the option splitting code ensure the following condition
  9010. */
  9011. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9012. return 0;
  9013. }
  9014. ch = vec->ptr[len]; /* Next character after the port number */
  9015. so->is_ssl = (ch == 's');
  9016. so->ssl_redir = (ch == 'r');
  9017. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9018. return is_valid_port(port)
  9019. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9020. }
  9021. static int
  9022. set_ports_option(struct mg_context *ctx)
  9023. {
  9024. const char *list;
  9025. int on = 1;
  9026. #if defined(USE_IPV6)
  9027. int off = 0;
  9028. #endif
  9029. struct vec vec;
  9030. struct socket so, *ptr;
  9031. in_port_t *portPtr;
  9032. union usa usa;
  9033. socklen_t len;
  9034. int portsTotal = 0;
  9035. int portsOk = 0;
  9036. if (!ctx) {
  9037. return 0;
  9038. }
  9039. memset(&so, 0, sizeof(so));
  9040. memset(&usa, 0, sizeof(usa));
  9041. len = sizeof(usa);
  9042. list = ctx->config[LISTENING_PORTS];
  9043. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9044. portsTotal++;
  9045. if (!parse_port_string(&vec, &so)) {
  9046. mg_cry(fc(ctx),
  9047. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9048. (int)vec.len,
  9049. vec.ptr,
  9050. portsTotal,
  9051. "[IP_ADDRESS:]PORT[s|r]");
  9052. continue;
  9053. }
  9054. #if !defined(NO_SSL)
  9055. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9056. mg_cry(fc(ctx),
  9057. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9058. "option set?",
  9059. portsTotal);
  9060. continue;
  9061. }
  9062. #endif
  9063. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9064. == INVALID_SOCKET) {
  9065. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9066. continue;
  9067. }
  9068. #ifdef _WIN32
  9069. /* Windows SO_REUSEADDR lets many procs binds to a
  9070. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9071. * if someone already has the socket -- DTL */
  9072. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9073. * Windows might need a few seconds before
  9074. * the same port can be used again in the
  9075. * same process, so a short Sleep may be
  9076. * required between mg_stop and mg_start.
  9077. */
  9078. if (setsockopt(so.sock,
  9079. SOL_SOCKET,
  9080. SO_EXCLUSIVEADDRUSE,
  9081. (SOCK_OPT_TYPE)&on,
  9082. sizeof(on)) != 0) {
  9083. mg_cry(fc(ctx),
  9084. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9085. portsTotal);
  9086. }
  9087. #else
  9088. if (setsockopt(so.sock,
  9089. SOL_SOCKET,
  9090. SO_REUSEADDR,
  9091. (SOCK_OPT_TYPE)&on,
  9092. sizeof(on)) != 0) {
  9093. mg_cry(fc(ctx),
  9094. "cannot set socket option SO_REUSEADDR (entry %i)",
  9095. portsTotal);
  9096. }
  9097. #endif
  9098. #if defined(USE_IPV6)
  9099. if (so.lsa.sa.sa_family == AF_INET6
  9100. && setsockopt(so.sock,
  9101. IPPROTO_IPV6,
  9102. IPV6_V6ONLY,
  9103. (void *)&off,
  9104. sizeof(off)) != 0) {
  9105. mg_cry(fc(ctx),
  9106. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9107. portsTotal);
  9108. }
  9109. #endif
  9110. if (so.lsa.sa.sa_family == AF_INET) {
  9111. len = sizeof(so.lsa.sin);
  9112. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9113. mg_cry(fc(ctx),
  9114. "cannot bind to %.*s: %d (%s)",
  9115. (int)vec.len,
  9116. vec.ptr,
  9117. (int)ERRNO,
  9118. strerror(errno));
  9119. closesocket(so.sock);
  9120. so.sock = INVALID_SOCKET;
  9121. continue;
  9122. }
  9123. }
  9124. #if defined(USE_IPV6)
  9125. else if (so.lsa.sa.sa_family == AF_INET6) {
  9126. len = sizeof(so.lsa.sin6);
  9127. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9128. mg_cry(fc(ctx),
  9129. "cannot bind to IPv6 %.*s: %d (%s)",
  9130. (int)vec.len,
  9131. vec.ptr,
  9132. (int)ERRNO,
  9133. strerror(errno));
  9134. closesocket(so.sock);
  9135. so.sock = INVALID_SOCKET;
  9136. continue;
  9137. }
  9138. }
  9139. #endif
  9140. else {
  9141. mg_cry(fc(ctx),
  9142. "cannot bind: address family not supported (entry %i)",
  9143. portsTotal);
  9144. continue;
  9145. }
  9146. if (listen(so.sock, SOMAXCONN) != 0) {
  9147. mg_cry(fc(ctx),
  9148. "cannot listen to %.*s: %d (%s)",
  9149. (int)vec.len,
  9150. vec.ptr,
  9151. (int)ERRNO,
  9152. strerror(errno));
  9153. closesocket(so.sock);
  9154. so.sock = INVALID_SOCKET;
  9155. continue;
  9156. }
  9157. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  9158. int err = (int)ERRNO;
  9159. mg_cry(fc(ctx),
  9160. "call to getsockname failed %.*s: %d (%s)",
  9161. (int)vec.len,
  9162. vec.ptr,
  9163. err,
  9164. strerror(errno));
  9165. closesocket(so.sock);
  9166. so.sock = INVALID_SOCKET;
  9167. continue;
  9168. }
  9169. if ((ptr = (struct socket *)
  9170. mg_realloc(ctx->listening_sockets,
  9171. (ctx->num_listening_sockets + 1)
  9172. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9173. mg_cry(fc(ctx), "%s", "Out of memory");
  9174. closesocket(so.sock);
  9175. so.sock = INVALID_SOCKET;
  9176. continue;
  9177. }
  9178. if ((portPtr =
  9179. (in_port_t *)mg_realloc(ctx->listening_ports,
  9180. (ctx->num_listening_sockets + 1)
  9181. * sizeof(ctx->listening_ports[0])))
  9182. == NULL) {
  9183. mg_cry(fc(ctx), "%s", "Out of memory");
  9184. closesocket(so.sock);
  9185. so.sock = INVALID_SOCKET;
  9186. mg_free(ptr);
  9187. continue;
  9188. }
  9189. set_close_on_exec(so.sock, fc(ctx));
  9190. ctx->listening_sockets = ptr;
  9191. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9192. ctx->listening_ports = portPtr;
  9193. ctx->listening_ports[ctx->num_listening_sockets] =
  9194. ntohs(usa.sin.sin_port);
  9195. ctx->num_listening_sockets++;
  9196. portsOk++;
  9197. }
  9198. if (portsOk != portsTotal) {
  9199. close_all_listening_sockets(ctx);
  9200. portsOk = 0;
  9201. }
  9202. return portsOk;
  9203. }
  9204. static const char *
  9205. header_val(const struct mg_connection *conn, const char *header)
  9206. {
  9207. const char *header_value;
  9208. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9209. return "-";
  9210. } else {
  9211. return header_value;
  9212. }
  9213. }
  9214. static void
  9215. log_access(const struct mg_connection *conn)
  9216. {
  9217. const struct mg_request_info *ri;
  9218. struct file fi;
  9219. char date[64], src_addr[IP_ADDR_STR_LEN];
  9220. struct tm *tm;
  9221. const char *referer;
  9222. const char *user_agent;
  9223. char buf[4096];
  9224. if (!conn || !conn->ctx) {
  9225. return;
  9226. }
  9227. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9228. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9229. == 0) {
  9230. fi.fp = NULL;
  9231. }
  9232. } else {
  9233. fi.fp = NULL;
  9234. }
  9235. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9236. return;
  9237. }
  9238. tm = localtime(&conn->conn_birth_time);
  9239. if (tm != NULL) {
  9240. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9241. } else {
  9242. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9243. date[sizeof(date) - 1] = '\0';
  9244. }
  9245. ri = &conn->request_info;
  9246. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9247. referer = header_val(conn, "Referer");
  9248. user_agent = header_val(conn, "User-Agent");
  9249. mg_snprintf(conn,
  9250. NULL, /* Ignore truncation in access log */
  9251. buf,
  9252. sizeof(buf),
  9253. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9254. src_addr,
  9255. ri->remote_user == NULL ? "-" : ri->remote_user,
  9256. date,
  9257. ri->request_method ? ri->request_method : "-",
  9258. ri->request_uri ? ri->request_uri : "-",
  9259. ri->query_string ? "?" : "",
  9260. ri->query_string ? ri->query_string : "",
  9261. ri->http_version,
  9262. conn->status_code,
  9263. conn->num_bytes_sent,
  9264. referer,
  9265. user_agent);
  9266. if (conn->ctx->callbacks.log_access) {
  9267. conn->ctx->callbacks.log_access(conn, buf);
  9268. }
  9269. if (fi.fp) {
  9270. flockfile(fi.fp);
  9271. fprintf(fi.fp, "%s\n", buf);
  9272. fflush(fi.fp);
  9273. funlockfile(fi.fp);
  9274. mg_fclose(&fi);
  9275. }
  9276. }
  9277. /* Verify given socket address against the ACL.
  9278. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9279. */
  9280. static int
  9281. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9282. {
  9283. int allowed, flag;
  9284. uint32_t net, mask;
  9285. struct vec vec;
  9286. if (ctx) {
  9287. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9288. /* If any ACL is set, deny by default */
  9289. allowed = list == NULL ? '+' : '-';
  9290. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9291. flag = vec.ptr[0];
  9292. if ((flag != '+' && flag != '-')
  9293. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9294. mg_cry(fc(ctx),
  9295. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9296. __func__);
  9297. return -1;
  9298. }
  9299. if (net == (remote_ip & mask)) {
  9300. allowed = flag;
  9301. }
  9302. }
  9303. return allowed == '+';
  9304. }
  9305. return -1;
  9306. }
  9307. #if !defined(_WIN32)
  9308. static int
  9309. set_uid_option(struct mg_context *ctx)
  9310. {
  9311. struct passwd *pw;
  9312. if (ctx) {
  9313. const char *uid = ctx->config[RUN_AS_USER];
  9314. int success = 0;
  9315. if (uid == NULL) {
  9316. success = 1;
  9317. } else {
  9318. if ((pw = getpwnam(uid)) == NULL) {
  9319. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9320. } else if (setgid(pw->pw_gid) == -1) {
  9321. mg_cry(fc(ctx),
  9322. "%s: setgid(%s): %s",
  9323. __func__,
  9324. uid,
  9325. strerror(errno));
  9326. } else if (setgroups(0, NULL)) {
  9327. mg_cry(fc(ctx),
  9328. "%s: setgroups(): %s",
  9329. __func__,
  9330. strerror(errno));
  9331. } else if (setuid(pw->pw_uid) == -1) {
  9332. mg_cry(fc(ctx),
  9333. "%s: setuid(%s): %s",
  9334. __func__,
  9335. uid,
  9336. strerror(errno));
  9337. } else {
  9338. success = 1;
  9339. }
  9340. }
  9341. return success;
  9342. }
  9343. return 0;
  9344. }
  9345. #endif /* !_WIN32 */
  9346. static void
  9347. tls_dtor(void *key)
  9348. {
  9349. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9350. /* key == pthread_getspecific(sTlsKey); */
  9351. if (tls) {
  9352. if (tls->is_master == 2) {
  9353. tls->is_master = -3; /* Mark memory as dead */
  9354. mg_free(tls);
  9355. }
  9356. }
  9357. pthread_setspecific(sTlsKey, NULL);
  9358. }
  9359. #if !defined(NO_SSL)
  9360. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9361. static unsigned long
  9362. ssl_id_callback(void)
  9363. {
  9364. #ifdef _WIN32
  9365. return GetCurrentThreadId();
  9366. #else
  9367. #ifdef __clang__
  9368. #pragma clang diagnostic push
  9369. #pragma clang diagnostic ignored "-Wunreachable-code"
  9370. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9371. * or not, so one of the two conditions will be unreachable by construction.
  9372. * Unfortunately the C standard does not define a way to check this at
  9373. * compile time, since the #if preprocessor conditions can not use the sizeof
  9374. * operator as an argument. */
  9375. #endif
  9376. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9377. /* This is the problematic case for CRYPTO_set_id_callback:
  9378. * The OS pthread_t can not be cast to unsigned long. */
  9379. struct mg_workerTLS *tls =
  9380. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9381. if (tls == NULL) {
  9382. /* SSL called from an unknown thread: Create some thread index.
  9383. */
  9384. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9385. tls->is_master = -2; /* -2 means "3rd party thread" */
  9386. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9387. pthread_setspecific(sTlsKey, tls);
  9388. }
  9389. return tls->thread_idx;
  9390. } else {
  9391. /* pthread_t may be any data type, so a simple cast to unsigned long
  9392. * can rise a warning/error, depending on the platform.
  9393. * Here memcpy is used as an anything-to-anything cast. */
  9394. unsigned long ret = 0;
  9395. pthread_t t = pthread_self();
  9396. memcpy(&ret, &t, sizeof(pthread_t));
  9397. return ret;
  9398. }
  9399. #ifdef __clang__
  9400. #pragma clang diagnostic pop
  9401. #endif
  9402. #endif
  9403. }
  9404. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9405. static const char *ssl_error(void);
  9406. static int
  9407. refresh_trust(struct mg_connection *conn)
  9408. {
  9409. static int reload_lock = 0;
  9410. static long int data_check = 0;
  9411. struct stat cert_buf;
  9412. long int t;
  9413. char *pem;
  9414. int should_verify_peer;
  9415. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9416. && conn->ctx->callbacks.init_ssl == NULL) {
  9417. return 0;
  9418. }
  9419. t = data_check;
  9420. if (stat(pem, &cert_buf) != -1) {
  9421. t = (long int)cert_buf.st_mtime;
  9422. }
  9423. if (data_check != t) {
  9424. data_check = t;
  9425. should_verify_peer =
  9426. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9427. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9428. == 0);
  9429. if (should_verify_peer) {
  9430. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9431. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9432. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9433. ca_file,
  9434. ca_path) != 1) {
  9435. mg_cry(fc(conn->ctx),
  9436. "SSL_CTX_load_verify_locations error: %s "
  9437. "ssl_verify_peer requires setting "
  9438. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9439. "present in "
  9440. "the .conf file?",
  9441. ssl_error());
  9442. return 0;
  9443. }
  9444. }
  9445. if (!reload_lock) {
  9446. reload_lock = 1;
  9447. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9448. return 0;
  9449. }
  9450. reload_lock = 0;
  9451. }
  9452. }
  9453. /* lock while cert is reloading */
  9454. while (reload_lock) {
  9455. sleep(1);
  9456. }
  9457. return 1;
  9458. }
  9459. static pthread_mutex_t *ssl_mutexes;
  9460. static int
  9461. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9462. {
  9463. int ret, err;
  9464. int short_trust;
  9465. if (!conn) {
  9466. return 0;
  9467. }
  9468. short_trust =
  9469. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9470. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9471. if (short_trust) {
  9472. int trust_ret = refresh_trust(conn);
  9473. if (!trust_ret) {
  9474. return trust_ret;
  9475. }
  9476. }
  9477. conn->ssl = SSL_new(s);
  9478. if (conn->ssl == NULL) {
  9479. return 0;
  9480. }
  9481. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9482. if (ret != 1) {
  9483. err = SSL_get_error(conn->ssl, ret);
  9484. (void)err; /* TODO: set some error message */
  9485. SSL_free(conn->ssl);
  9486. conn->ssl = NULL;
  9487. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9488. /* see
  9489. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9490. ERR_remove_state(0);
  9491. return 0;
  9492. }
  9493. ret = func(conn->ssl);
  9494. if (ret != 1) {
  9495. err = SSL_get_error(conn->ssl, ret);
  9496. (void)err; /* TODO: set some error message */
  9497. SSL_free(conn->ssl);
  9498. conn->ssl = NULL;
  9499. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9500. /* see
  9501. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9502. ERR_remove_state(0);
  9503. return 0;
  9504. }
  9505. return 1;
  9506. }
  9507. /* Return OpenSSL error message (from CRYPTO lib) */
  9508. static const char *
  9509. ssl_error(void)
  9510. {
  9511. unsigned long err;
  9512. err = ERR_get_error();
  9513. return err == 0 ? "" : ERR_error_string(err, NULL);
  9514. }
  9515. static void
  9516. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9517. {
  9518. (void)line;
  9519. (void)file;
  9520. if (mode & 1) {
  9521. /* 1 is CRYPTO_LOCK */
  9522. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9523. } else {
  9524. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9525. }
  9526. }
  9527. #if !defined(NO_SSL_DL)
  9528. static void *
  9529. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9530. {
  9531. union {
  9532. void *p;
  9533. void (*fp)(void);
  9534. } u;
  9535. void *dll_handle;
  9536. struct ssl_func *fp;
  9537. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9538. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9539. return NULL;
  9540. }
  9541. for (fp = sw; fp->name != NULL; fp++) {
  9542. #ifdef _WIN32
  9543. /* GetProcAddress() returns pointer to function */
  9544. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9545. #else
  9546. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9547. * pointers to function pointers. We need to use a union to make a
  9548. * cast. */
  9549. u.p = dlsym(dll_handle, fp->name);
  9550. #endif /* _WIN32 */
  9551. if (u.fp == NULL) {
  9552. mg_cry(fc(ctx),
  9553. "%s: %s: cannot find %s",
  9554. __func__,
  9555. dll_name,
  9556. fp->name);
  9557. dlclose(dll_handle);
  9558. return NULL;
  9559. } else {
  9560. fp->ptr = u.fp;
  9561. }
  9562. }
  9563. return dll_handle;
  9564. }
  9565. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9566. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9567. #endif /* NO_SSL_DL */
  9568. #if defined(SSL_ALREADY_INITIALIZED)
  9569. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9570. #else
  9571. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9572. #endif
  9573. static int
  9574. initialize_ssl(struct mg_context *ctx)
  9575. {
  9576. int i;
  9577. size_t size;
  9578. #if !defined(NO_SSL_DL)
  9579. if (!cryptolib_dll_handle) {
  9580. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9581. if (!cryptolib_dll_handle) {
  9582. return 0;
  9583. }
  9584. }
  9585. #endif /* NO_SSL_DL */
  9586. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9587. return 1;
  9588. }
  9589. /* Initialize locking callbacks, needed for thread safety.
  9590. * http://www.openssl.org/support/faq.html#PROG1
  9591. */
  9592. i = CRYPTO_num_locks();
  9593. if (i < 0) {
  9594. i = 0;
  9595. }
  9596. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9597. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9598. mg_cry(fc(ctx),
  9599. "%s: cannot allocate mutexes: %s",
  9600. __func__,
  9601. ssl_error());
  9602. return 0;
  9603. }
  9604. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9605. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9606. }
  9607. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9608. CRYPTO_set_id_callback(&ssl_id_callback);
  9609. return 1;
  9610. }
  9611. static int
  9612. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9613. {
  9614. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9615. mg_cry(fc(ctx),
  9616. "%s: cannot open certificate file %s: %s",
  9617. __func__,
  9618. pem,
  9619. ssl_error());
  9620. return 0;
  9621. }
  9622. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9623. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9624. mg_cry(fc(ctx),
  9625. "%s: cannot open private key file %s: %s",
  9626. __func__,
  9627. pem,
  9628. ssl_error());
  9629. return 0;
  9630. }
  9631. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9632. mg_cry(fc(ctx),
  9633. "%s: certificate and private key do not match: %s",
  9634. __func__,
  9635. pem);
  9636. return 0;
  9637. }
  9638. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9639. mg_cry(fc(ctx),
  9640. "%s: cannot use certificate chain file %s: %s",
  9641. __func__,
  9642. pem,
  9643. ssl_error());
  9644. return 0;
  9645. }
  9646. return 1;
  9647. }
  9648. static long
  9649. ssl_get_protocol(int version_id)
  9650. {
  9651. long ret = SSL_OP_ALL;
  9652. if (version_id > 0)
  9653. ret |= SSL_OP_NO_SSLv2;
  9654. if (version_id > 1)
  9655. ret |= SSL_OP_NO_SSLv3;
  9656. if (version_id > 2)
  9657. ret |= SSL_OP_NO_TLSv1;
  9658. if (version_id > 3)
  9659. ret |= SSL_OP_NO_TLSv1_1;
  9660. return ret;
  9661. }
  9662. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9663. static int
  9664. set_ssl_option(struct mg_context *ctx)
  9665. {
  9666. const char *pem;
  9667. int callback_ret;
  9668. int should_verify_peer;
  9669. const char *ca_path;
  9670. const char *ca_file;
  9671. int use_default_verify_paths;
  9672. int verify_depth;
  9673. time_t now_rt = time(NULL);
  9674. struct timespec now_mt;
  9675. md5_byte_t ssl_context_id[16];
  9676. md5_state_t md5state;
  9677. int protocol_ver;
  9678. /* If PEM file is not specified and the init_ssl callback
  9679. * is not specified, skip SSL initialization. */
  9680. if (!ctx) {
  9681. return 0;
  9682. }
  9683. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9684. && ctx->callbacks.init_ssl == NULL) {
  9685. return 1;
  9686. }
  9687. if (!initialize_ssl(ctx)) {
  9688. return 0;
  9689. }
  9690. #if !defined(NO_SSL_DL)
  9691. if (!ssllib_dll_handle) {
  9692. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9693. if (!ssllib_dll_handle) {
  9694. return 0;
  9695. }
  9696. }
  9697. #endif /* NO_SSL_DL */
  9698. /* Initialize SSL library */
  9699. SSL_library_init();
  9700. SSL_load_error_strings();
  9701. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9702. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9703. return 0;
  9704. }
  9705. SSL_CTX_clear_options(ctx->ssl_ctx,
  9706. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9707. | SSL_OP_NO_TLSv1_1);
  9708. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9709. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9710. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9711. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9712. /* If a callback has been specified, call it. */
  9713. callback_ret =
  9714. (ctx->callbacks.init_ssl == NULL)
  9715. ? 0
  9716. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9717. /* If callback returns 0, civetweb sets up the SSL certificate.
  9718. * If it returns 1, civetweb assumes the calback already did this.
  9719. * If it returns -1, initializing ssl fails. */
  9720. if (callback_ret < 0) {
  9721. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9722. return 0;
  9723. }
  9724. if (callback_ret > 0) {
  9725. if (pem != NULL) {
  9726. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9727. }
  9728. return 1;
  9729. }
  9730. /* Use some UID as session context ID. */
  9731. md5_init(&md5state);
  9732. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9733. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9734. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9735. md5_append(&md5state,
  9736. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9737. strlen(ctx->config[LISTENING_PORTS]));
  9738. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9739. md5_finish(&md5state, ssl_context_id);
  9740. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9741. (const unsigned char *)&ssl_context_id,
  9742. sizeof(ssl_context_id));
  9743. if (pem != NULL) {
  9744. if (!ssl_use_pem_file(ctx, pem)) {
  9745. return 0;
  9746. }
  9747. }
  9748. should_verify_peer =
  9749. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9750. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9751. use_default_verify_paths =
  9752. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9753. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9754. if (should_verify_peer) {
  9755. ca_path = ctx->config[SSL_CA_PATH];
  9756. ca_file = ctx->config[SSL_CA_FILE];
  9757. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9758. != 1) {
  9759. mg_cry(fc(ctx),
  9760. "SSL_CTX_load_verify_locations error: %s "
  9761. "ssl_verify_peer requires setting "
  9762. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9763. "present in "
  9764. "the .conf file?",
  9765. ssl_error());
  9766. return 0;
  9767. }
  9768. SSL_CTX_set_verify(ctx->ssl_ctx,
  9769. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9770. NULL);
  9771. if (use_default_verify_paths
  9772. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9773. mg_cry(fc(ctx),
  9774. "SSL_CTX_set_default_verify_paths error: %s",
  9775. ssl_error());
  9776. return 0;
  9777. }
  9778. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9779. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9780. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9781. }
  9782. }
  9783. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9784. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9785. != 1) {
  9786. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9787. }
  9788. }
  9789. return 1;
  9790. }
  9791. static void
  9792. uninitialize_ssl(struct mg_context *ctx)
  9793. {
  9794. int i;
  9795. (void)ctx;
  9796. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9797. /* Shutdown according to
  9798. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9799. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9800. */
  9801. CRYPTO_set_locking_callback(NULL);
  9802. CRYPTO_set_id_callback(NULL);
  9803. ENGINE_cleanup();
  9804. CONF_modules_unload(1);
  9805. ERR_free_strings();
  9806. EVP_cleanup();
  9807. CRYPTO_cleanup_all_ex_data();
  9808. ERR_remove_state(0);
  9809. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9810. pthread_mutex_destroy(&ssl_mutexes[i]);
  9811. }
  9812. mg_free(ssl_mutexes);
  9813. ssl_mutexes = NULL;
  9814. }
  9815. }
  9816. #endif /* !NO_SSL */
  9817. static int
  9818. set_gpass_option(struct mg_context *ctx)
  9819. {
  9820. if (ctx) {
  9821. struct file file = STRUCT_FILE_INITIALIZER;
  9822. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9823. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9824. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9825. return 0;
  9826. }
  9827. return 1;
  9828. }
  9829. return 0;
  9830. }
  9831. static int
  9832. set_acl_option(struct mg_context *ctx)
  9833. {
  9834. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9835. }
  9836. static void
  9837. reset_per_request_attributes(struct mg_connection *conn)
  9838. {
  9839. if (!conn) {
  9840. return;
  9841. }
  9842. conn->path_info = NULL;
  9843. conn->num_bytes_sent = conn->consumed_content = 0;
  9844. conn->status_code = -1;
  9845. conn->is_chunked = 0;
  9846. conn->must_close = conn->request_len = conn->throttle = 0;
  9847. conn->request_info.content_length = -1;
  9848. conn->request_info.remote_user = NULL;
  9849. conn->request_info.request_method = NULL;
  9850. conn->request_info.request_uri = NULL;
  9851. conn->request_info.local_uri = NULL;
  9852. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9853. * local_uri and request_uri */
  9854. conn->request_info.http_version = NULL;
  9855. conn->request_info.num_headers = 0;
  9856. conn->data_len = 0;
  9857. conn->chunk_remainder = 0;
  9858. conn->internal_error = 0;
  9859. }
  9860. static int
  9861. set_sock_timeout(SOCKET sock, int milliseconds)
  9862. {
  9863. int r0 = 0, r1, r2;
  9864. #ifdef _WIN32
  9865. /* Windows specific */
  9866. DWORD tv = (DWORD)milliseconds;
  9867. #else
  9868. /* Linux, ... (not Windows) */
  9869. struct timeval tv;
  9870. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9871. * max. time waiting for the acknowledged of TCP data before the connection
  9872. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9873. * If this option is not set, the default timeout of 20-30 minutes is used.
  9874. */
  9875. /* #define TCP_USER_TIMEOUT (18) */
  9876. #if defined(TCP_USER_TIMEOUT)
  9877. unsigned int uto = (unsigned int)milliseconds;
  9878. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9879. #endif
  9880. memset(&tv, 0, sizeof(tv));
  9881. tv.tv_sec = milliseconds / 1000;
  9882. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9883. #endif /* _WIN32 */
  9884. r1 = setsockopt(
  9885. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9886. r2 = setsockopt(
  9887. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9888. return r0 || r1 || r2;
  9889. }
  9890. static int
  9891. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9892. {
  9893. if (setsockopt(sock,
  9894. IPPROTO_TCP,
  9895. TCP_NODELAY,
  9896. (SOCK_OPT_TYPE)&nodelay_on,
  9897. sizeof(nodelay_on)) != 0) {
  9898. /* Error */
  9899. return 1;
  9900. }
  9901. /* OK */
  9902. return 0;
  9903. }
  9904. static void
  9905. close_socket_gracefully(struct mg_connection *conn)
  9906. {
  9907. #if defined(_WIN32)
  9908. char buf[MG_BUF_LEN];
  9909. int n;
  9910. #endif
  9911. struct linger linger;
  9912. if (!conn) {
  9913. return;
  9914. }
  9915. /* Set linger option to avoid socket hanging out after close. This
  9916. * prevent
  9917. * ephemeral port exhaust problem under high QPS. */
  9918. linger.l_onoff = 1;
  9919. linger.l_linger = 1;
  9920. if (setsockopt(conn->client.sock,
  9921. SOL_SOCKET,
  9922. SO_LINGER,
  9923. (char *)&linger,
  9924. sizeof(linger)) != 0) {
  9925. mg_cry(conn,
  9926. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9927. __func__,
  9928. strerror(ERRNO));
  9929. }
  9930. /* Send FIN to the client */
  9931. shutdown(conn->client.sock, SHUT_WR);
  9932. set_non_blocking_mode(conn->client.sock);
  9933. #if defined(_WIN32)
  9934. /* Read and discard pending incoming data. If we do not do that and
  9935. * close
  9936. * the socket, the data in the send buffer may be discarded. This
  9937. * behaviour is seen on Windows, when client keeps sending data
  9938. * when server decides to close the connection; then when client
  9939. * does recv() it gets no data back. */
  9940. do {
  9941. n = pull(
  9942. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9943. } while (n > 0);
  9944. #endif
  9945. /* Now we know that our FIN is ACK-ed, safe to close */
  9946. closesocket(conn->client.sock);
  9947. conn->client.sock = INVALID_SOCKET;
  9948. }
  9949. static void
  9950. close_connection(struct mg_connection *conn)
  9951. {
  9952. if (!conn || !conn->ctx) {
  9953. return;
  9954. }
  9955. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9956. if (conn->lua_websocket_state) {
  9957. lua_websocket_close(conn, conn->lua_websocket_state);
  9958. conn->lua_websocket_state = NULL;
  9959. }
  9960. #endif
  9961. /* call the connection_close callback if assigned */
  9962. if ((conn->ctx->callbacks.connection_close != NULL)
  9963. && (conn->ctx->context_type == 1)) {
  9964. conn->ctx->callbacks.connection_close(conn);
  9965. }
  9966. mg_lock_connection(conn);
  9967. conn->must_close = 1;
  9968. #ifndef NO_SSL
  9969. if (conn->ssl != NULL) {
  9970. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9971. */
  9972. SSL_shutdown(conn->ssl);
  9973. SSL_free(conn->ssl);
  9974. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9975. /* see
  9976. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9977. ERR_remove_state(0);
  9978. conn->ssl = NULL;
  9979. }
  9980. #endif
  9981. if (conn->client.sock != INVALID_SOCKET) {
  9982. close_socket_gracefully(conn);
  9983. conn->client.sock = INVALID_SOCKET;
  9984. }
  9985. mg_unlock_connection(conn);
  9986. }
  9987. void
  9988. mg_close_connection(struct mg_connection *conn)
  9989. {
  9990. struct mg_context *client_ctx = NULL;
  9991. unsigned int i;
  9992. if (conn == NULL) {
  9993. return;
  9994. }
  9995. if (conn->ctx->context_type == 2) {
  9996. client_ctx = conn->ctx;
  9997. /* client context: loops must end */
  9998. conn->ctx->stop_flag = 1;
  9999. }
  10000. #ifndef NO_SSL
  10001. if (conn->client_ssl_ctx != NULL) {
  10002. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10003. }
  10004. #endif
  10005. close_connection(conn);
  10006. if (client_ctx != NULL) {
  10007. /* join worker thread and free context */
  10008. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10009. if (client_ctx->workerthreadids[i] != 0) {
  10010. mg_join_thread(client_ctx->workerthreadids[i]);
  10011. }
  10012. }
  10013. mg_free(client_ctx->workerthreadids);
  10014. mg_free(client_ctx);
  10015. (void)pthread_mutex_destroy(&conn->mutex);
  10016. mg_free(conn);
  10017. }
  10018. }
  10019. static struct mg_connection *
  10020. mg_connect_client_impl(const struct mg_client_options *client_options,
  10021. int use_ssl,
  10022. char *ebuf,
  10023. size_t ebuf_len)
  10024. {
  10025. static struct mg_context fake_ctx;
  10026. struct mg_connection *conn = NULL;
  10027. SOCKET sock;
  10028. union usa sa;
  10029. if (!connect_socket(&fake_ctx,
  10030. client_options->host,
  10031. client_options->port,
  10032. use_ssl,
  10033. ebuf,
  10034. ebuf_len,
  10035. &sock,
  10036. &sa)) {
  10037. ;
  10038. } else if ((conn = (struct mg_connection *)
  10039. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10040. mg_snprintf(NULL,
  10041. NULL, /* No truncation check for ebuf */
  10042. ebuf,
  10043. ebuf_len,
  10044. "calloc(): %s",
  10045. strerror(ERRNO));
  10046. closesocket(sock);
  10047. #ifndef NO_SSL
  10048. } else if (use_ssl
  10049. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10050. == NULL) {
  10051. mg_snprintf(NULL,
  10052. NULL, /* No truncation check for ebuf */
  10053. ebuf,
  10054. ebuf_len,
  10055. "SSL_CTX_new error");
  10056. closesocket(sock);
  10057. mg_free(conn);
  10058. conn = NULL;
  10059. #endif /* NO_SSL */
  10060. } else {
  10061. #ifdef USE_IPV6
  10062. socklen_t len = (sa.sa.sa_family == AF_INET)
  10063. ? sizeof(conn->client.rsa.sin)
  10064. : sizeof(conn->client.rsa.sin6);
  10065. struct sockaddr *psa =
  10066. (sa.sa.sa_family == AF_INET)
  10067. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10068. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10069. #else
  10070. socklen_t len = sizeof(conn->client.rsa.sin);
  10071. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10072. #endif
  10073. conn->buf_size = MAX_REQUEST_SIZE;
  10074. conn->buf = (char *)(conn + 1);
  10075. conn->ctx = &fake_ctx;
  10076. conn->client.sock = sock;
  10077. conn->client.lsa = sa;
  10078. if (getsockname(sock, psa, &len) != 0) {
  10079. mg_cry(conn,
  10080. "%s: getsockname() failed: %s",
  10081. __func__,
  10082. strerror(ERRNO));
  10083. }
  10084. conn->client.is_ssl = use_ssl ? 1 : 0;
  10085. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10086. #ifndef NO_SSL
  10087. if (use_ssl) {
  10088. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10089. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10090. * SSL_CTX_set_verify call is needed to switch off server
  10091. * certificate checking, which is off by default in OpenSSL and
  10092. * on in yaSSL. */
  10093. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10094. * SSL_VERIFY_PEER, verify_ssl_server); */
  10095. if (client_options->client_cert) {
  10096. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10097. mg_snprintf(NULL,
  10098. NULL, /* No truncation check for ebuf */
  10099. ebuf,
  10100. ebuf_len,
  10101. "Can not use SSL client certificate");
  10102. SSL_CTX_free(conn->client_ssl_ctx);
  10103. closesocket(sock);
  10104. mg_free(conn);
  10105. conn = NULL;
  10106. }
  10107. }
  10108. if (client_options->server_cert) {
  10109. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10110. client_options->server_cert,
  10111. NULL);
  10112. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10113. } else {
  10114. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10115. }
  10116. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10117. mg_snprintf(NULL,
  10118. NULL, /* No truncation check for ebuf */
  10119. ebuf,
  10120. ebuf_len,
  10121. "SSL connection error");
  10122. SSL_CTX_free(conn->client_ssl_ctx);
  10123. closesocket(sock);
  10124. mg_free(conn);
  10125. conn = NULL;
  10126. }
  10127. }
  10128. #endif
  10129. }
  10130. return conn;
  10131. }
  10132. CIVETWEB_API struct mg_connection *
  10133. mg_connect_client_secure(const struct mg_client_options *client_options,
  10134. char *error_buffer,
  10135. size_t error_buffer_size)
  10136. {
  10137. return mg_connect_client_impl(client_options,
  10138. 1,
  10139. error_buffer,
  10140. error_buffer_size);
  10141. }
  10142. struct mg_connection *
  10143. mg_connect_client(const char *host,
  10144. int port,
  10145. int use_ssl,
  10146. char *error_buffer,
  10147. size_t error_buffer_size)
  10148. {
  10149. struct mg_client_options opts;
  10150. memset(&opts, 0, sizeof(opts));
  10151. opts.host = host;
  10152. opts.port = port;
  10153. return mg_connect_client_impl(&opts,
  10154. use_ssl,
  10155. error_buffer,
  10156. error_buffer_size);
  10157. }
  10158. static const struct {
  10159. const char *proto;
  10160. size_t proto_len;
  10161. unsigned default_port;
  10162. } abs_uri_protocols[] = {{"http://", 7, 80},
  10163. {"https://", 8, 443},
  10164. {"ws://", 5, 80},
  10165. {"wss://", 6, 443},
  10166. {NULL, 0, 0}};
  10167. /* Check if the uri is valid.
  10168. * return 0 for invalid uri,
  10169. * return 1 for *,
  10170. * return 2 for relative uri,
  10171. * return 3 for absolute uri without port,
  10172. * return 4 for absolute uri with port */
  10173. static int
  10174. get_uri_type(const char *uri)
  10175. {
  10176. int i;
  10177. char *hostend, *portbegin, *portend;
  10178. unsigned long port;
  10179. /* According to the HTTP standard
  10180. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10181. * URI can be an asterisk (*) or should start with slash (relative uri),
  10182. * or it should start with the protocol (absolute uri). */
  10183. if (uri[0] == '*' && uri[1] == '\0') {
  10184. /* asterisk */
  10185. return 1;
  10186. }
  10187. if (uri[0] == '/') {
  10188. /* relative uri */
  10189. return 2;
  10190. }
  10191. /* It could be an absolute uri: */
  10192. /* This function only checks if the uri is valid, not if it is
  10193. * addressing the current server. So civetweb can also be used
  10194. * as a proxy server. */
  10195. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10196. if (mg_strncasecmp(uri,
  10197. abs_uri_protocols[i].proto,
  10198. abs_uri_protocols[i].proto_len) == 0) {
  10199. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10200. if (!hostend) {
  10201. return 0;
  10202. }
  10203. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10204. if (!portbegin) {
  10205. return 3;
  10206. }
  10207. port = strtoul(portbegin + 1, &portend, 10);
  10208. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10209. return 0;
  10210. }
  10211. return 4;
  10212. }
  10213. }
  10214. return 0;
  10215. }
  10216. /* Return NULL or the relative uri at the current server */
  10217. static const char *
  10218. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10219. {
  10220. const char *server_domain;
  10221. size_t server_domain_len;
  10222. size_t request_domain_len = 0;
  10223. unsigned long port = 0;
  10224. int i;
  10225. const char *hostbegin = NULL;
  10226. const char *hostend = NULL;
  10227. const char *portbegin;
  10228. char *portend;
  10229. /* DNS is case insensitive, so use case insensitive string compare here
  10230. */
  10231. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10232. if (!server_domain) {
  10233. return 0;
  10234. }
  10235. server_domain_len = strlen(server_domain);
  10236. if (!server_domain_len) {
  10237. return 0;
  10238. }
  10239. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10240. if (mg_strncasecmp(uri,
  10241. abs_uri_protocols[i].proto,
  10242. abs_uri_protocols[i].proto_len) == 0) {
  10243. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10244. hostend = strchr(hostbegin, '/');
  10245. if (!hostend) {
  10246. return 0;
  10247. }
  10248. portbegin = strchr(hostbegin, ':');
  10249. if ((!portbegin) || (portbegin > hostend)) {
  10250. port = abs_uri_protocols[i].default_port;
  10251. request_domain_len = (size_t)(hostend - hostbegin);
  10252. } else {
  10253. port = strtoul(portbegin + 1, &portend, 10);
  10254. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10255. return 0;
  10256. }
  10257. request_domain_len = (size_t)(portbegin - hostbegin);
  10258. }
  10259. /* protocol found, port set */
  10260. break;
  10261. }
  10262. }
  10263. if (!port) {
  10264. /* port remains 0 if the protocol is not found */
  10265. return 0;
  10266. }
  10267. #if defined(USE_IPV6)
  10268. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10269. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10270. /* Request is directed to a different port */
  10271. return 0;
  10272. }
  10273. } else
  10274. #endif
  10275. {
  10276. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10277. /* Request is directed to a different port */
  10278. return 0;
  10279. }
  10280. }
  10281. if ((request_domain_len != server_domain_len)
  10282. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10283. /* Request is directed to another server */
  10284. return 0;
  10285. }
  10286. return hostend;
  10287. }
  10288. static int
  10289. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10290. {
  10291. const char *cl;
  10292. if (ebuf_len > 0) {
  10293. ebuf[0] = '\0';
  10294. }
  10295. *err = 0;
  10296. reset_per_request_attributes(conn);
  10297. if (!conn) {
  10298. mg_snprintf(conn,
  10299. NULL, /* No truncation check for ebuf */
  10300. ebuf,
  10301. ebuf_len,
  10302. "%s",
  10303. "Internal error");
  10304. *err = 500;
  10305. return 0;
  10306. }
  10307. /* Set the time the request was received. This value should be used for
  10308. * timeouts. */
  10309. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10310. conn->request_len =
  10311. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10312. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10313. */
  10314. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10315. mg_snprintf(conn,
  10316. NULL, /* No truncation check for ebuf */
  10317. ebuf,
  10318. ebuf_len,
  10319. "%s",
  10320. "Invalid request size");
  10321. *err = 500;
  10322. return 0;
  10323. }
  10324. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10325. mg_snprintf(conn,
  10326. NULL, /* No truncation check for ebuf */
  10327. ebuf,
  10328. ebuf_len,
  10329. "%s",
  10330. "Request Too Large");
  10331. *err = 413;
  10332. return 0;
  10333. } else if (conn->request_len <= 0) {
  10334. if (conn->data_len > 0) {
  10335. mg_snprintf(conn,
  10336. NULL, /* No truncation check for ebuf */
  10337. ebuf,
  10338. ebuf_len,
  10339. "%s",
  10340. "Client sent malformed request");
  10341. *err = 400;
  10342. } else {
  10343. /* Server did not send anything -> just close the connection */
  10344. conn->must_close = 1;
  10345. mg_snprintf(conn,
  10346. NULL, /* No truncation check for ebuf */
  10347. ebuf,
  10348. ebuf_len,
  10349. "%s",
  10350. "Client did not send a request");
  10351. *err = 0;
  10352. }
  10353. return 0;
  10354. } else if (parse_http_message(conn->buf,
  10355. conn->buf_size,
  10356. &conn->request_info) <= 0) {
  10357. mg_snprintf(conn,
  10358. NULL, /* No truncation check for ebuf */
  10359. ebuf,
  10360. ebuf_len,
  10361. "%s",
  10362. "Bad Request");
  10363. *err = 400;
  10364. return 0;
  10365. } else {
  10366. /* Message is a valid request or response */
  10367. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10368. /* Request/response has content length set */
  10369. char *endptr = NULL;
  10370. conn->content_len = strtoll(cl, &endptr, 10);
  10371. if (endptr == cl) {
  10372. mg_snprintf(conn,
  10373. NULL, /* No truncation check for ebuf */
  10374. ebuf,
  10375. ebuf_len,
  10376. "%s",
  10377. "Bad Request");
  10378. *err = 411;
  10379. return 0;
  10380. }
  10381. /* Publish the content length back to the request info. */
  10382. conn->request_info.content_length = conn->content_len;
  10383. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10384. != NULL
  10385. && !mg_strcasecmp(cl, "chunked")) {
  10386. conn->is_chunked = 1;
  10387. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10388. || !mg_strcasecmp(conn->request_info.request_method,
  10389. "PUT")) {
  10390. /* POST or PUT request without content length set */
  10391. conn->content_len = -1;
  10392. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10393. "HTTP/",
  10394. 5)) {
  10395. /* Response without content length set */
  10396. conn->content_len = -1;
  10397. } else {
  10398. /* Other request */
  10399. conn->content_len = 0;
  10400. }
  10401. }
  10402. return 1;
  10403. }
  10404. int
  10405. mg_get_response(struct mg_connection *conn,
  10406. char *ebuf,
  10407. size_t ebuf_len,
  10408. int timeout)
  10409. {
  10410. if (conn) {
  10411. /* Implementation of API function for HTTP clients */
  10412. int err, ret;
  10413. struct mg_context *octx = conn->ctx;
  10414. struct mg_context rctx = *(conn->ctx);
  10415. char txt[32]; /* will not overflow */
  10416. if (timeout >= 0) {
  10417. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10418. rctx.config[REQUEST_TIMEOUT] = txt;
  10419. set_sock_timeout(conn->client.sock, timeout);
  10420. } else {
  10421. rctx.config[REQUEST_TIMEOUT] = NULL;
  10422. }
  10423. conn->ctx = &rctx;
  10424. ret = getreq(conn, ebuf, ebuf_len, &err);
  10425. conn->ctx = octx;
  10426. /* TODO: 1) uri is deprecated;
  10427. * 2) here, ri.uri is the http response code */
  10428. conn->request_info.uri = conn->request_info.request_uri;
  10429. /* TODO (mid): Define proper return values - maybe return length?
  10430. * For the first test use <0 for error and >0 for OK */
  10431. return (ret == 0) ? -1 : +1;
  10432. }
  10433. return -1;
  10434. }
  10435. struct mg_connection *
  10436. mg_download(const char *host,
  10437. int port,
  10438. int use_ssl,
  10439. char *ebuf,
  10440. size_t ebuf_len,
  10441. const char *fmt,
  10442. ...)
  10443. {
  10444. struct mg_connection *conn;
  10445. va_list ap;
  10446. int i;
  10447. int reqerr;
  10448. va_start(ap, fmt);
  10449. ebuf[0] = '\0';
  10450. /* open a connection */
  10451. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10452. if (conn != NULL) {
  10453. i = mg_vprintf(conn, fmt, ap);
  10454. if (i <= 0) {
  10455. mg_snprintf(conn,
  10456. NULL, /* No truncation check for ebuf */
  10457. ebuf,
  10458. ebuf_len,
  10459. "%s",
  10460. "Error sending request");
  10461. } else {
  10462. getreq(conn, ebuf, ebuf_len, &reqerr);
  10463. /* TODO: 1) uri is deprecated;
  10464. * 2) here, ri.uri is the http response code */
  10465. conn->request_info.uri = conn->request_info.request_uri;
  10466. }
  10467. }
  10468. /* if an error occured, close the connection */
  10469. if (ebuf[0] != '\0' && conn != NULL) {
  10470. mg_close_connection(conn);
  10471. conn = NULL;
  10472. }
  10473. va_end(ap);
  10474. return conn;
  10475. }
  10476. struct websocket_client_thread_data {
  10477. struct mg_connection *conn;
  10478. mg_websocket_data_handler data_handler;
  10479. mg_websocket_close_handler close_handler;
  10480. void *callback_data;
  10481. };
  10482. #if defined(USE_WEBSOCKET)
  10483. #ifdef _WIN32
  10484. static unsigned __stdcall websocket_client_thread(void *data)
  10485. #else
  10486. static void *
  10487. websocket_client_thread(void *data)
  10488. #endif
  10489. {
  10490. struct websocket_client_thread_data *cdata =
  10491. (struct websocket_client_thread_data *)data;
  10492. mg_set_thread_name("ws-client");
  10493. if (cdata->conn->ctx) {
  10494. if (cdata->conn->ctx->callbacks.init_thread) {
  10495. /* 3 indicates a websocket client thread */
  10496. /* TODO: check if conn->ctx can be set */
  10497. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10498. }
  10499. }
  10500. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10501. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10502. if (cdata->close_handler != NULL) {
  10503. cdata->close_handler(cdata->conn, cdata->callback_data);
  10504. }
  10505. mg_free((void *)cdata);
  10506. #ifdef _WIN32
  10507. return 0;
  10508. #else
  10509. return NULL;
  10510. #endif
  10511. }
  10512. #endif
  10513. struct mg_connection *
  10514. mg_connect_websocket_client(const char *host,
  10515. int port,
  10516. int use_ssl,
  10517. char *error_buffer,
  10518. size_t error_buffer_size,
  10519. const char *path,
  10520. const char *origin,
  10521. mg_websocket_data_handler data_func,
  10522. mg_websocket_close_handler close_func,
  10523. void *user_data)
  10524. {
  10525. struct mg_connection *conn = NULL;
  10526. #if defined(USE_WEBSOCKET)
  10527. struct mg_context *newctx = NULL;
  10528. struct websocket_client_thread_data *thread_data;
  10529. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10530. static const char *handshake_req;
  10531. if (origin != NULL) {
  10532. handshake_req = "GET %s HTTP/1.1\r\n"
  10533. "Host: %s\r\n"
  10534. "Upgrade: websocket\r\n"
  10535. "Connection: Upgrade\r\n"
  10536. "Sec-WebSocket-Key: %s\r\n"
  10537. "Sec-WebSocket-Version: 13\r\n"
  10538. "Origin: %s\r\n"
  10539. "\r\n";
  10540. } else {
  10541. handshake_req = "GET %s HTTP/1.1\r\n"
  10542. "Host: %s\r\n"
  10543. "Upgrade: websocket\r\n"
  10544. "Connection: Upgrade\r\n"
  10545. "Sec-WebSocket-Key: %s\r\n"
  10546. "Sec-WebSocket-Version: 13\r\n"
  10547. "\r\n";
  10548. }
  10549. /* Establish the client connection and request upgrade */
  10550. conn = mg_download(host,
  10551. port,
  10552. use_ssl,
  10553. error_buffer,
  10554. error_buffer_size,
  10555. handshake_req,
  10556. path,
  10557. host,
  10558. magic,
  10559. origin);
  10560. /* Connection object will be null if something goes wrong */
  10561. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10562. if (!*error_buffer) {
  10563. /* if there is a connection, but it did not return 101,
  10564. * error_buffer is not yet set */
  10565. mg_snprintf(conn,
  10566. NULL, /* No truncation check for ebuf */
  10567. error_buffer,
  10568. error_buffer_size,
  10569. "Unexpected server reply");
  10570. }
  10571. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10572. if (conn != NULL) {
  10573. mg_free(conn);
  10574. conn = NULL;
  10575. }
  10576. return conn;
  10577. }
  10578. /* For client connections, mg_context is fake. Since we need to set a
  10579. * callback function, we need to create a copy and modify it. */
  10580. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10581. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10582. newctx->user_data = user_data;
  10583. newctx->context_type = 2; /* client context type */
  10584. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10585. newctx->workerthreadids =
  10586. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10587. conn->ctx = newctx;
  10588. thread_data = (struct websocket_client_thread_data *)
  10589. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10590. thread_data->conn = conn;
  10591. thread_data->data_handler = data_func;
  10592. thread_data->close_handler = close_func;
  10593. thread_data->callback_data = NULL;
  10594. /* Start a thread to read the websocket client connection
  10595. * This thread will automatically stop when mg_disconnect is
  10596. * called on the client connection */
  10597. if (mg_start_thread_with_id(websocket_client_thread,
  10598. (void *)thread_data,
  10599. newctx->workerthreadids) != 0) {
  10600. mg_free((void *)thread_data);
  10601. mg_free((void *)newctx->workerthreadids);
  10602. mg_free((void *)newctx);
  10603. mg_free((void *)conn);
  10604. conn = NULL;
  10605. DEBUG_TRACE("%s",
  10606. "Websocket client connect thread could not be started\r\n");
  10607. }
  10608. #else
  10609. /* Appease "unused parameter" warnings */
  10610. (void)host;
  10611. (void)port;
  10612. (void)use_ssl;
  10613. (void)error_buffer;
  10614. (void)error_buffer_size;
  10615. (void)path;
  10616. (void)origin;
  10617. (void)user_data;
  10618. (void)data_func;
  10619. (void)close_func;
  10620. #endif
  10621. return conn;
  10622. }
  10623. static void
  10624. process_new_connection(struct mg_connection *conn)
  10625. {
  10626. if (conn && conn->ctx) {
  10627. struct mg_request_info *ri = &conn->request_info;
  10628. int keep_alive_enabled, keep_alive, discard_len;
  10629. char ebuf[100];
  10630. const char *hostend;
  10631. int reqerr, uri_type;
  10632. keep_alive_enabled =
  10633. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10634. /* Important: on new connection, reset the receiving buffer. Credit
  10635. * goes to crule42. */
  10636. conn->data_len = 0;
  10637. do {
  10638. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10639. /* The request sent by the client could not be understood by
  10640. * the server, or it was incomplete or a timeout. Send an
  10641. * error message and close the connection. */
  10642. if (reqerr > 0) {
  10643. /*assert(ebuf[0] != '\0');*/
  10644. send_http_error(conn, reqerr, "%s", ebuf);
  10645. }
  10646. } else if (strcmp(ri->http_version, "1.0")
  10647. && strcmp(ri->http_version, "1.1")) {
  10648. mg_snprintf(conn,
  10649. NULL, /* No truncation check for ebuf */
  10650. ebuf,
  10651. sizeof(ebuf),
  10652. "Bad HTTP version: [%s]",
  10653. ri->http_version);
  10654. send_http_error(conn, 505, "%s", ebuf);
  10655. }
  10656. if (ebuf[0] == '\0') {
  10657. uri_type = get_uri_type(conn->request_info.request_uri);
  10658. switch (uri_type) {
  10659. case 1:
  10660. /* Asterisk */
  10661. conn->request_info.local_uri = NULL;
  10662. break;
  10663. case 2:
  10664. /* relative uri */
  10665. conn->request_info.local_uri =
  10666. conn->request_info.request_uri;
  10667. break;
  10668. case 3:
  10669. case 4:
  10670. /* absolute uri (with/without port) */
  10671. hostend = get_rel_url_at_current_server(
  10672. conn->request_info.request_uri, conn);
  10673. if (hostend) {
  10674. conn->request_info.local_uri = hostend;
  10675. } else {
  10676. conn->request_info.local_uri = NULL;
  10677. }
  10678. break;
  10679. default:
  10680. mg_snprintf(conn,
  10681. NULL, /* No truncation check for ebuf */
  10682. ebuf,
  10683. sizeof(ebuf),
  10684. "Invalid URI: [%s]",
  10685. ri->request_uri);
  10686. send_http_error(conn, 400, "%s", ebuf);
  10687. break;
  10688. }
  10689. /* TODO: cleanup uri, local_uri and request_uri */
  10690. conn->request_info.uri = conn->request_info.local_uri;
  10691. }
  10692. if (ebuf[0] == '\0') {
  10693. if (conn->request_info.local_uri) {
  10694. /* handle request to local server */
  10695. handle_request(conn);
  10696. if (conn->ctx->callbacks.end_request != NULL) {
  10697. conn->ctx->callbacks.end_request(conn,
  10698. conn->status_code);
  10699. }
  10700. log_access(conn);
  10701. } else {
  10702. /* TODO: handle non-local request (PROXY) */
  10703. conn->must_close = 1;
  10704. }
  10705. } else {
  10706. conn->must_close = 1;
  10707. }
  10708. if (ri->remote_user != NULL) {
  10709. mg_free((void *)ri->remote_user);
  10710. /* Important! When having connections with and without auth
  10711. * would cause double free and then crash */
  10712. ri->remote_user = NULL;
  10713. }
  10714. /* NOTE(lsm): order is important here. should_keep_alive() call
  10715. * is
  10716. * using parsed request, which will be invalid after memmove's
  10717. * below.
  10718. * Therefore, memorize should_keep_alive() result now for later
  10719. * use
  10720. * in loop exit condition. */
  10721. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10722. && conn->content_len >= 0 && should_keep_alive(conn);
  10723. /* Discard all buffered data for this request */
  10724. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10725. && conn->request_len + conn->content_len
  10726. < (int64_t)conn->data_len
  10727. ? (int)(conn->request_len + conn->content_len)
  10728. : conn->data_len;
  10729. /*assert(discard_len >= 0);*/
  10730. if (discard_len < 0)
  10731. break;
  10732. conn->data_len -= discard_len;
  10733. if (conn->data_len > 0) {
  10734. memmove(conn->buf,
  10735. conn->buf + discard_len,
  10736. (size_t)conn->data_len);
  10737. }
  10738. /* assert(conn->data_len >= 0); */
  10739. /* assert(conn->data_len <= conn->buf_size); */
  10740. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10741. break;
  10742. }
  10743. } while (keep_alive);
  10744. }
  10745. }
  10746. /* Worker threads take accepted socket from the queue */
  10747. static int
  10748. consume_socket(struct mg_context *ctx, struct socket *sp)
  10749. {
  10750. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10751. if (!ctx) {
  10752. return 0;
  10753. }
  10754. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10755. DEBUG_TRACE("%s", "going idle");
  10756. /* If the queue is empty, wait. We're idle at this point. */
  10757. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10758. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10759. }
  10760. /* If we're stopping, sq_head may be equal to sq_tail. */
  10761. if (ctx->sq_head > ctx->sq_tail) {
  10762. /* Copy socket from the queue and increment tail */
  10763. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10764. ctx->sq_tail++;
  10765. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10766. /* Wrap pointers if needed */
  10767. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10768. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10769. ctx->sq_head -= QUEUE_SIZE(ctx);
  10770. }
  10771. }
  10772. (void)pthread_cond_signal(&ctx->sq_empty);
  10773. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10774. return !ctx->stop_flag;
  10775. #undef QUEUE_SIZE
  10776. }
  10777. static void *
  10778. worker_thread_run(void *thread_func_param)
  10779. {
  10780. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10781. struct mg_connection *conn;
  10782. struct mg_workerTLS tls;
  10783. #if defined(MG_LEGACY_INTERFACE)
  10784. uint32_t addr;
  10785. #endif
  10786. mg_set_thread_name("worker");
  10787. tls.is_master = 0;
  10788. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10789. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10790. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10791. #endif
  10792. if (ctx->callbacks.init_thread) {
  10793. /* call init_thread for a worker thread (type 1) */
  10794. ctx->callbacks.init_thread(ctx, 1);
  10795. }
  10796. conn =
  10797. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10798. if (conn == NULL) {
  10799. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10800. } else {
  10801. pthread_setspecific(sTlsKey, &tls);
  10802. conn->buf_size = MAX_REQUEST_SIZE;
  10803. conn->buf = (char *)(conn + 1);
  10804. conn->ctx = ctx;
  10805. conn->request_info.user_data = ctx->user_data;
  10806. /* Allocate a mutex for this connection to allow communication both
  10807. * within the request handler and from elsewhere in the application
  10808. */
  10809. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10810. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10811. * signal sq_empty condvar to wake up the master waiting in
  10812. * produce_socket() */
  10813. while (consume_socket(ctx, &conn->client)) {
  10814. conn->conn_birth_time = time(NULL);
  10815. /* Fill in IP, port info early so even if SSL setup below fails,
  10816. * error handler would have the corresponding info.
  10817. * Thanks to Johannes Winkelmann for the patch.
  10818. */
  10819. #if defined(USE_IPV6)
  10820. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10821. conn->request_info.remote_port =
  10822. ntohs(conn->client.rsa.sin6.sin6_port);
  10823. } else
  10824. #endif
  10825. {
  10826. conn->request_info.remote_port =
  10827. ntohs(conn->client.rsa.sin.sin_port);
  10828. }
  10829. sockaddr_to_string(conn->request_info.remote_addr,
  10830. sizeof(conn->request_info.remote_addr),
  10831. &conn->client.rsa);
  10832. #if defined(MG_LEGACY_INTERFACE)
  10833. /* This legacy interface only works for the IPv4 case */
  10834. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10835. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10836. #endif
  10837. conn->request_info.is_ssl = conn->client.is_ssl;
  10838. if (!conn->client.is_ssl
  10839. #ifndef NO_SSL
  10840. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10841. #endif
  10842. ) {
  10843. process_new_connection(conn);
  10844. }
  10845. close_connection(conn);
  10846. }
  10847. }
  10848. /* Signal master that we're done with connection and exiting */
  10849. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10850. ctx->running_worker_threads--;
  10851. (void)pthread_cond_signal(&ctx->thread_cond);
  10852. /* assert(ctx->running_worker_threads >= 0); */
  10853. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10854. pthread_setspecific(sTlsKey, NULL);
  10855. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10856. CloseHandle(tls.pthread_cond_helper_mutex);
  10857. #endif
  10858. pthread_mutex_destroy(&conn->mutex);
  10859. mg_free(conn);
  10860. DEBUG_TRACE("%s", "exiting");
  10861. return NULL;
  10862. }
  10863. /* Threads have different return types on Windows and Unix. */
  10864. #ifdef _WIN32
  10865. static unsigned __stdcall worker_thread(void *thread_func_param)
  10866. {
  10867. worker_thread_run(thread_func_param);
  10868. return 0;
  10869. }
  10870. #else
  10871. static void *
  10872. worker_thread(void *thread_func_param)
  10873. {
  10874. worker_thread_run(thread_func_param);
  10875. return NULL;
  10876. }
  10877. #endif /* _WIN32 */
  10878. /* Master thread adds accepted socket to a queue */
  10879. static void
  10880. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10881. {
  10882. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10883. if (!ctx) {
  10884. return;
  10885. }
  10886. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10887. /* If the queue is full, wait */
  10888. while (ctx->stop_flag == 0
  10889. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10890. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10891. }
  10892. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10893. /* Copy socket to the queue and increment head */
  10894. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10895. ctx->sq_head++;
  10896. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10897. }
  10898. (void)pthread_cond_signal(&ctx->sq_full);
  10899. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10900. #undef QUEUE_SIZE
  10901. }
  10902. static void
  10903. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10904. {
  10905. struct socket so;
  10906. char src_addr[IP_ADDR_STR_LEN];
  10907. socklen_t len = sizeof(so.rsa);
  10908. int on = 1;
  10909. int timeout;
  10910. if (!listener) {
  10911. return;
  10912. }
  10913. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10914. == INVALID_SOCKET) {
  10915. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10916. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10917. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10918. closesocket(so.sock);
  10919. so.sock = INVALID_SOCKET;
  10920. } else {
  10921. /* Put so socket structure into the queue */
  10922. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10923. set_close_on_exec(so.sock, fc(ctx));
  10924. so.is_ssl = listener->is_ssl;
  10925. so.ssl_redir = listener->ssl_redir;
  10926. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10927. mg_cry(fc(ctx),
  10928. "%s: getsockname() failed: %s",
  10929. __func__,
  10930. strerror(ERRNO));
  10931. }
  10932. /* Set TCP keep-alive. This is needed because if HTTP-level
  10933. * keep-alive
  10934. * is enabled, and client resets the connection, server won't get
  10935. * TCP FIN or RST and will keep the connection open forever. With
  10936. * TCP keep-alive, next keep-alive handshake will figure out that
  10937. * the client is down and will close the server end.
  10938. * Thanks to Igor Klopov who suggested the patch. */
  10939. if (setsockopt(so.sock,
  10940. SOL_SOCKET,
  10941. SO_KEEPALIVE,
  10942. (SOCK_OPT_TYPE)&on,
  10943. sizeof(on)) != 0) {
  10944. mg_cry(fc(ctx),
  10945. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10946. __func__,
  10947. strerror(ERRNO));
  10948. }
  10949. /* Disable TCP Nagle's algorithm. Normally TCP packets are
  10950. * coalesced
  10951. * to effectively fill up the underlying IP packet payload and
  10952. * reduce
  10953. * the overhead of sending lots of small buffers. However this hurts
  10954. * the server's throughput (ie. operations per second) when HTTP 1.1
  10955. * persistent connections are used and the responses are relatively
  10956. * small (eg. less than 1400 bytes).
  10957. */
  10958. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10959. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10960. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10961. mg_cry(fc(ctx),
  10962. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10963. __func__,
  10964. strerror(ERRNO));
  10965. }
  10966. }
  10967. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10968. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10969. } else {
  10970. timeout = -1;
  10971. }
  10972. /* Set socket timeout to the given value, but not more than a
  10973. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10974. * so the server can exit after that time if requested. */
  10975. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10976. set_sock_timeout(so.sock, timeout);
  10977. } else {
  10978. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10979. }
  10980. produce_socket(ctx, &so);
  10981. }
  10982. }
  10983. static void
  10984. master_thread_run(void *thread_func_param)
  10985. {
  10986. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10987. struct mg_workerTLS tls;
  10988. struct pollfd *pfd;
  10989. unsigned int i;
  10990. unsigned int workerthreadcount;
  10991. if (!ctx) {
  10992. return;
  10993. }
  10994. mg_set_thread_name("master");
  10995. /* Increase priority of the master thread */
  10996. #if defined(_WIN32)
  10997. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10998. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10999. int min_prio = sched_get_priority_min(SCHED_RR);
  11000. int max_prio = sched_get_priority_max(SCHED_RR);
  11001. if ((min_prio >= 0) && (max_prio >= 0)
  11002. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11003. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11004. struct sched_param sched_param = {0};
  11005. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11006. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11007. }
  11008. #endif
  11009. /* Initialize thread local storage */
  11010. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11011. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11012. #endif
  11013. tls.is_master = 1;
  11014. pthread_setspecific(sTlsKey, &tls);
  11015. if (ctx->callbacks.init_thread) {
  11016. /* Callback for the master thread (type 0) */
  11017. ctx->callbacks.init_thread(ctx, 0);
  11018. }
  11019. /* Server starts *now* */
  11020. ctx->start_time = time(NULL);
  11021. /* Allocate memory for the listening sockets, and start the server */
  11022. pfd =
  11023. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  11024. while (pfd != NULL && ctx->stop_flag == 0) {
  11025. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11026. pfd[i].fd = ctx->listening_sockets[i].sock;
  11027. pfd[i].events = POLLIN;
  11028. }
  11029. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11030. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11031. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11032. * successful poll, and POLLIN is defined as
  11033. * (POLLRDNORM | POLLRDBAND)
  11034. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11035. * pfd[i].revents == POLLIN. */
  11036. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11037. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11038. }
  11039. }
  11040. }
  11041. }
  11042. mg_free(pfd);
  11043. DEBUG_TRACE("%s", "stopping workers");
  11044. /* Stop signal received: somebody called mg_stop. Quit. */
  11045. close_all_listening_sockets(ctx);
  11046. /* Wakeup workers that are waiting for connections to handle. */
  11047. pthread_cond_broadcast(&ctx->sq_full);
  11048. /* Wait until all threads finish */
  11049. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11050. while (ctx->running_worker_threads > 0) {
  11051. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  11052. }
  11053. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11054. /* Join all worker threads to avoid leaking threads. */
  11055. workerthreadcount = ctx->cfg_worker_threads;
  11056. for (i = 0; i < workerthreadcount; i++) {
  11057. if (ctx->workerthreadids[i] != 0) {
  11058. mg_join_thread(ctx->workerthreadids[i]);
  11059. }
  11060. }
  11061. #if !defined(NO_SSL)
  11062. if (ctx->ssl_ctx != NULL) {
  11063. uninitialize_ssl(ctx);
  11064. }
  11065. #endif
  11066. DEBUG_TRACE("%s", "exiting");
  11067. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11068. CloseHandle(tls.pthread_cond_helper_mutex);
  11069. #endif
  11070. pthread_setspecific(sTlsKey, NULL);
  11071. /* Signal mg_stop() that we're done.
  11072. * WARNING: This must be the very last thing this
  11073. * thread does, as ctx becomes invalid after this line. */
  11074. ctx->stop_flag = 2;
  11075. }
  11076. /* Threads have different return types on Windows and Unix. */
  11077. #ifdef _WIN32
  11078. static unsigned __stdcall master_thread(void *thread_func_param)
  11079. {
  11080. master_thread_run(thread_func_param);
  11081. return 0;
  11082. }
  11083. #else
  11084. static void *
  11085. master_thread(void *thread_func_param)
  11086. {
  11087. master_thread_run(thread_func_param);
  11088. return NULL;
  11089. }
  11090. #endif /* _WIN32 */
  11091. static void
  11092. free_context(struct mg_context *ctx)
  11093. {
  11094. int i;
  11095. struct mg_handler_info *tmp_rh;
  11096. if (ctx == NULL) {
  11097. return;
  11098. }
  11099. if (ctx->callbacks.exit_context) {
  11100. ctx->callbacks.exit_context(ctx);
  11101. }
  11102. /* All threads exited, no sync is needed. Destroy thread mutex and
  11103. * condvars
  11104. */
  11105. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11106. (void)pthread_cond_destroy(&ctx->thread_cond);
  11107. (void)pthread_cond_destroy(&ctx->sq_empty);
  11108. (void)pthread_cond_destroy(&ctx->sq_full);
  11109. /* Destroy other context global data structures mutex */
  11110. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11111. #if defined(USE_TIMERS)
  11112. timers_exit(ctx);
  11113. #endif
  11114. /* Deallocate config parameters */
  11115. for (i = 0; i < NUM_OPTIONS; i++) {
  11116. if (ctx->config[i] != NULL) {
  11117. #if defined(_MSC_VER)
  11118. #pragma warning(suppress : 6001)
  11119. #endif
  11120. mg_free(ctx->config[i]);
  11121. }
  11122. }
  11123. /* Deallocate request handlers */
  11124. while (ctx->handlers) {
  11125. tmp_rh = ctx->handlers;
  11126. ctx->handlers = tmp_rh->next;
  11127. mg_free(tmp_rh->uri);
  11128. mg_free(tmp_rh);
  11129. }
  11130. #ifndef NO_SSL
  11131. /* Deallocate SSL context */
  11132. if (ctx->ssl_ctx != NULL) {
  11133. SSL_CTX_free(ctx->ssl_ctx);
  11134. }
  11135. #endif /* !NO_SSL */
  11136. /* Deallocate worker thread ID array */
  11137. if (ctx->workerthreadids != NULL) {
  11138. mg_free(ctx->workerthreadids);
  11139. }
  11140. /* Deallocate the tls variable */
  11141. if (mg_atomic_dec(&sTlsInit) == 0) {
  11142. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11143. DeleteCriticalSection(&global_log_file_lock);
  11144. #endif /* _WIN32 && !__SYMBIAN32__ */
  11145. #if !defined(_WIN32)
  11146. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11147. #endif
  11148. pthread_key_delete(sTlsKey);
  11149. }
  11150. /* deallocate system name string */
  11151. mg_free(ctx->systemName);
  11152. /* Deallocate context itself */
  11153. mg_free(ctx);
  11154. }
  11155. void
  11156. mg_stop(struct mg_context *ctx)
  11157. {
  11158. pthread_t mt;
  11159. if (!ctx) {
  11160. return;
  11161. }
  11162. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11163. * two threads is not allowed. */
  11164. mt = ctx->masterthreadid;
  11165. if (mt == 0) {
  11166. return;
  11167. }
  11168. ctx->masterthreadid = 0;
  11169. ctx->stop_flag = 1;
  11170. /* Wait until mg_fini() stops */
  11171. while (ctx->stop_flag != 2) {
  11172. (void)mg_sleep(10);
  11173. }
  11174. mg_join_thread(mt);
  11175. free_context(ctx);
  11176. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11177. (void)WSACleanup();
  11178. #endif /* _WIN32 && !__SYMBIAN32__ */
  11179. }
  11180. static void
  11181. get_system_name(char **sysName)
  11182. {
  11183. #if defined(_WIN32)
  11184. #if !defined(__SYMBIAN32__)
  11185. char name[128];
  11186. DWORD dwVersion = 0;
  11187. DWORD dwMajorVersion = 0;
  11188. DWORD dwMinorVersion = 0;
  11189. DWORD dwBuild = 0;
  11190. #ifdef _MSC_VER
  11191. #pragma warning(push)
  11192. // GetVersion was declared deprecated
  11193. #pragma warning(disable : 4996)
  11194. #endif
  11195. dwVersion = GetVersion();
  11196. #ifdef _MSC_VER
  11197. #pragma warning(pop)
  11198. #endif
  11199. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11200. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11201. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11202. (void)dwBuild;
  11203. sprintf(name,
  11204. "Windows %u.%u",
  11205. (unsigned)dwMajorVersion,
  11206. (unsigned)dwMinorVersion);
  11207. *sysName = mg_strdup(name);
  11208. #else
  11209. *sysName = mg_strdup("Symbian");
  11210. #endif
  11211. #else
  11212. struct utsname name;
  11213. memset(&name, 0, sizeof(name));
  11214. uname(&name);
  11215. *sysName = mg_strdup(name.sysname);
  11216. #endif
  11217. }
  11218. struct mg_context *
  11219. mg_start(const struct mg_callbacks *callbacks,
  11220. void *user_data,
  11221. const char **options)
  11222. {
  11223. struct mg_context *ctx;
  11224. const char *name, *value, *default_value;
  11225. int idx, ok, workerthreadcount;
  11226. unsigned int i;
  11227. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11228. struct mg_workerTLS tls;
  11229. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11230. WSADATA data;
  11231. WSAStartup(MAKEWORD(2, 2), &data);
  11232. #endif /* _WIN32 && !__SYMBIAN32__ */
  11233. /* Allocate context and initialize reasonable general case defaults. */
  11234. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11235. return NULL;
  11236. }
  11237. /* Random number generator will initialize at the first call */
  11238. ctx->auth_nonce_mask =
  11239. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11240. if (mg_atomic_inc(&sTlsInit) == 1) {
  11241. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11242. InitializeCriticalSection(&global_log_file_lock);
  11243. #endif /* _WIN32 && !__SYMBIAN32__ */
  11244. #if !defined(_WIN32)
  11245. pthread_mutexattr_init(&pthread_mutex_attr);
  11246. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11247. #endif
  11248. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11249. /* Fatal error - abort start. However, this situation should
  11250. * never
  11251. * occur in practice. */
  11252. mg_atomic_dec(&sTlsInit);
  11253. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11254. mg_free(ctx);
  11255. return NULL;
  11256. }
  11257. } else {
  11258. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11259. * initialized. */
  11260. mg_sleep(1);
  11261. }
  11262. tls.is_master = -1;
  11263. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11264. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11265. tls.pthread_cond_helper_mutex = NULL;
  11266. #endif
  11267. pthread_setspecific(sTlsKey, &tls);
  11268. #if defined(USE_LUA)
  11269. lua_init_optional_libraries();
  11270. #endif
  11271. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11272. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  11273. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11274. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11275. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11276. if (!ok) {
  11277. /* Fatal error - abort start. However, this situation should never
  11278. * occur in practice. */
  11279. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11280. mg_free(ctx);
  11281. pthread_setspecific(sTlsKey, NULL);
  11282. return NULL;
  11283. }
  11284. if (callbacks) {
  11285. ctx->callbacks = *callbacks;
  11286. exit_callback = callbacks->exit_context;
  11287. ctx->callbacks.exit_context = 0;
  11288. }
  11289. ctx->user_data = user_data;
  11290. ctx->handlers = NULL;
  11291. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11292. ctx->shared_lua_websockets = 0;
  11293. #endif
  11294. while (options && (name = *options++) != NULL) {
  11295. if ((idx = get_option_index(name)) == -1) {
  11296. mg_cry(fc(ctx), "Invalid option: %s", name);
  11297. free_context(ctx);
  11298. pthread_setspecific(sTlsKey, NULL);
  11299. return NULL;
  11300. } else if ((value = *options++) == NULL) {
  11301. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11302. free_context(ctx);
  11303. pthread_setspecific(sTlsKey, NULL);
  11304. return NULL;
  11305. }
  11306. if (ctx->config[idx] != NULL) {
  11307. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11308. mg_free(ctx->config[idx]);
  11309. }
  11310. ctx->config[idx] = mg_strdup(value);
  11311. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11312. }
  11313. /* Set default value if needed */
  11314. for (i = 0; config_options[i].name != NULL; i++) {
  11315. default_value = config_options[i].default_value;
  11316. if (ctx->config[i] == NULL && default_value != NULL) {
  11317. ctx->config[i] = mg_strdup(default_value);
  11318. }
  11319. }
  11320. #if defined(NO_FILES)
  11321. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11322. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11323. free_context(ctx);
  11324. pthread_setspecific(sTlsKey, NULL);
  11325. return NULL;
  11326. }
  11327. #endif
  11328. get_system_name(&ctx->systemName);
  11329. /* NOTE(lsm): order is important here. SSL certificates must
  11330. * be initialized before listening ports. UID must be set last. */
  11331. if (!set_gpass_option(ctx) ||
  11332. #if !defined(NO_SSL)
  11333. !set_ssl_option(ctx) ||
  11334. #endif
  11335. !set_ports_option(ctx) ||
  11336. #if !defined(_WIN32)
  11337. !set_uid_option(ctx) ||
  11338. #endif
  11339. !set_acl_option(ctx)) {
  11340. free_context(ctx);
  11341. pthread_setspecific(sTlsKey, NULL);
  11342. return NULL;
  11343. }
  11344. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11345. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11346. * won't kill the whole process. */
  11347. (void)signal(SIGPIPE, SIG_IGN);
  11348. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11349. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11350. if (workerthreadcount > MAX_WORKER_THREADS) {
  11351. mg_cry(fc(ctx), "Too many worker threads");
  11352. free_context(ctx);
  11353. pthread_setspecific(sTlsKey, NULL);
  11354. return NULL;
  11355. }
  11356. if (workerthreadcount > 0) {
  11357. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11358. ctx->workerthreadids =
  11359. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11360. if (ctx->workerthreadids == NULL) {
  11361. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11362. free_context(ctx);
  11363. pthread_setspecific(sTlsKey, NULL);
  11364. return NULL;
  11365. }
  11366. }
  11367. #if defined(USE_TIMERS)
  11368. if (timers_init(ctx) != 0) {
  11369. mg_cry(fc(ctx), "Error creating timers");
  11370. free_context(ctx);
  11371. pthread_setspecific(sTlsKey, NULL);
  11372. return NULL;
  11373. }
  11374. #endif
  11375. /* Context has been created - init user libraries */
  11376. if (ctx->callbacks.init_context) {
  11377. ctx->callbacks.init_context(ctx);
  11378. }
  11379. ctx->callbacks.exit_context = exit_callback;
  11380. ctx->context_type = 1; /* server context */
  11381. /* Start master (listening) thread */
  11382. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11383. /* Start worker threads */
  11384. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11385. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11386. ctx->running_worker_threads++;
  11387. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11388. if (mg_start_thread_with_id(worker_thread,
  11389. ctx,
  11390. &ctx->workerthreadids[i]) != 0) {
  11391. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11392. ctx->running_worker_threads--;
  11393. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11394. if (i > 0) {
  11395. mg_cry(fc(ctx),
  11396. "Cannot start worker thread %i: error %ld",
  11397. i + 1,
  11398. (long)ERRNO);
  11399. } else {
  11400. mg_cry(fc(ctx),
  11401. "Cannot create threads: error %ld",
  11402. (long)ERRNO);
  11403. free_context(ctx);
  11404. pthread_setspecific(sTlsKey, NULL);
  11405. return NULL;
  11406. }
  11407. break;
  11408. }
  11409. }
  11410. pthread_setspecific(sTlsKey, NULL);
  11411. return ctx;
  11412. }
  11413. /* Feature check API function */
  11414. unsigned
  11415. mg_check_feature(unsigned feature)
  11416. {
  11417. static const unsigned feature_set = 0
  11418. /* Set bits for available features according to API documentation.
  11419. * This bit mask is created at compile time, according to the active
  11420. * preprocessor defines. It is a single const value at runtime. */
  11421. #if !defined(NO_FILES)
  11422. | 0x0001u
  11423. #endif
  11424. #if !defined(NO_SSL)
  11425. | 0x0002u
  11426. #endif
  11427. #if !defined(NO_CGI)
  11428. | 0x0004u
  11429. #endif
  11430. #if defined(USE_IPV6)
  11431. | 0x0008u
  11432. #endif
  11433. #if defined(USE_WEBSOCKET)
  11434. | 0x0010u
  11435. #endif
  11436. #if defined(USE_LUA)
  11437. | 0x0020u
  11438. #endif
  11439. #if defined(USE_DUKTAPE)
  11440. | 0x0040u
  11441. #endif
  11442. #if !defined(NO_CACHING)
  11443. | 0x0080u
  11444. #endif
  11445. /* Set some extra bits not defined in the API documentation.
  11446. * These bits may change without further notice. */
  11447. #if defined(MG_LEGACY_INTERFACE)
  11448. | 0x8000u
  11449. #endif
  11450. #if defined(MEMORY_DEBUGGING)
  11451. | 0x0100u
  11452. #endif
  11453. #if defined(USE_TIMERS)
  11454. | 0x0200u
  11455. #endif
  11456. #if !defined(NO_NONCE_CHECK)
  11457. | 0x0400u
  11458. #endif
  11459. #if !defined(NO_POPEN)
  11460. | 0x0800u
  11461. #endif
  11462. ;
  11463. return (feature & feature_set);
  11464. }