civetweb.c 348 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474
  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. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  284. } pthread_cond_t;
  285. #ifndef __clockid_t_defined
  286. typedef DWORD clockid_t;
  287. #endif
  288. #ifndef CLOCK_MONOTONIC
  289. #define CLOCK_MONOTONIC (1)
  290. #endif
  291. #ifndef CLOCK_REALTIME
  292. #define CLOCK_REALTIME (2)
  293. #endif
  294. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  295. #define _TIMESPEC_DEFINED
  296. #endif
  297. #ifndef _TIMESPEC_DEFINED
  298. struct timespec {
  299. time_t tv_sec; /* seconds */
  300. long tv_nsec; /* nanoseconds */
  301. };
  302. #endif
  303. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  304. static int pthread_mutex_lock(pthread_mutex_t *);
  305. static int pthread_mutex_unlock(pthread_mutex_t *);
  306. static void path_to_unicode(const struct mg_connection *conn,
  307. const char *path,
  308. wchar_t *wbuf,
  309. size_t wbuf_len);
  310. struct file;
  311. static const char *
  312. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  313. #if defined(HAVE_STDINT)
  314. #include <stdint.h>
  315. #else
  316. typedef unsigned char uint8_t;
  317. typedef unsigned short uint16_t;
  318. typedef unsigned int uint32_t;
  319. typedef unsigned __int64 uint64_t;
  320. typedef __int64 int64_t;
  321. #ifndef INT64_MAX
  322. #define INT64_MAX (9223372036854775807)
  323. #endif
  324. #endif /* HAVE_STDINT */
  325. /* POSIX dirent interface */
  326. struct dirent {
  327. char d_name[PATH_MAX];
  328. };
  329. typedef struct DIR {
  330. HANDLE handle;
  331. WIN32_FIND_DATAW info;
  332. struct dirent result;
  333. } DIR;
  334. #if defined(_WIN32) && !defined(POLLIN)
  335. #ifndef HAVE_POLL
  336. struct pollfd {
  337. SOCKET fd;
  338. short events;
  339. short revents;
  340. };
  341. #define POLLIN (0x0300)
  342. #endif
  343. #endif
  344. /* Mark required libraries */
  345. #if defined(_MSC_VER)
  346. #pragma comment(lib, "Ws2_32.lib")
  347. #endif
  348. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  349. WINDOWS / UNIX include block */
  350. #include <sys/wait.h>
  351. #include <sys/socket.h>
  352. #include <sys/poll.h>
  353. #include <netinet/in.h>
  354. #include <arpa/inet.h>
  355. #include <sys/time.h>
  356. #include <sys/utsname.h>
  357. #include <stdint.h>
  358. #include <inttypes.h>
  359. #include <netdb.h>
  360. #include <netinet/tcp.h>
  361. typedef const void *SOCK_OPT_TYPE;
  362. #if defined(ANDROID)
  363. typedef unsigned short int in_port_t;
  364. #endif
  365. #include <pwd.h>
  366. #include <unistd.h>
  367. #include <grp.h>
  368. #include <dirent.h>
  369. #define vsnprintf_impl vsnprintf
  370. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  371. #include <dlfcn.h>
  372. #endif
  373. #include <pthread.h>
  374. #if defined(__MACH__)
  375. #define SSL_LIB "libssl.dylib"
  376. #define CRYPTO_LIB "libcrypto.dylib"
  377. #else
  378. #if !defined(SSL_LIB)
  379. #define SSL_LIB "libssl.so"
  380. #endif
  381. #if !defined(CRYPTO_LIB)
  382. #define CRYPTO_LIB "libcrypto.so"
  383. #endif
  384. #endif
  385. #ifndef O_BINARY
  386. #define O_BINARY (0)
  387. #endif /* O_BINARY */
  388. #define closesocket(a) (close(a))
  389. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  390. #define mg_remove(conn, x) (remove(x))
  391. #define mg_sleep(x) (usleep((x)*1000))
  392. #define mg_opendir(conn, x) (opendir(x))
  393. #define mg_closedir(x) (closedir(x))
  394. #define mg_readdir(x) (readdir(x))
  395. #define ERRNO (errno)
  396. #define INVALID_SOCKET (-1)
  397. #define INT64_FMT PRId64
  398. #define UINT64_FMT PRIu64
  399. typedef int SOCKET;
  400. #define WINCDECL
  401. #if defined(__hpux)
  402. /* HPUX 11 does not have monotonic, fall back to realtime */
  403. #ifndef CLOCK_MONOTONIC
  404. #define CLOCK_MONOTONIC CLOCK_REALTIME
  405. #endif
  406. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  407. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  408. * the prototypes use int* rather than socklen_t* which matches the
  409. * actual library expectation. When called with the wrong size arg
  410. * accept() returns a zero client inet addr and check_acl() always
  411. * fails. Since socklen_t is widely used below, just force replace
  412. * their typedef with int. - DTL
  413. */
  414. #define socklen_t int
  415. #endif /* hpux */
  416. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  417. WINDOWS / UNIX include block */
  418. /* va_copy should always be a macro, C99 and C++11 - DTL */
  419. #ifndef va_copy
  420. #define va_copy(x, y) ((x) = (y))
  421. #endif
  422. #ifdef _WIN32
  423. /* Create substitutes for POSIX functions in Win32. */
  424. #if defined(__MINGW32__)
  425. /* Show no warning in case system functions are not used. */
  426. #pragma GCC diagnostic push
  427. #pragma GCC diagnostic ignored "-Wunused-function"
  428. #endif
  429. static CRITICAL_SECTION global_log_file_lock;
  430. static DWORD
  431. pthread_self(void)
  432. {
  433. return GetCurrentThreadId();
  434. }
  435. static int
  436. pthread_key_create(
  437. pthread_key_t *key,
  438. void (*_ignored)(void *) /* destructor not supported for Windows */
  439. )
  440. {
  441. (void)_ignored;
  442. if ((key != 0)) {
  443. *key = TlsAlloc();
  444. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  445. }
  446. return -2;
  447. }
  448. static int
  449. pthread_key_delete(pthread_key_t key)
  450. {
  451. return TlsFree(key) ? 0 : 1;
  452. }
  453. static int
  454. pthread_setspecific(pthread_key_t key, void *value)
  455. {
  456. return TlsSetValue(key, value) ? 0 : 1;
  457. }
  458. static void *
  459. pthread_getspecific(pthread_key_t key)
  460. {
  461. return TlsGetValue(key);
  462. }
  463. #if defined(__MINGW32__)
  464. /* Enable unused function warning again */
  465. #pragma GCC diagnostic pop
  466. #endif
  467. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  468. #else
  469. static pthread_mutexattr_t pthread_mutex_attr;
  470. #endif /* _WIN32 */
  471. #define PASSWORDS_FILE_NAME ".htpasswd"
  472. #define CGI_ENVIRONMENT_SIZE (4096)
  473. #define MAX_CGI_ENVIR_VARS (256)
  474. #define MG_BUF_LEN (8192)
  475. #ifndef MAX_REQUEST_SIZE
  476. #define MAX_REQUEST_SIZE (16384)
  477. #endif
  478. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  479. "request size length must be a positive number");
  480. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  481. #if !defined(DEBUG_TRACE)
  482. #if defined(DEBUG)
  483. #if defined(_WIN32_WCE)
  484. /* Create substitutes for POSIX functions in Win32. */
  485. #if defined(__MINGW32__)
  486. /* Show no warning in case system functions are not used. */
  487. #pragma GCC diagnostic push
  488. #pragma GCC diagnostic ignored "-Wunused-function"
  489. #endif
  490. static time_t
  491. time(time_t *ptime)
  492. {
  493. time_t t;
  494. SYSTEMTIME st;
  495. FILETIME ft;
  496. GetSystemTime(&st);
  497. SystemTimeToFileTime(&st, &ft);
  498. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  499. if (ptime != NULL) {
  500. *ptime = t;
  501. }
  502. return t;
  503. }
  504. static struct tm *
  505. localtime_s(const time_t *ptime, struct tm *ptm)
  506. {
  507. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  508. FILETIME ft, lft;
  509. SYSTEMTIME st;
  510. TIME_ZONE_INFORMATION tzinfo;
  511. if (ptm == NULL) {
  512. return NULL;
  513. }
  514. *(int64_t *)&ft = t;
  515. FileTimeToLocalFileTime(&ft, &lft);
  516. FileTimeToSystemTime(&lft, &st);
  517. ptm->tm_year = st.wYear - 1900;
  518. ptm->tm_mon = st.wMonth - 1;
  519. ptm->tm_wday = st.wDayOfWeek;
  520. ptm->tm_mday = st.wDay;
  521. ptm->tm_hour = st.wHour;
  522. ptm->tm_min = st.wMinute;
  523. ptm->tm_sec = st.wSecond;
  524. ptm->tm_yday = 0; /* hope nobody uses this */
  525. ptm->tm_isdst =
  526. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  527. return ptm;
  528. }
  529. static struct tm *
  530. gmtime_s(const time_t *ptime, struct tm *ptm)
  531. {
  532. /* FIXME(lsm): fix this. */
  533. return localtime_s(ptime, ptm);
  534. }
  535. static int mg_atomic_inc(volatile int *addr);
  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, tm_array + 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, tm_array + 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(NULL, a, wa, ARRAY_SIZE(wa));
  566. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  567. return MoveFileW(wa, wb) ? 0 : -1;
  568. }
  569. struct stat {
  570. int64_t st_size;
  571. time_t st_mtime;
  572. };
  573. static int
  574. stat(const char *name, struct stat *st)
  575. {
  576. wchar_t wbuf[PATH_MAX];
  577. WIN32_FILE_ATTRIBUTE_DATA attr;
  578. time_t creation_time, write_time;
  579. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  580. memset(&attr, 0, sizeof(attr));
  581. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  582. st->st_size =
  583. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  584. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  585. attr.ftLastWriteTime.dwHighDateTime);
  586. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  587. attr.ftCreationTime.dwHighDateTime);
  588. if (creation_time > write_time) {
  589. st->st_mtime = creation_time;
  590. } else {
  591. st->st_mtime = write_time;
  592. }
  593. return 0;
  594. }
  595. #define access(x, a) 1 /* not required anyway */
  596. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  597. #define EEXIST 1 /* TODO: See Windows error codes */
  598. #define EACCES 2 /* TODO: See Windows error codes */
  599. #define ENOENT 3 /* TODO: See Windows Error codes */
  600. #if defined(__MINGW32__)
  601. /* Enable unused function warning again */
  602. #pragma GCC diagnostic pop
  603. #endif
  604. #endif /* defined(_WIN32_WCE) */
  605. static void DEBUG_TRACE_FUNC(const char *func,
  606. unsigned line,
  607. PRINTF_FORMAT_STRING(const char *fmt),
  608. ...) PRINTF_ARGS(3, 4);
  609. static void
  610. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  611. {
  612. va_list args;
  613. flockfile(stdout);
  614. printf("*** %lu.%p.%s.%u: ",
  615. (unsigned long)time(NULL),
  616. (void *)pthread_self(),
  617. func,
  618. line);
  619. va_start(args, fmt);
  620. vprintf(fmt, args);
  621. va_end(args);
  622. putchar('\n');
  623. fflush(stdout);
  624. funlockfile(stdout);
  625. }
  626. #define DEBUG_TRACE(fmt, ...) \
  627. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  628. #else
  629. #define DEBUG_TRACE(fmt, ...) \
  630. do { \
  631. } while (0)
  632. #endif /* DEBUG */
  633. #endif /* DEBUG_TRACE */
  634. #if defined(MEMORY_DEBUGGING)
  635. unsigned long mg_memory_debug_blockCount = 0;
  636. unsigned long mg_memory_debug_totalMemUsed = 0;
  637. static void *
  638. mg_malloc_ex(size_t size, const char *file, unsigned line)
  639. {
  640. void *data = malloc(size + sizeof(size_t));
  641. void *memory = 0;
  642. char mallocStr[256];
  643. if (data) {
  644. *(size_t *)data = size;
  645. mg_memory_debug_totalMemUsed += size;
  646. mg_memory_debug_blockCount++;
  647. memory = (void *)(((char *)data) + sizeof(size_t));
  648. }
  649. sprintf(mallocStr,
  650. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  651. memory,
  652. (unsigned long)size,
  653. mg_memory_debug_totalMemUsed,
  654. mg_memory_debug_blockCount,
  655. file,
  656. line);
  657. #if defined(_WIN32)
  658. OutputDebugStringA(mallocStr);
  659. #else
  660. DEBUG_TRACE("%s", mallocStr);
  661. #endif
  662. return memory;
  663. }
  664. static void *
  665. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  666. {
  667. void *data = mg_malloc_ex(size * count, file, line);
  668. if (data) {
  669. memset(data, 0, size);
  670. }
  671. return data;
  672. }
  673. static void
  674. mg_free_ex(void *memory, const char *file, unsigned line)
  675. {
  676. char mallocStr[256];
  677. void *data = (void *)(((char *)memory) - sizeof(size_t));
  678. size_t size;
  679. if (memory) {
  680. size = *(size_t *)data;
  681. mg_memory_debug_totalMemUsed -= size;
  682. mg_memory_debug_blockCount--;
  683. sprintf(mallocStr,
  684. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  685. memory,
  686. (unsigned long)size,
  687. mg_memory_debug_totalMemUsed,
  688. mg_memory_debug_blockCount,
  689. file,
  690. line);
  691. #if defined(_WIN32)
  692. OutputDebugStringA(mallocStr);
  693. #else
  694. DEBUG_TRACE("%s", mallocStr);
  695. #endif
  696. free(data);
  697. }
  698. }
  699. static void *
  700. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  701. {
  702. char mallocStr[256];
  703. void *data;
  704. void *_realloc;
  705. size_t oldsize;
  706. if (newsize) {
  707. if (memory) {
  708. data = (void *)(((char *)memory) - sizeof(size_t));
  709. oldsize = *(size_t *)data;
  710. _realloc = realloc(data, newsize + sizeof(size_t));
  711. if (_realloc) {
  712. data = _realloc;
  713. mg_memory_debug_totalMemUsed -= oldsize;
  714. sprintf(mallocStr,
  715. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  716. memory,
  717. (unsigned long)oldsize,
  718. mg_memory_debug_totalMemUsed,
  719. mg_memory_debug_blockCount,
  720. file,
  721. line);
  722. #if defined(_WIN32)
  723. OutputDebugStringA(mallocStr);
  724. #else
  725. DEBUG_TRACE("%s", mallocStr);
  726. #endif
  727. mg_memory_debug_totalMemUsed += newsize;
  728. sprintf(mallocStr,
  729. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  730. memory,
  731. (unsigned long)newsize,
  732. mg_memory_debug_totalMemUsed,
  733. mg_memory_debug_blockCount,
  734. file,
  735. line);
  736. #if defined(_WIN32)
  737. OutputDebugStringA(mallocStr);
  738. #else
  739. DEBUG_TRACE("%s", mallocStr);
  740. #endif
  741. *(size_t *)data = newsize;
  742. data = (void *)(((char *)data) + sizeof(size_t));
  743. } else {
  744. #if defined(_WIN32)
  745. OutputDebugStringA("MEM: realloc failed\n");
  746. #else
  747. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  748. #endif
  749. return _realloc;
  750. }
  751. } else {
  752. data = mg_malloc_ex(newsize, file, line);
  753. }
  754. } else {
  755. data = 0;
  756. mg_free_ex(memory, file, line);
  757. }
  758. return data;
  759. }
  760. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  761. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  762. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  763. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  764. #else
  765. static __inline void *
  766. mg_malloc(size_t a)
  767. {
  768. return malloc(a);
  769. }
  770. static __inline void *
  771. mg_calloc(size_t a, size_t b)
  772. {
  773. return calloc(a, b);
  774. }
  775. static __inline void *
  776. mg_realloc(void *a, size_t b)
  777. {
  778. return realloc(a, b);
  779. }
  780. static __inline void
  781. mg_free(void *a)
  782. {
  783. free(a);
  784. }
  785. #endif
  786. static void mg_vsnprintf(const struct mg_connection *conn,
  787. int *truncated,
  788. char *buf,
  789. size_t buflen,
  790. const char *fmt,
  791. va_list ap);
  792. static void mg_snprintf(const struct mg_connection *conn,
  793. int *truncated,
  794. char *buf,
  795. size_t buflen,
  796. PRINTF_FORMAT_STRING(const char *fmt),
  797. ...) PRINTF_ARGS(5, 6);
  798. /* This following lines are just meant as a reminder to use the mg-functions
  799. * for memory management */
  800. #ifdef malloc
  801. #undef malloc
  802. #endif
  803. #ifdef calloc
  804. #undef calloc
  805. #endif
  806. #ifdef realloc
  807. #undef realloc
  808. #endif
  809. #ifdef free
  810. #undef free
  811. #endif
  812. #ifdef snprintf
  813. #undef snprintf
  814. #endif
  815. #ifdef vsnprintf
  816. #undef vsnprintf
  817. #endif
  818. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  819. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  820. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  821. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  822. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  823. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  824. * but this define only works well for Windows. */
  825. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  826. #endif
  827. #define MD5_STATIC static
  828. #include "md5.inl"
  829. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  830. #ifdef NO_SOCKLEN_T
  831. typedef int socklen_t;
  832. #endif /* NO_SOCKLEN_T */
  833. #define _DARWIN_UNLIMITED_SELECT
  834. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  835. #if !defined(MSG_NOSIGNAL)
  836. #define MSG_NOSIGNAL (0)
  837. #endif
  838. #if !defined(SOMAXCONN)
  839. #define SOMAXCONN (100)
  840. #endif
  841. /* Size of the accepted socket queue */
  842. #if !defined(MGSQLEN)
  843. #define MGSQLEN (20)
  844. #endif
  845. #if defined(NO_SSL)
  846. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  847. typedef struct SSL_CTX SSL_CTX;
  848. #else
  849. #if defined(NO_SSL_DL)
  850. #include <openssl/ssl.h>
  851. #include <openssl/err.h>
  852. #include <openssl/crypto.h>
  853. #include <openssl/x509.h>
  854. #include <openssl/pem.h>
  855. #include <openssl/engine.h>
  856. #include <openssl/conf.h>
  857. #else
  858. /* SSL loaded dynamically from DLL.
  859. * I put the prototypes here to be independent from OpenSSL source
  860. * installation. */
  861. typedef struct ssl_st SSL;
  862. typedef struct ssl_method_st SSL_METHOD;
  863. typedef struct ssl_ctx_st SSL_CTX;
  864. typedef struct x509_store_ctx_st X509_STORE_CTX;
  865. #define SSL_CTRL_OPTIONS (32)
  866. #define SSL_CTRL_CLEAR_OPTIONS (77)
  867. #define SSL_CTRL_SET_ECDH_AUTO (94)
  868. #define SSL_VERIFY_NONE (0)
  869. #define SSL_VERIFY_PEER (1)
  870. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  871. #define SSL_VERIFY_CLIENT_ONCE (4)
  872. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  873. #define SSL_OP_NO_SSLv2 (0x01000000L)
  874. #define SSL_OP_NO_SSLv3 (0x02000000L)
  875. #define SSL_OP_NO_TLSv1 (0x04000000L)
  876. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  877. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  878. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  879. #define SSL_ERROR_NONE (0)
  880. #define SSL_ERROR_SSL (1)
  881. #define SSL_ERROR_WANT_READ (2)
  882. #define SSL_ERROR_WANT_WRITE (3)
  883. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  884. #define SSL_ERROR_SYSCALL (5) /* see errno */
  885. #define SSL_ERROR_ZERO_RETURN (6)
  886. #define SSL_ERROR_WANT_CONNECT (7)
  887. #define SSL_ERROR_WANT_ACCEPT (8)
  888. struct ssl_func {
  889. const char *name; /* SSL function name */
  890. void (*ptr)(void); /* Function pointer */
  891. };
  892. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  893. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  894. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  895. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  896. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  897. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  898. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  899. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  900. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  901. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  902. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  903. #define SSL_CTX_use_PrivateKey_file \
  904. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  905. #define SSL_CTX_use_certificate_file \
  906. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  907. #define SSL_CTX_set_default_passwd_cb \
  908. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  909. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  910. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  911. #define SSL_CTX_use_certificate_chain_file \
  912. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  913. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  914. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  915. #define SSL_CTX_set_verify \
  916. (*(void (*)(SSL_CTX *, \
  917. int, \
  918. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  919. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  920. #define SSL_CTX_load_verify_locations \
  921. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  922. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  923. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  924. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  925. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  926. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  927. #define SSL_CIPHER_get_name \
  928. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  929. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  930. #define SSL_CTX_set_session_id_context \
  931. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  932. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  933. #define SSL_CTX_set_cipher_list \
  934. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  935. #define SSL_CTX_set_options(ctx, op) \
  936. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  937. #define SSL_CTX_clear_options(ctx, op) \
  938. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  939. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  940. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  941. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  942. #define CRYPTO_set_locking_callback \
  943. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  944. #define CRYPTO_set_id_callback \
  945. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  946. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  947. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  948. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  949. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  950. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  951. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  952. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  953. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  954. /* set_ssl_option() function updates this array.
  955. * It loads SSL library dynamically and changes NULLs to the actual addresses
  956. * of respective functions. The macros above (like SSL_connect()) are really
  957. * just calling these functions indirectly via the pointer. */
  958. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  959. {"SSL_accept", NULL},
  960. {"SSL_connect", NULL},
  961. {"SSL_read", NULL},
  962. {"SSL_write", NULL},
  963. {"SSL_get_error", NULL},
  964. {"SSL_set_fd", NULL},
  965. {"SSL_new", NULL},
  966. {"SSL_CTX_new", NULL},
  967. {"SSLv23_server_method", NULL},
  968. {"SSL_library_init", NULL},
  969. {"SSL_CTX_use_PrivateKey_file", NULL},
  970. {"SSL_CTX_use_certificate_file", NULL},
  971. {"SSL_CTX_set_default_passwd_cb", NULL},
  972. {"SSL_CTX_free", NULL},
  973. {"SSL_load_error_strings", NULL},
  974. {"SSL_CTX_use_certificate_chain_file", NULL},
  975. {"SSLv23_client_method", NULL},
  976. {"SSL_pending", NULL},
  977. {"SSL_CTX_set_verify", NULL},
  978. {"SSL_shutdown", NULL},
  979. {"SSL_CTX_load_verify_locations", NULL},
  980. {"SSL_CTX_set_default_verify_paths", NULL},
  981. {"SSL_CTX_set_verify_depth", NULL},
  982. {"SSL_get_peer_certificate", NULL},
  983. {"SSL_get_version", NULL},
  984. {"SSL_get_current_cipher", NULL},
  985. {"SSL_CIPHER_get_name", NULL},
  986. {"SSL_CTX_check_private_key", NULL},
  987. {"SSL_CTX_set_session_id_context", NULL},
  988. {"SSL_CTX_ctrl", NULL},
  989. {"SSL_CTX_set_cipher_list", NULL},
  990. {NULL, NULL}};
  991. /* Similar array as ssl_sw. These functions could be located in different
  992. * lib. */
  993. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  994. {"CRYPTO_set_locking_callback", NULL},
  995. {"CRYPTO_set_id_callback", NULL},
  996. {"ERR_get_error", NULL},
  997. {"ERR_error_string", NULL},
  998. {"ERR_remove_state", NULL},
  999. {"ERR_free_strings", NULL},
  1000. {"ENGINE_cleanup", NULL},
  1001. {"CONF_modules_unload", NULL},
  1002. {"CRYPTO_cleanup_all_ex_data", NULL},
  1003. {"EVP_cleanup", NULL},
  1004. {NULL, NULL}};
  1005. #endif /* NO_SSL_DL */
  1006. #endif /* NO_SSL */
  1007. #if !defined(NO_CACHING)
  1008. static const char *month_names[] = {"Jan",
  1009. "Feb",
  1010. "Mar",
  1011. "Apr",
  1012. "May",
  1013. "Jun",
  1014. "Jul",
  1015. "Aug",
  1016. "Sep",
  1017. "Oct",
  1018. "Nov",
  1019. "Dec"};
  1020. #endif /* !NO_CACHING */
  1021. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1022. * union u. */
  1023. union usa {
  1024. struct sockaddr sa;
  1025. struct sockaddr_in sin;
  1026. #if defined(USE_IPV6)
  1027. struct sockaddr_in6 sin6;
  1028. #endif
  1029. };
  1030. /* Describes a string (chunk of memory). */
  1031. struct vec {
  1032. const char *ptr;
  1033. size_t len;
  1034. };
  1035. struct file {
  1036. uint64_t size;
  1037. time_t last_modified;
  1038. FILE *fp;
  1039. const char *membuf; /* Non-NULL if file data is in memory */
  1040. int is_directory;
  1041. int gzipped; /* set to 1 if the content is gzipped
  1042. * in which case we need a content-encoding: gzip header */
  1043. };
  1044. #define STRUCT_FILE_INITIALIZER \
  1045. { \
  1046. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1047. }
  1048. /* Describes listening socket, or socket which was accept()-ed by the master
  1049. * thread and queued for future handling by the worker thread. */
  1050. struct socket {
  1051. SOCKET sock; /* Listening socket */
  1052. union usa lsa; /* Local socket address */
  1053. union usa rsa; /* Remote socket address */
  1054. unsigned char is_ssl; /* Is port SSL-ed */
  1055. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1056. * port */
  1057. };
  1058. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1059. enum {
  1060. CGI_EXTENSIONS,
  1061. CGI_ENVIRONMENT,
  1062. PUT_DELETE_PASSWORDS_FILE,
  1063. CGI_INTERPRETER,
  1064. PROTECT_URI,
  1065. AUTHENTICATION_DOMAIN,
  1066. SSI_EXTENSIONS,
  1067. THROTTLE,
  1068. ACCESS_LOG_FILE,
  1069. ENABLE_DIRECTORY_LISTING,
  1070. ERROR_LOG_FILE,
  1071. GLOBAL_PASSWORDS_FILE,
  1072. INDEX_FILES,
  1073. ENABLE_KEEP_ALIVE,
  1074. ACCESS_CONTROL_LIST,
  1075. EXTRA_MIME_TYPES,
  1076. LISTENING_PORTS,
  1077. DOCUMENT_ROOT,
  1078. SSL_CERTIFICATE,
  1079. NUM_THREADS,
  1080. RUN_AS_USER,
  1081. REWRITE,
  1082. HIDE_FILES,
  1083. REQUEST_TIMEOUT,
  1084. SSL_DO_VERIFY_PEER,
  1085. SSL_CA_PATH,
  1086. SSL_CA_FILE,
  1087. SSL_VERIFY_DEPTH,
  1088. SSL_DEFAULT_VERIFY_PATHS,
  1089. SSL_CIPHER_LIST,
  1090. SSL_PROTOCOL_VERSION,
  1091. SSL_SHORT_TRUST,
  1092. #if defined(USE_WEBSOCKET)
  1093. WEBSOCKET_TIMEOUT,
  1094. #endif
  1095. DECODE_URL,
  1096. #if defined(USE_LUA)
  1097. LUA_PRELOAD_FILE,
  1098. LUA_SCRIPT_EXTENSIONS,
  1099. LUA_SERVER_PAGE_EXTENSIONS,
  1100. #endif
  1101. #if defined(USE_DUKTAPE)
  1102. DUKTAPE_SCRIPT_EXTENSIONS,
  1103. #endif
  1104. #if defined(USE_WEBSOCKET)
  1105. WEBSOCKET_ROOT,
  1106. #endif
  1107. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1108. LUA_WEBSOCKET_EXTENSIONS,
  1109. #endif
  1110. ACCESS_CONTROL_ALLOW_ORIGIN,
  1111. ERROR_PAGES,
  1112. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1113. * socket option typedef TCP_NODELAY. */
  1114. #if !defined(NO_CACHING)
  1115. STATIC_FILE_MAX_AGE,
  1116. #endif
  1117. NUM_OPTIONS
  1118. };
  1119. /* Config option name, config types, default value */
  1120. static struct mg_option config_options[] = {
  1121. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1122. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1123. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1124. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1125. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1126. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1127. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1128. {"throttle", CONFIG_TYPE_STRING, NULL},
  1129. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1130. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1131. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1132. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1133. {"index_files",
  1134. CONFIG_TYPE_STRING,
  1135. #ifdef USE_LUA
  1136. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1137. "index.shtml,index.php"},
  1138. #else
  1139. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1140. #endif
  1141. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1142. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1143. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1144. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1145. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1146. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1147. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1148. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1149. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1150. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1151. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1152. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1153. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1154. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1155. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1156. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1157. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1158. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1159. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1160. #if defined(USE_WEBSOCKET)
  1161. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1162. #endif
  1163. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1164. #if defined(USE_LUA)
  1165. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1166. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1167. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1168. #endif
  1169. #if defined(USE_DUKTAPE)
  1170. /* The support for duktape is still in alpha version state.
  1171. * The name of this config option might change. */
  1172. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1173. #endif
  1174. #if defined(USE_WEBSOCKET)
  1175. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1176. #endif
  1177. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1178. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1179. #endif
  1180. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1181. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1182. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1183. #if !defined(NO_CACHING)
  1184. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1185. #endif
  1186. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1187. /* Check if the config_options and the corresponding enum have compatible
  1188. * sizes. */
  1189. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1190. == (NUM_OPTIONS + 1),
  1191. "config_options and enum not sync");
  1192. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1193. struct mg_handler_info {
  1194. /* Name/Pattern of the URI. */
  1195. char *uri;
  1196. size_t uri_len;
  1197. /* handler type */
  1198. int handler_type;
  1199. /* Handler for http/https or authorization requests. */
  1200. mg_request_handler handler;
  1201. /* Handler for ws/wss (websocket) requests. */
  1202. mg_websocket_connect_handler connect_handler;
  1203. mg_websocket_ready_handler ready_handler;
  1204. mg_websocket_data_handler data_handler;
  1205. mg_websocket_close_handler close_handler;
  1206. /* Handler for authorization requests */
  1207. mg_authorization_handler auth_handler;
  1208. /* User supplied argument for the handler function. */
  1209. void *cbdata;
  1210. /* next handler in a linked list */
  1211. struct mg_handler_info *next;
  1212. };
  1213. struct mg_context {
  1214. volatile int stop_flag; /* Should we stop event loop */
  1215. SSL_CTX *ssl_ctx; /* SSL context */
  1216. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1217. struct mg_callbacks callbacks; /* User-defined callback function */
  1218. void *user_data; /* User-defined data */
  1219. int context_type; /* 1 = server context, 2 = client context */
  1220. struct socket *listening_sockets;
  1221. struct pollfd *listening_socket_fds;
  1222. unsigned int num_listening_sockets;
  1223. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1224. #ifdef ALTERNATIVE_QUEUE
  1225. struct socket *client_socks;
  1226. int *client_wait_events;
  1227. #else
  1228. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1229. volatile int sq_head; /* Head of the socket queue */
  1230. volatile int sq_tail; /* Tail of the socket queue */
  1231. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1232. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1233. #endif
  1234. pthread_t masterthreadid; /* The master thread ID */
  1235. unsigned int
  1236. cfg_worker_threads; /* The number of configured worker threads. */
  1237. pthread_t *workerthreadids; /* The worker thread IDs */
  1238. time_t start_time; /* Server start time, used for authentication */
  1239. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1240. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1241. unsigned long nonce_count; /* Used nonces, used for authentication */
  1242. char *systemName; /* What operating system is running */
  1243. /* linked list of uri handlers */
  1244. struct mg_handler_info *handlers;
  1245. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1246. /* linked list of shared lua websockets */
  1247. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1248. #endif
  1249. #ifdef USE_TIMERS
  1250. struct ttimers *timers;
  1251. #endif
  1252. };
  1253. struct mg_connection {
  1254. struct mg_request_info request_info;
  1255. struct mg_context *ctx;
  1256. SSL *ssl; /* SSL descriptor */
  1257. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1258. struct socket client; /* Connected client */
  1259. time_t conn_birth_time; /* Time (wall clock) when connection was
  1260. * established */
  1261. struct timespec req_time; /* Time (since system start) when the request
  1262. * was received */
  1263. int64_t num_bytes_sent; /* Total bytes sent to client */
  1264. int64_t content_len; /* Content-Length header value */
  1265. int64_t consumed_content; /* How many bytes of content have been read */
  1266. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1267. * data available, 2: all data read */
  1268. size_t chunk_remainder; /* Unread data from the last chunk */
  1269. char *buf; /* Buffer for received data */
  1270. char *path_info; /* PATH_INFO part of the URL */
  1271. int must_close; /* 1 if connection must be closed */
  1272. int in_error_handler; /* 1 if in handler for user defined error
  1273. * pages */
  1274. int internal_error; /* 1 if an error occured while processing the
  1275. * request */
  1276. int buf_size; /* Buffer size */
  1277. int request_len; /* Size of the request + headers in a buffer */
  1278. int data_len; /* Total size of data in a buffer */
  1279. int status_code; /* HTTP reply status code, e.g. 200 */
  1280. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1281. * throttle */
  1282. time_t last_throttle_time; /* Last time throttled data was sent */
  1283. int64_t last_throttle_bytes; /* Bytes sent this second */
  1284. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1285. * atomic transmissions for websockets */
  1286. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1287. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1288. #endif
  1289. };
  1290. static pthread_key_t sTlsKey; /* Thread local storage index */
  1291. static int sTlsInit = 0;
  1292. static int thread_idx_max = 0;
  1293. struct mg_workerTLS {
  1294. int is_master;
  1295. unsigned long thread_idx;
  1296. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1297. HANDLE pthread_cond_helper_mutex;
  1298. struct mg_workerTLS *next_waiting_thread;
  1299. #endif
  1300. };
  1301. /* Directory entry */
  1302. struct de {
  1303. struct mg_connection *conn;
  1304. char *file_name;
  1305. struct file file;
  1306. };
  1307. #if defined(USE_WEBSOCKET)
  1308. static int is_websocket_protocol(const struct mg_connection *conn);
  1309. #else
  1310. #define is_websocket_protocol(conn) (0)
  1311. #endif
  1312. static int
  1313. mg_atomic_inc(volatile int *addr)
  1314. {
  1315. int ret;
  1316. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1317. /* Depending on the SDK, this function uses either
  1318. * (volatile unsigned int *) or (volatile LONG *),
  1319. * so whatever you use, the other SDK is likely to raise a warning. */
  1320. ret = InterlockedIncrement((volatile long *)addr);
  1321. #elif defined(__GNUC__) \
  1322. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1323. ret = __sync_add_and_fetch(addr, 1);
  1324. #else
  1325. ret = (++(*addr));
  1326. #endif
  1327. return ret;
  1328. }
  1329. static int
  1330. mg_atomic_dec(volatile int *addr)
  1331. {
  1332. int ret;
  1333. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1334. /* Depending on the SDK, this function uses either
  1335. * (volatile unsigned int *) or (volatile LONG *),
  1336. * so whatever you use, the other SDK is likely to raise a warning. */
  1337. ret = InterlockedDecrement((volatile long *)addr);
  1338. #elif defined(__GNUC__) \
  1339. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1340. ret = __sync_sub_and_fetch(addr, 1);
  1341. #else
  1342. ret = (--(*addr));
  1343. #endif
  1344. return ret;
  1345. }
  1346. #if !defined(NO_THREAD_NAME)
  1347. #if defined(_WIN32) && defined(_MSC_VER)
  1348. /* Set the thread name for debugging purposes in Visual Studio
  1349. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1350. */
  1351. #pragma pack(push, 8)
  1352. typedef struct tagTHREADNAME_INFO {
  1353. DWORD dwType; /* Must be 0x1000. */
  1354. LPCSTR szName; /* Pointer to name (in user addr space). */
  1355. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1356. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1357. } THREADNAME_INFO;
  1358. #pragma pack(pop)
  1359. #elif defined(__linux__)
  1360. #include <sys/prctl.h>
  1361. #include <sys/sendfile.h>
  1362. #include <sys/eventfd.h>
  1363. static int
  1364. event_create(void)
  1365. {
  1366. int ret = eventfd(0, EFD_CLOEXEC);
  1367. if (ret == -1) {
  1368. /* Linux uses -1 on error, Windows NULL. */
  1369. /* However, Linux does not return 0 on success either. */
  1370. return 0;
  1371. }
  1372. return ret;
  1373. }
  1374. static int
  1375. event_wait(int eventhdl)
  1376. {
  1377. uint64_t u;
  1378. int s = read(eventhdl, &u, sizeof(u));
  1379. if (s != sizeof(uint64_t)) {
  1380. /* error */
  1381. return 0;
  1382. }
  1383. (void)u; /* the value is not required */
  1384. return 1;
  1385. }
  1386. static int
  1387. event_signal(int eventhdl)
  1388. {
  1389. uint64_t u = 1;
  1390. int s = write(eventhdl, &u, sizeof(u));
  1391. if (s != sizeof(uint64_t)) {
  1392. /* error */
  1393. return 0;
  1394. }
  1395. return 1;
  1396. }
  1397. static void
  1398. event_destroy(int eventhdl)
  1399. {
  1400. close(eventhdl);
  1401. }
  1402. #endif
  1403. static void
  1404. mg_set_thread_name(const char *name)
  1405. {
  1406. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1407. mg_snprintf(
  1408. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1409. #if defined(_WIN32)
  1410. #if defined(_MSC_VER)
  1411. /* Windows and Visual Studio Compiler */
  1412. __try
  1413. {
  1414. THREADNAME_INFO info;
  1415. info.dwType = 0x1000;
  1416. info.szName = threadName;
  1417. info.dwThreadID = ~0U;
  1418. info.dwFlags = 0;
  1419. RaiseException(0x406D1388,
  1420. 0,
  1421. sizeof(info) / sizeof(ULONG_PTR),
  1422. (ULONG_PTR *)&info);
  1423. }
  1424. __except(EXCEPTION_EXECUTE_HANDLER)
  1425. {
  1426. }
  1427. #elif defined(__MINGW32__)
  1428. /* No option known to set thread name for MinGW */
  1429. #endif
  1430. #elif defined(__GLIBC__) \
  1431. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1432. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1433. (void)pthread_setname_np(pthread_self(), threadName);
  1434. #elif defined(__linux__)
  1435. /* on linux we can use the old prctl function */
  1436. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1437. #endif
  1438. }
  1439. #else /* !defined(NO_THREAD_NAME) */
  1440. void
  1441. mg_set_thread_name(const char *threadName)
  1442. {
  1443. }
  1444. #endif
  1445. #if defined(MG_LEGACY_INTERFACE)
  1446. const char **
  1447. mg_get_valid_option_names(void)
  1448. {
  1449. /* This function is deprecated. Use mg_get_valid_options instead. */
  1450. static const char *
  1451. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1452. int i;
  1453. for (i = 0; config_options[i].name != NULL; i++) {
  1454. data[i * 2] = config_options[i].name;
  1455. data[i * 2 + 1] = config_options[i].default_value;
  1456. }
  1457. return data;
  1458. }
  1459. #endif
  1460. const struct mg_option *
  1461. mg_get_valid_options(void)
  1462. {
  1463. return config_options;
  1464. }
  1465. static int
  1466. is_file_in_memory(const struct mg_connection *conn,
  1467. const char *path,
  1468. struct file *filep)
  1469. {
  1470. size_t size = 0;
  1471. if (!conn || !filep) {
  1472. return 0;
  1473. }
  1474. if (conn->ctx->callbacks.open_file) {
  1475. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1476. if (filep->membuf != NULL) {
  1477. /* NOTE: override filep->size only on success. Otherwise, it might
  1478. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1479. filep->size = size;
  1480. }
  1481. }
  1482. return filep->membuf != NULL;
  1483. }
  1484. static int
  1485. is_file_opened(const struct file *filep)
  1486. {
  1487. if (!filep) {
  1488. return 0;
  1489. }
  1490. return filep->membuf != NULL || filep->fp != NULL;
  1491. }
  1492. /* mg_fopen will open a file either in memory or on the disk.
  1493. * The input parameter path is a string in UTF-8 encoding.
  1494. * The input parameter mode is the same as for fopen.
  1495. * Either fp or membuf will be set in the output struct filep.
  1496. * The function returns 1 on success, 0 on error. */
  1497. static int
  1498. mg_fopen(const struct mg_connection *conn,
  1499. const char *path,
  1500. const char *mode,
  1501. struct file *filep)
  1502. {
  1503. struct stat st;
  1504. if (!filep) {
  1505. return 0;
  1506. }
  1507. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1508. * only get the file status. They should not work on different members of
  1509. * the same structure (bad cohesion). */
  1510. memset(filep, 0, sizeof(*filep));
  1511. if (stat(path, &st) == 0) {
  1512. filep->size = (uint64_t)(st.st_size);
  1513. }
  1514. if (!is_file_in_memory(conn, path, filep)) {
  1515. #ifdef _WIN32
  1516. wchar_t wbuf[PATH_MAX], wmode[20];
  1517. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1518. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1519. filep->fp = _wfopen(wbuf, wmode);
  1520. #else
  1521. /* Linux et al already use unicode. No need to convert. */
  1522. filep->fp = fopen(path, mode);
  1523. #endif
  1524. }
  1525. return is_file_opened(filep);
  1526. }
  1527. static void
  1528. mg_fclose(struct file *filep)
  1529. {
  1530. if (filep != NULL && filep->fp != NULL) {
  1531. fclose(filep->fp);
  1532. }
  1533. }
  1534. static void
  1535. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1536. {
  1537. for (; *src != '\0' && n > 1; n--) {
  1538. *dst++ = *src++;
  1539. }
  1540. *dst = '\0';
  1541. }
  1542. static int
  1543. lowercase(const char *s)
  1544. {
  1545. return tolower(*(const unsigned char *)s);
  1546. }
  1547. int
  1548. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1549. {
  1550. int diff = 0;
  1551. if (len > 0) {
  1552. do {
  1553. diff = lowercase(s1++) - lowercase(s2++);
  1554. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1555. }
  1556. return diff;
  1557. }
  1558. int
  1559. mg_strcasecmp(const char *s1, const char *s2)
  1560. {
  1561. int diff;
  1562. do {
  1563. diff = lowercase(s1++) - lowercase(s2++);
  1564. } while (diff == 0 && s1[-1] != '\0');
  1565. return diff;
  1566. }
  1567. static char *
  1568. mg_strndup(const char *ptr, size_t len)
  1569. {
  1570. char *p;
  1571. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1572. mg_strlcpy(p, ptr, len + 1);
  1573. }
  1574. return p;
  1575. }
  1576. static char *
  1577. mg_strdup(const char *str)
  1578. {
  1579. return mg_strndup(str, strlen(str));
  1580. }
  1581. static const char *
  1582. mg_strcasestr(const char *big_str, const char *small_str)
  1583. {
  1584. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1585. if (big_len >= small_len) {
  1586. for (i = 0; i <= (big_len - small_len); i++) {
  1587. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1588. return big_str + i;
  1589. }
  1590. }
  1591. }
  1592. return NULL;
  1593. }
  1594. /* Return null terminated string of given maximum length.
  1595. * Report errors if length is exceeded. */
  1596. static void
  1597. mg_vsnprintf(const struct mg_connection *conn,
  1598. int *truncated,
  1599. char *buf,
  1600. size_t buflen,
  1601. const char *fmt,
  1602. va_list ap)
  1603. {
  1604. int n, ok;
  1605. if (buflen == 0) {
  1606. return;
  1607. }
  1608. #ifdef __clang__
  1609. #pragma clang diagnostic push
  1610. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1611. /* Using fmt as a non-literal is intended here, since it is mostly called
  1612. * indirectly by mg_snprintf */
  1613. #endif
  1614. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1615. ok = (n >= 0) && ((size_t)n < buflen);
  1616. #ifdef __clang__
  1617. #pragma clang diagnostic pop
  1618. #endif
  1619. if (ok) {
  1620. if (truncated) {
  1621. *truncated = 0;
  1622. }
  1623. } else {
  1624. if (truncated) {
  1625. *truncated = 1;
  1626. }
  1627. mg_cry(conn,
  1628. "truncating vsnprintf buffer: [%.*s]",
  1629. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1630. buf);
  1631. n = (int)buflen - 1;
  1632. }
  1633. buf[n] = '\0';
  1634. }
  1635. static void
  1636. mg_snprintf(const struct mg_connection *conn,
  1637. int *truncated,
  1638. char *buf,
  1639. size_t buflen,
  1640. const char *fmt,
  1641. ...)
  1642. {
  1643. va_list ap;
  1644. va_start(ap, fmt);
  1645. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1646. va_end(ap);
  1647. }
  1648. static int
  1649. get_option_index(const char *name)
  1650. {
  1651. int i;
  1652. for (i = 0; config_options[i].name != NULL; i++) {
  1653. if (strcmp(config_options[i].name, name) == 0) {
  1654. return i;
  1655. }
  1656. }
  1657. return -1;
  1658. }
  1659. const char *
  1660. mg_get_option(const struct mg_context *ctx, const char *name)
  1661. {
  1662. int i;
  1663. if ((i = get_option_index(name)) == -1) {
  1664. return NULL;
  1665. } else if (!ctx || ctx->config[i] == NULL) {
  1666. return "";
  1667. } else {
  1668. return ctx->config[i];
  1669. }
  1670. }
  1671. struct mg_context *
  1672. mg_get_context(const struct mg_connection *conn)
  1673. {
  1674. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1675. }
  1676. void *
  1677. mg_get_user_data(const struct mg_context *ctx)
  1678. {
  1679. return (ctx == NULL) ? NULL : ctx->user_data;
  1680. }
  1681. void
  1682. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1683. {
  1684. if (conn != NULL) {
  1685. conn->request_info.conn_data = data;
  1686. }
  1687. }
  1688. void *
  1689. mg_get_user_connection_data(const struct mg_connection *conn)
  1690. {
  1691. if (conn != NULL) {
  1692. return conn->request_info.conn_data;
  1693. }
  1694. return NULL;
  1695. }
  1696. size_t
  1697. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1698. {
  1699. size_t i;
  1700. if (!ctx) {
  1701. return 0;
  1702. }
  1703. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1704. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1705. ports[i] =
  1706. #if defined(USE_IPV6)
  1707. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1708. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1709. :
  1710. #endif
  1711. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1712. }
  1713. return i;
  1714. }
  1715. int
  1716. mg_get_server_ports(const struct mg_context *ctx,
  1717. int size,
  1718. struct mg_server_ports *ports)
  1719. {
  1720. int i, cnt = 0;
  1721. if (size <= 0) {
  1722. return -1;
  1723. }
  1724. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1725. if (!ctx) {
  1726. return -1;
  1727. }
  1728. if (!ctx->listening_sockets) {
  1729. return -1;
  1730. }
  1731. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1732. ports[cnt].port =
  1733. #if defined(USE_IPV6)
  1734. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1735. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1736. :
  1737. #endif
  1738. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1739. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1740. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1741. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1742. /* IPv4 */
  1743. ports[cnt].protocol = 1;
  1744. cnt++;
  1745. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1746. /* IPv6 */
  1747. ports[cnt].protocol = 3;
  1748. cnt++;
  1749. }
  1750. }
  1751. return cnt;
  1752. }
  1753. static void
  1754. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1755. {
  1756. buf[0] = '\0';
  1757. if (!usa) {
  1758. return;
  1759. }
  1760. if (usa->sa.sa_family == AF_INET) {
  1761. getnameinfo(&usa->sa,
  1762. sizeof(usa->sin),
  1763. buf,
  1764. (unsigned)len,
  1765. NULL,
  1766. 0,
  1767. NI_NUMERICHOST);
  1768. }
  1769. #if defined(USE_IPV6)
  1770. else if (usa->sa.sa_family == AF_INET6) {
  1771. getnameinfo(&usa->sa,
  1772. sizeof(usa->sin6),
  1773. buf,
  1774. (unsigned)len,
  1775. NULL,
  1776. 0,
  1777. NI_NUMERICHOST);
  1778. }
  1779. #endif
  1780. }
  1781. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1782. * included in all responses other than 100, 101, 5xx. */
  1783. static void
  1784. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1785. {
  1786. struct tm *tm;
  1787. tm = ((t != NULL) ? gmtime(t) : NULL);
  1788. if (tm != NULL) {
  1789. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1790. } else {
  1791. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1792. buf[buf_len - 1] = '\0';
  1793. }
  1794. }
  1795. /* difftime for struct timespec. Return value is in seconds. */
  1796. static double
  1797. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1798. {
  1799. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1800. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1801. }
  1802. /* Print error message to the opened error log stream. */
  1803. void
  1804. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1805. {
  1806. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1807. va_list ap;
  1808. struct file fi;
  1809. time_t timestamp;
  1810. va_start(ap, fmt);
  1811. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1812. va_end(ap);
  1813. buf[sizeof(buf) - 1] = 0;
  1814. if (!conn) {
  1815. puts(buf);
  1816. return;
  1817. }
  1818. /* Do not lock when getting the callback value, here and below.
  1819. * I suppose this is fine, since function cannot disappear in the
  1820. * same way string option can. */
  1821. if ((conn->ctx->callbacks.log_message == NULL)
  1822. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1823. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1824. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1825. == 0) {
  1826. fi.fp = NULL;
  1827. }
  1828. } else {
  1829. fi.fp = NULL;
  1830. }
  1831. if (fi.fp != NULL) {
  1832. flockfile(fi.fp);
  1833. timestamp = time(NULL);
  1834. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1835. fprintf(fi.fp,
  1836. "[%010lu] [error] [client %s] ",
  1837. (unsigned long)timestamp,
  1838. src_addr);
  1839. if (conn->request_info.request_method != NULL) {
  1840. fprintf(fi.fp,
  1841. "%s %s: ",
  1842. conn->request_info.request_method,
  1843. conn->request_info.request_uri);
  1844. }
  1845. fprintf(fi.fp, "%s", buf);
  1846. fputc('\n', fi.fp);
  1847. fflush(fi.fp);
  1848. funlockfile(fi.fp);
  1849. mg_fclose(&fi);
  1850. }
  1851. }
  1852. }
  1853. /* Return fake connection structure. Used for logging, if connection
  1854. * is not applicable at the moment of logging. */
  1855. static struct mg_connection *
  1856. fc(struct mg_context *ctx)
  1857. {
  1858. static struct mg_connection fake_connection;
  1859. fake_connection.ctx = ctx;
  1860. return &fake_connection;
  1861. }
  1862. const char *
  1863. mg_version(void)
  1864. {
  1865. return CIVETWEB_VERSION;
  1866. }
  1867. const struct mg_request_info *
  1868. mg_get_request_info(const struct mg_connection *conn)
  1869. {
  1870. if (!conn) {
  1871. return NULL;
  1872. }
  1873. return &conn->request_info;
  1874. }
  1875. /* Skip the characters until one of the delimiters characters found.
  1876. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1877. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1878. * Delimiters can be quoted with quotechar. */
  1879. static char *
  1880. skip_quoted(char **buf,
  1881. const char *delimiters,
  1882. const char *whitespace,
  1883. char quotechar)
  1884. {
  1885. char *p, *begin_word, *end_word, *end_whitespace;
  1886. begin_word = *buf;
  1887. end_word = begin_word + strcspn(begin_word, delimiters);
  1888. /* Check for quotechar */
  1889. if (end_word > begin_word) {
  1890. p = end_word - 1;
  1891. while (*p == quotechar) {
  1892. /* While the delimiter is quoted, look for the next delimiter. */
  1893. /* This happens, e.g., in calls from parse_auth_header,
  1894. * if the user name contains a " character. */
  1895. /* If there is anything beyond end_word, copy it. */
  1896. if (*end_word != '\0') {
  1897. size_t end_off = strcspn(end_word + 1, delimiters);
  1898. memmove(p, end_word, end_off + 1);
  1899. p += end_off; /* p must correspond to end_word - 1 */
  1900. end_word += end_off + 1;
  1901. } else {
  1902. *p = '\0';
  1903. break;
  1904. }
  1905. }
  1906. for (p++; p < end_word; p++) {
  1907. *p = '\0';
  1908. }
  1909. }
  1910. if (*end_word == '\0') {
  1911. *buf = end_word;
  1912. } else {
  1913. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1914. for (p = end_word; p < end_whitespace; p++) {
  1915. *p = '\0';
  1916. }
  1917. *buf = end_whitespace;
  1918. }
  1919. return begin_word;
  1920. }
  1921. /* Simplified version of skip_quoted without quote char
  1922. * and whitespace == delimiters */
  1923. static char *
  1924. skip(char **buf, const char *delimiters)
  1925. {
  1926. return skip_quoted(buf, delimiters, delimiters, 0);
  1927. }
  1928. /* Return HTTP header value, or NULL if not found. */
  1929. static const char *
  1930. get_header(const struct mg_request_info *ri, const char *name)
  1931. {
  1932. int i;
  1933. if (ri) {
  1934. for (i = 0; i < ri->num_headers; i++) {
  1935. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1936. return ri->http_headers[i].value;
  1937. }
  1938. }
  1939. }
  1940. return NULL;
  1941. }
  1942. const char *
  1943. mg_get_header(const struct mg_connection *conn, const char *name)
  1944. {
  1945. if (!conn) {
  1946. return NULL;
  1947. }
  1948. return get_header(&conn->request_info, name);
  1949. }
  1950. /* A helper function for traversing a comma separated list of values.
  1951. * It returns a list pointer shifted to the next value, or NULL if the end
  1952. * of the list found.
  1953. * Value is stored in val vector. If value has form "x=y", then eq_val
  1954. * vector is initialized to point to the "y" part, and val vector length
  1955. * is adjusted to point only to "x". */
  1956. static const char *
  1957. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1958. {
  1959. int end;
  1960. reparse:
  1961. if (val == NULL || list == NULL || *list == '\0') {
  1962. /* End of the list */
  1963. list = NULL;
  1964. } else {
  1965. /* Skip over leading LWS */
  1966. while (*list == ' ' || *list == '\t')
  1967. list++;
  1968. val->ptr = list;
  1969. if ((list = strchr(val->ptr, ',')) != NULL) {
  1970. /* Comma found. Store length and shift the list ptr */
  1971. val->len = ((size_t)(list - val->ptr));
  1972. list++;
  1973. } else {
  1974. /* This value is the last one */
  1975. list = val->ptr + strlen(val->ptr);
  1976. val->len = ((size_t)(list - val->ptr));
  1977. }
  1978. /* Adjust length for trailing LWS */
  1979. end = (int)val->len - 1;
  1980. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1981. end--;
  1982. val->len = (size_t)(end + 1);
  1983. if (val->len == 0) {
  1984. /* Ignore any empty entries. */
  1985. goto reparse;
  1986. }
  1987. if (eq_val != NULL) {
  1988. /* Value has form "x=y", adjust pointers and lengths
  1989. * so that val points to "x", and eq_val points to "y". */
  1990. eq_val->len = 0;
  1991. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1992. if (eq_val->ptr != NULL) {
  1993. eq_val->ptr++; /* Skip over '=' character */
  1994. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1995. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1996. }
  1997. }
  1998. }
  1999. return list;
  2000. }
  2001. /* A helper function for checking if a comma separated list of values contains
  2002. * the given option (case insensitvely).
  2003. * 'header' can be NULL, in which case false is returned. */
  2004. static int
  2005. header_has_option(const char *header, const char *option)
  2006. {
  2007. struct vec opt_vec;
  2008. struct vec eq_vec;
  2009. assert(option != NULL);
  2010. assert(option[0] != '\0');
  2011. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2012. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2013. return 1;
  2014. }
  2015. return 0;
  2016. }
  2017. /* Perform case-insensitive match of string against pattern */
  2018. static int
  2019. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2020. {
  2021. const char *or_str;
  2022. size_t i;
  2023. int j, len, res;
  2024. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2025. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2026. return (res > 0) ? res : match_prefix(or_str + 1,
  2027. (size_t)((pattern + pattern_len)
  2028. - (or_str + 1)),
  2029. str);
  2030. }
  2031. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2032. if (pattern[i] == '?' && str[j] != '\0') {
  2033. continue;
  2034. } else if (pattern[i] == '$') {
  2035. return (str[j] == '\0') ? j : -1;
  2036. } else if (pattern[i] == '*') {
  2037. i++;
  2038. if (pattern[i] == '*') {
  2039. i++;
  2040. len = (int)strlen(str + j);
  2041. } else {
  2042. len = (int)strcspn(str + j, "/");
  2043. }
  2044. if (i == pattern_len) {
  2045. return j + len;
  2046. }
  2047. do {
  2048. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2049. } while (res == -1 && len-- > 0);
  2050. return (res == -1) ? -1 : j + res + len;
  2051. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2052. return -1;
  2053. }
  2054. }
  2055. return j;
  2056. }
  2057. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2058. * This function must tolerate situations when connection info is not
  2059. * set up, for example if request parsing failed. */
  2060. static int
  2061. should_keep_alive(const struct mg_connection *conn)
  2062. {
  2063. if (conn != NULL) {
  2064. const char *http_version = conn->request_info.http_version;
  2065. const char *header = mg_get_header(conn, "Connection");
  2066. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2067. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2068. || (header != NULL && !header_has_option(header, "keep-alive"))
  2069. || (header == NULL && http_version
  2070. && 0 != strcmp(http_version, "1.1"))) {
  2071. return 0;
  2072. }
  2073. return 1;
  2074. }
  2075. return 0;
  2076. }
  2077. static int
  2078. should_decode_url(const struct mg_connection *conn)
  2079. {
  2080. if (!conn || !conn->ctx) {
  2081. return 0;
  2082. }
  2083. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2084. }
  2085. static const char *
  2086. suggest_connection_header(const struct mg_connection *conn)
  2087. {
  2088. return should_keep_alive(conn) ? "keep-alive" : "close";
  2089. }
  2090. static int
  2091. send_no_cache_header(struct mg_connection *conn)
  2092. {
  2093. /* Send all current and obsolete cache opt-out directives. */
  2094. return mg_printf(conn,
  2095. "Cache-Control: no-cache, no-store, "
  2096. "must-revalidate, private, max-age=0\r\n"
  2097. "Pragma: no-cache\r\n"
  2098. "Expires: 0\r\n");
  2099. }
  2100. static int
  2101. send_static_cache_header(struct mg_connection *conn)
  2102. {
  2103. #if !defined(NO_CACHING)
  2104. /* Read the server config to check how long a file may be cached.
  2105. * The configuration is in seconds. */
  2106. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2107. if (max_age <= 0) {
  2108. /* 0 means "do not cache". All values <0 are reserved
  2109. * and may be used differently in the future. */
  2110. /* If a file should not be cached, do not only send
  2111. * max-age=0, but also pragmas and Expires headers. */
  2112. return send_no_cache_header(conn);
  2113. }
  2114. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2115. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2116. /* See also https://www.mnot.net/cache_docs/ */
  2117. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2118. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2119. * year to 31622400 seconds. For the moment, we just send whatever has
  2120. * been configured, still the behavior for >1 year should be considered
  2121. * as undefined. */
  2122. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2123. #else /* NO_CACHING */
  2124. return send_no_cache_header(conn);
  2125. #endif /* !NO_CACHING */
  2126. }
  2127. static void handle_file_based_request(struct mg_connection *conn,
  2128. const char *path,
  2129. struct file *filep);
  2130. static int
  2131. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2132. const char *
  2133. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2134. {
  2135. /* See IANA HTTP status code assignment:
  2136. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2137. */
  2138. switch (response_code) {
  2139. /* RFC2616 Section 10.1 - Informational 1xx */
  2140. case 100:
  2141. return "Continue"; /* RFC2616 Section 10.1.1 */
  2142. case 101:
  2143. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2144. case 102:
  2145. return "Processing"; /* RFC2518 Section 10.1 */
  2146. /* RFC2616 Section 10.2 - Successful 2xx */
  2147. case 200:
  2148. return "OK"; /* RFC2616 Section 10.2.1 */
  2149. case 201:
  2150. return "Created"; /* RFC2616 Section 10.2.2 */
  2151. case 202:
  2152. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2153. case 203:
  2154. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2155. case 204:
  2156. return "No Content"; /* RFC2616 Section 10.2.5 */
  2157. case 205:
  2158. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2159. case 206:
  2160. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2161. case 207:
  2162. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2163. case 208:
  2164. return "Already Reported"; /* RFC5842 Section 7.1 */
  2165. case 226:
  2166. return "IM used"; /* RFC3229 Section 10.4.1 */
  2167. /* RFC2616 Section 10.3 - Redirection 3xx */
  2168. case 300:
  2169. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2170. case 301:
  2171. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2172. case 302:
  2173. return "Found"; /* RFC2616 Section 10.3.3 */
  2174. case 303:
  2175. return "See Other"; /* RFC2616 Section 10.3.4 */
  2176. case 304:
  2177. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2178. case 305:
  2179. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2180. case 307:
  2181. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2182. case 308:
  2183. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2184. /* RFC2616 Section 10.4 - Client Error 4xx */
  2185. case 400:
  2186. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2187. case 401:
  2188. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2189. case 402:
  2190. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2191. case 403:
  2192. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2193. case 404:
  2194. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2195. case 405:
  2196. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2197. case 406:
  2198. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2199. case 407:
  2200. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2201. case 408:
  2202. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2203. case 409:
  2204. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2205. case 410:
  2206. return "Gone"; /* RFC2616 Section 10.4.11 */
  2207. case 411:
  2208. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2209. case 412:
  2210. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2211. case 413:
  2212. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2213. case 414:
  2214. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2215. case 415:
  2216. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2217. case 416:
  2218. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2219. case 417:
  2220. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2221. case 421:
  2222. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2223. case 422:
  2224. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2225. * Section 11.2 */
  2226. case 423:
  2227. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2228. case 424:
  2229. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2230. * Section 11.4 */
  2231. case 426:
  2232. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2233. case 428:
  2234. return "Precondition Required"; /* RFC 6585, Section 3 */
  2235. case 429:
  2236. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2237. case 431:
  2238. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2239. case 451:
  2240. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2241. * Section 3 */
  2242. /* RFC2616 Section 10.5 - Server Error 5xx */
  2243. case 500:
  2244. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2245. case 501:
  2246. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2247. case 502:
  2248. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2249. case 503:
  2250. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2251. case 504:
  2252. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2253. case 505:
  2254. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2255. case 506:
  2256. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2257. case 507:
  2258. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2259. * Section 11.5 */
  2260. case 508:
  2261. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2262. case 510:
  2263. return "Not Extended"; /* RFC 2774, Section 7 */
  2264. case 511:
  2265. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2266. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2267. * E.g., "de facto" standards due to common use, ... */
  2268. case 418:
  2269. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2270. case 419:
  2271. return "Authentication Timeout"; /* common use */
  2272. case 420:
  2273. return "Enhance Your Calm"; /* common use */
  2274. case 440:
  2275. return "Login Timeout"; /* common use */
  2276. case 509:
  2277. return "Bandwidth Limit Exceeded"; /* common use */
  2278. default:
  2279. /* This error code is unknown. This should not happen. */
  2280. if (conn) {
  2281. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2282. }
  2283. /* Return at least a category according to RFC 2616 Section 10. */
  2284. if (response_code >= 100 && response_code < 200) {
  2285. /* Unknown informational status code */
  2286. return "Information";
  2287. }
  2288. if (response_code >= 200 && response_code < 300) {
  2289. /* Unknown success code */
  2290. return "Success";
  2291. }
  2292. if (response_code >= 300 && response_code < 400) {
  2293. /* Unknown redirection code */
  2294. return "Redirection";
  2295. }
  2296. if (response_code >= 400 && response_code < 500) {
  2297. /* Unknown request error code */
  2298. return "Client Error";
  2299. }
  2300. if (response_code >= 500 && response_code < 600) {
  2301. /* Unknown server error code */
  2302. return "Server Error";
  2303. }
  2304. /* Response code not even within reasonable range */
  2305. return "";
  2306. }
  2307. }
  2308. static void send_http_error(struct mg_connection *,
  2309. int,
  2310. PRINTF_FORMAT_STRING(const char *fmt),
  2311. ...) PRINTF_ARGS(3, 4);
  2312. static void
  2313. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2314. {
  2315. char buf[MG_BUF_LEN];
  2316. va_list ap;
  2317. int len, i, page_handler_found, scope, truncated;
  2318. char date[64];
  2319. time_t curtime = time(NULL);
  2320. const char *error_handler = NULL;
  2321. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2322. const char *error_page_file_ext, *tstr;
  2323. const char *status_text = mg_get_response_code_text(conn, status);
  2324. if (conn == NULL) {
  2325. return;
  2326. }
  2327. conn->status_code = status;
  2328. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2329. || conn->ctx->callbacks.http_error(conn, status)) {
  2330. if (!conn->in_error_handler) {
  2331. /* Send user defined error pages, if defined */
  2332. error_handler = conn->ctx->config[ERROR_PAGES];
  2333. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2334. page_handler_found = 0;
  2335. if (error_handler != NULL) {
  2336. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2337. switch (scope) {
  2338. case 1: /* Handler for specific error, e.g. 404 error */
  2339. mg_snprintf(conn,
  2340. &truncated,
  2341. buf,
  2342. sizeof(buf) - 32,
  2343. "%serror%03u.",
  2344. error_handler,
  2345. status);
  2346. break;
  2347. case 2: /* Handler for error group, e.g., 5xx error handler
  2348. * for all server errors (500-599) */
  2349. mg_snprintf(conn,
  2350. &truncated,
  2351. buf,
  2352. sizeof(buf) - 32,
  2353. "%serror%01uxx.",
  2354. error_handler,
  2355. status / 100);
  2356. break;
  2357. default: /* Handler for all errors */
  2358. mg_snprintf(conn,
  2359. &truncated,
  2360. buf,
  2361. sizeof(buf) - 32,
  2362. "%serror.",
  2363. error_handler);
  2364. break;
  2365. }
  2366. /* String truncation in buf may only occur if error_handler
  2367. * is too long. This string is from the config, not from a
  2368. * client. */
  2369. (void)truncated;
  2370. len = (int)strlen(buf);
  2371. tstr = strchr(error_page_file_ext, '.');
  2372. while (tstr) {
  2373. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2374. i++)
  2375. buf[len + i - 1] = tstr[i];
  2376. buf[len + i - 1] = 0;
  2377. if (mg_stat(conn, buf, &error_page_file)) {
  2378. page_handler_found = 1;
  2379. break;
  2380. }
  2381. tstr = strchr(tstr + i, '.');
  2382. }
  2383. }
  2384. }
  2385. if (page_handler_found) {
  2386. conn->in_error_handler = 1;
  2387. handle_file_based_request(conn, buf, &error_page_file);
  2388. conn->in_error_handler = 0;
  2389. return;
  2390. }
  2391. }
  2392. /* No custom error page. Send default error page. */
  2393. gmt_time_string(date, sizeof(date), &curtime);
  2394. conn->must_close = 1;
  2395. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2396. send_no_cache_header(conn);
  2397. mg_printf(conn,
  2398. "Date: %s\r\n"
  2399. "Connection: close\r\n\r\n",
  2400. date);
  2401. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2402. if (status > 199 && status != 204 && status != 304) {
  2403. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2404. if (fmt != NULL) {
  2405. va_start(ap, fmt);
  2406. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2407. va_end(ap);
  2408. mg_write(conn, buf, strlen(buf));
  2409. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2410. }
  2411. } else {
  2412. /* No body allowed. Close the connection. */
  2413. DEBUG_TRACE("Error %i", status);
  2414. }
  2415. }
  2416. }
  2417. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2418. /* Create substitutes for POSIX functions in Win32. */
  2419. #if defined(__MINGW32__)
  2420. /* Show no warning in case system functions are not used. */
  2421. #pragma GCC diagnostic push
  2422. #pragma GCC diagnostic ignored "-Wunused-function"
  2423. #endif
  2424. static int
  2425. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2426. {
  2427. (void)unused;
  2428. *mutex = CreateMutex(NULL, FALSE, NULL);
  2429. return (*mutex == NULL) ? -1 : 0;
  2430. }
  2431. static int
  2432. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2433. {
  2434. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2435. }
  2436. static int
  2437. pthread_mutex_lock(pthread_mutex_t *mutex)
  2438. {
  2439. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2440. }
  2441. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2442. static int
  2443. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2444. {
  2445. switch (WaitForSingleObject(*mutex, 0)) {
  2446. case WAIT_OBJECT_0:
  2447. return 0;
  2448. case WAIT_TIMEOUT:
  2449. return -2; /* EBUSY */
  2450. }
  2451. return -1;
  2452. }
  2453. #endif
  2454. static int
  2455. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2456. {
  2457. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2458. }
  2459. #ifndef WIN_PTHREADS_TIME_H
  2460. static int
  2461. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2462. {
  2463. FILETIME ft;
  2464. ULARGE_INTEGER li;
  2465. BOOL ok = FALSE;
  2466. double d;
  2467. static double perfcnt_per_sec = 0.0;
  2468. if (tp) {
  2469. memset(tp, 0, sizeof(*tp));
  2470. if (clk_id == CLOCK_REALTIME) {
  2471. GetSystemTimeAsFileTime(&ft);
  2472. li.LowPart = ft.dwLowDateTime;
  2473. li.HighPart = ft.dwHighDateTime;
  2474. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2475. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2476. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2477. ok = TRUE;
  2478. } else if (clk_id == CLOCK_MONOTONIC) {
  2479. if (perfcnt_per_sec == 0.0) {
  2480. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2481. perfcnt_per_sec = 1.0 / li.QuadPart;
  2482. }
  2483. if (perfcnt_per_sec != 0.0) {
  2484. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2485. d = li.QuadPart * perfcnt_per_sec;
  2486. tp->tv_sec = (time_t)d;
  2487. d -= tp->tv_sec;
  2488. tp->tv_nsec = (long)(d * 1.0E9);
  2489. ok = TRUE;
  2490. }
  2491. }
  2492. }
  2493. return ok ? 0 : -1;
  2494. }
  2495. #endif
  2496. static int
  2497. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2498. {
  2499. (void)unused;
  2500. InitializeCriticalSection(&cv->threadIdSec);
  2501. cv->waiting_thread = NULL;
  2502. return 0;
  2503. }
  2504. static int
  2505. pthread_cond_timedwait(pthread_cond_t *cv,
  2506. pthread_mutex_t *mutex,
  2507. const struct timespec *abstime)
  2508. {
  2509. struct mg_workerTLS **ptls,
  2510. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2511. int ok;
  2512. struct timespec tsnow;
  2513. int64_t nsnow, nswaitabs, nswaitrel;
  2514. DWORD mswaitrel;
  2515. EnterCriticalSection(&cv->threadIdSec);
  2516. /* Add this thread to cv's waiting list */
  2517. ptls = &cv->waiting_thread;
  2518. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2519. ;
  2520. tls->next_waiting_thread = NULL;
  2521. *ptls = tls;
  2522. LeaveCriticalSection(&cv->threadIdSec);
  2523. if (abstime) {
  2524. clock_gettime(CLOCK_REALTIME, &tsnow);
  2525. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2526. nswaitabs =
  2527. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2528. nswaitrel = nswaitabs - nsnow;
  2529. if (nswaitrel < 0) {
  2530. nswaitrel = 0;
  2531. }
  2532. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2533. } else {
  2534. mswaitrel = INFINITE;
  2535. }
  2536. pthread_mutex_unlock(mutex);
  2537. ok = (WAIT_OBJECT_0
  2538. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2539. if (!ok) {
  2540. ok = 1;
  2541. EnterCriticalSection(&cv->threadIdSec);
  2542. ptls = &cv->waiting_thread;
  2543. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2544. if (*ptls == tls) {
  2545. *ptls = tls->next_waiting_thread;
  2546. ok = 0;
  2547. break;
  2548. }
  2549. }
  2550. LeaveCriticalSection(&cv->threadIdSec);
  2551. if (ok) {
  2552. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2553. }
  2554. }
  2555. /* This thread has been removed from cv's waiting list */
  2556. pthread_mutex_lock(mutex);
  2557. return ok ? 0 : -1;
  2558. }
  2559. static int
  2560. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2561. {
  2562. return pthread_cond_timedwait(cv, mutex, NULL);
  2563. }
  2564. static int
  2565. pthread_cond_signal(pthread_cond_t *cv)
  2566. {
  2567. HANDLE wkup = NULL;
  2568. BOOL ok = FALSE;
  2569. EnterCriticalSection(&cv->threadIdSec);
  2570. if (cv->waiting_thread) {
  2571. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2572. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2573. ok = SetEvent(wkup);
  2574. assert(ok);
  2575. }
  2576. LeaveCriticalSection(&cv->threadIdSec);
  2577. return ok ? 0 : 1;
  2578. }
  2579. static int
  2580. pthread_cond_broadcast(pthread_cond_t *cv)
  2581. {
  2582. EnterCriticalSection(&cv->threadIdSec);
  2583. while (cv->waiting_thread) {
  2584. pthread_cond_signal(cv);
  2585. }
  2586. LeaveCriticalSection(&cv->threadIdSec);
  2587. return 0;
  2588. }
  2589. static int
  2590. pthread_cond_destroy(pthread_cond_t *cv)
  2591. {
  2592. EnterCriticalSection(&cv->threadIdSec);
  2593. assert(cv->waiting_thread == NULL);
  2594. LeaveCriticalSection(&cv->threadIdSec);
  2595. DeleteCriticalSection(&cv->threadIdSec);
  2596. return 0;
  2597. }
  2598. static int
  2599. event_create(void)
  2600. {
  2601. return (int)CreateEvent(NULL, FALSE, FALSE, NULL);
  2602. }
  2603. static int
  2604. event_wait(int eventhdl)
  2605. {
  2606. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2607. return (res == WAIT_OBJECT_0);
  2608. }
  2609. static int
  2610. event_signal(int eventhdl, unsigned timeout)
  2611. {
  2612. return (int)SetEvent((HANDLE)eventhdl);
  2613. }
  2614. static void
  2615. event_destroy(int eventhdl)
  2616. {
  2617. CloseHandle((HANDLE)eventhdl);
  2618. }
  2619. #if defined(__MINGW32__)
  2620. /* Enable unused function warning again */
  2621. #pragma GCC diagnostic pop
  2622. #endif
  2623. /* For Windows, change all slashes to backslashes in path names. */
  2624. static void
  2625. change_slashes_to_backslashes(char *path)
  2626. {
  2627. int i;
  2628. for (i = 0; path[i] != '\0'; i++) {
  2629. if (path[i] == '/') {
  2630. path[i] = '\\';
  2631. }
  2632. /* remove double backslash (check i > 0 to preserve UNC paths,
  2633. * like \\server\file.txt) */
  2634. if ((path[i] == '\\') && (i > 0)) {
  2635. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2636. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2637. }
  2638. }
  2639. }
  2640. }
  2641. static int
  2642. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2643. {
  2644. int diff;
  2645. do {
  2646. diff = tolower(*s1) - tolower(*s2);
  2647. s1++;
  2648. s2++;
  2649. } while (diff == 0 && s1[-1] != '\0');
  2650. return diff;
  2651. }
  2652. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2653. * wbuf and wbuf_len is a target buffer and its length. */
  2654. static void
  2655. path_to_unicode(const struct mg_connection *conn,
  2656. const char *path,
  2657. wchar_t *wbuf,
  2658. size_t wbuf_len)
  2659. {
  2660. char buf[PATH_MAX], buf2[PATH_MAX];
  2661. wchar_t wbuf2[MAX_PATH + 1];
  2662. DWORD long_len, err;
  2663. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2664. mg_strlcpy(buf, path, sizeof(buf));
  2665. change_slashes_to_backslashes(buf);
  2666. /* Convert to Unicode and back. If doubly-converted string does not
  2667. * match the original, something is fishy, reject. */
  2668. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2669. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2670. WideCharToMultiByte(
  2671. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2672. if (strcmp(buf, buf2) != 0) {
  2673. wbuf[0] = L'\0';
  2674. }
  2675. /* TODO: Add a configuration to switch between case sensitive and
  2676. * case insensitive URIs for Windows server. */
  2677. /*
  2678. if (conn) {
  2679. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2680. fcompare = wcscmp;
  2681. }
  2682. }
  2683. */
  2684. (void)conn; /* conn is currently unused */
  2685. #if !defined(_WIN32_WCE)
  2686. /* Only accept a full file path, not a Windows short (8.3) path. */
  2687. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2688. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2689. if (long_len == 0) {
  2690. err = GetLastError();
  2691. if (err == ERROR_FILE_NOT_FOUND) {
  2692. /* File does not exist. This is not always a problem here. */
  2693. return;
  2694. }
  2695. }
  2696. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2697. /* Short name is used. */
  2698. wbuf[0] = L'\0';
  2699. }
  2700. #else
  2701. (void)long_len;
  2702. (void)wbuf2;
  2703. (void)err;
  2704. if (strchr(path, '~')) {
  2705. wbuf[0] = L'\0';
  2706. }
  2707. #endif
  2708. }
  2709. /* Windows happily opens files with some garbage at the end of file name.
  2710. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2711. * "a.cgi", despite one would expect an error back.
  2712. * This function returns non-0 if path ends with some garbage. */
  2713. static int
  2714. path_cannot_disclose_cgi(const char *path)
  2715. {
  2716. static const char *allowed_last_characters = "_-";
  2717. int last = path[strlen(path) - 1];
  2718. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2719. }
  2720. static int
  2721. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2722. {
  2723. wchar_t wbuf[PATH_MAX];
  2724. WIN32_FILE_ATTRIBUTE_DATA info;
  2725. time_t creation_time;
  2726. if (!filep) {
  2727. return 0;
  2728. }
  2729. memset(filep, 0, sizeof(*filep));
  2730. if (conn && is_file_in_memory(conn, path, filep)) {
  2731. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2732. * memset */
  2733. filep->last_modified = time(NULL);
  2734. /* last_modified = now ... assumes the file may change during runtime,
  2735. * so every mg_fopen call may return different data */
  2736. /* last_modified = conn->ctx.start_time;
  2737. * May be used it the data does not change during runtime. This allows
  2738. * browser caching. Since we do not know, we have to assume the file
  2739. * in memory may change. */
  2740. return 1;
  2741. }
  2742. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2743. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2744. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2745. filep->last_modified =
  2746. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2747. info.ftLastWriteTime.dwHighDateTime);
  2748. /* On Windows, the file creation time can be higher than the
  2749. * modification time, e.g. when a file is copied.
  2750. * Since the Last-Modified timestamp is used for caching
  2751. * it should be based on the most recent timestamp. */
  2752. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2753. info.ftCreationTime.dwHighDateTime);
  2754. if (creation_time > filep->last_modified) {
  2755. filep->last_modified = creation_time;
  2756. }
  2757. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2758. /* If file name is fishy, reset the file structure and return
  2759. * error.
  2760. * Note it is important to reset, not just return the error, cause
  2761. * functions like is_file_opened() check the struct. */
  2762. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2763. memset(filep, 0, sizeof(*filep));
  2764. return 0;
  2765. }
  2766. return 1;
  2767. }
  2768. return 0;
  2769. }
  2770. static int
  2771. mg_remove(const struct mg_connection *conn, const char *path)
  2772. {
  2773. wchar_t wbuf[PATH_MAX];
  2774. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2775. return DeleteFileW(wbuf) ? 0 : -1;
  2776. }
  2777. static int
  2778. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2779. {
  2780. wchar_t wbuf[PATH_MAX];
  2781. (void)mode;
  2782. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2783. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2784. }
  2785. /* Create substitutes for POSIX functions in Win32. */
  2786. #if defined(__MINGW32__)
  2787. /* Show no warning in case system functions are not used. */
  2788. #pragma GCC diagnostic push
  2789. #pragma GCC diagnostic ignored "-Wunused-function"
  2790. #endif
  2791. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2792. static DIR *
  2793. mg_opendir(const struct mg_connection *conn, const char *name)
  2794. {
  2795. DIR *dir = NULL;
  2796. wchar_t wpath[PATH_MAX];
  2797. DWORD attrs;
  2798. if (name == NULL) {
  2799. SetLastError(ERROR_BAD_ARGUMENTS);
  2800. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2801. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2802. } else {
  2803. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2804. attrs = GetFileAttributesW(wpath);
  2805. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2806. == FILE_ATTRIBUTE_DIRECTORY)) {
  2807. (void)wcscat(wpath, L"\\*");
  2808. dir->handle = FindFirstFileW(wpath, &dir->info);
  2809. dir->result.d_name[0] = '\0';
  2810. } else {
  2811. mg_free(dir);
  2812. dir = NULL;
  2813. }
  2814. }
  2815. return dir;
  2816. }
  2817. static int
  2818. mg_closedir(DIR *dir)
  2819. {
  2820. int result = 0;
  2821. if (dir != NULL) {
  2822. if (dir->handle != INVALID_HANDLE_VALUE)
  2823. result = FindClose(dir->handle) ? 0 : -1;
  2824. mg_free(dir);
  2825. } else {
  2826. result = -1;
  2827. SetLastError(ERROR_BAD_ARGUMENTS);
  2828. }
  2829. return result;
  2830. }
  2831. static struct dirent *
  2832. mg_readdir(DIR *dir)
  2833. {
  2834. struct dirent *result = 0;
  2835. if (dir) {
  2836. if (dir->handle != INVALID_HANDLE_VALUE) {
  2837. result = &dir->result;
  2838. (void)WideCharToMultiByte(CP_UTF8,
  2839. 0,
  2840. dir->info.cFileName,
  2841. -1,
  2842. result->d_name,
  2843. sizeof(result->d_name),
  2844. NULL,
  2845. NULL);
  2846. if (!FindNextFileW(dir->handle, &dir->info)) {
  2847. (void)FindClose(dir->handle);
  2848. dir->handle = INVALID_HANDLE_VALUE;
  2849. }
  2850. } else {
  2851. SetLastError(ERROR_FILE_NOT_FOUND);
  2852. }
  2853. } else {
  2854. SetLastError(ERROR_BAD_ARGUMENTS);
  2855. }
  2856. return result;
  2857. }
  2858. #ifndef HAVE_POLL
  2859. static int
  2860. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2861. {
  2862. struct timeval tv;
  2863. fd_set set;
  2864. unsigned int i;
  2865. int result;
  2866. SOCKET maxfd = 0;
  2867. memset(&tv, 0, sizeof(tv));
  2868. tv.tv_sec = milliseconds / 1000;
  2869. tv.tv_usec = (milliseconds % 1000) * 1000;
  2870. FD_ZERO(&set);
  2871. for (i = 0; i < n; i++) {
  2872. FD_SET((SOCKET)pfd[i].fd, &set);
  2873. pfd[i].revents = 0;
  2874. if (pfd[i].fd > maxfd) {
  2875. maxfd = pfd[i].fd;
  2876. }
  2877. }
  2878. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2879. for (i = 0; i < n; i++) {
  2880. if (FD_ISSET(pfd[i].fd, &set)) {
  2881. pfd[i].revents = POLLIN;
  2882. }
  2883. }
  2884. }
  2885. return result;
  2886. }
  2887. #endif /* HAVE_POLL */
  2888. #if defined(__MINGW32__)
  2889. /* Enable unused function warning again */
  2890. #pragma GCC diagnostic pop
  2891. #endif
  2892. static void
  2893. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2894. {
  2895. (void)conn; /* Unused. */
  2896. #if defined(_WIN32_WCE)
  2897. (void)sock;
  2898. #else
  2899. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2900. #endif
  2901. }
  2902. int
  2903. mg_start_thread(mg_thread_func_t f, void *p)
  2904. {
  2905. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2906. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2907. */
  2908. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2909. == ((uintptr_t)(-1L)))
  2910. ? -1
  2911. : 0);
  2912. #else
  2913. return (
  2914. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2915. ? -1
  2916. : 0);
  2917. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2918. }
  2919. /* Start a thread storing the thread context. */
  2920. static int
  2921. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2922. void *p,
  2923. pthread_t *threadidptr)
  2924. {
  2925. uintptr_t uip;
  2926. HANDLE threadhandle;
  2927. int result = -1;
  2928. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2929. threadhandle = (HANDLE)uip;
  2930. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2931. *threadidptr = threadhandle;
  2932. result = 0;
  2933. }
  2934. return result;
  2935. }
  2936. /* Wait for a thread to finish. */
  2937. static int
  2938. mg_join_thread(pthread_t threadid)
  2939. {
  2940. int result;
  2941. DWORD dwevent;
  2942. result = -1;
  2943. dwevent = WaitForSingleObject(threadid, INFINITE);
  2944. if (dwevent == WAIT_FAILED) {
  2945. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2946. } else {
  2947. if (dwevent == WAIT_OBJECT_0) {
  2948. CloseHandle(threadid);
  2949. result = 0;
  2950. }
  2951. }
  2952. return result;
  2953. }
  2954. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  2955. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  2956. /* Create substitutes for POSIX functions in Win32. */
  2957. #if defined(__MINGW32__)
  2958. /* Show no warning in case system functions are not used. */
  2959. #pragma GCC diagnostic push
  2960. #pragma GCC diagnostic ignored "-Wunused-function"
  2961. #endif
  2962. static HANDLE
  2963. dlopen(const char *dll_name, int flags)
  2964. {
  2965. wchar_t wbuf[PATH_MAX];
  2966. (void)flags;
  2967. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2968. return LoadLibraryW(wbuf);
  2969. }
  2970. static int
  2971. dlclose(void *handle)
  2972. {
  2973. int result;
  2974. if (FreeLibrary((HMODULE)handle) != 0) {
  2975. result = 0;
  2976. } else {
  2977. result = -1;
  2978. }
  2979. return result;
  2980. }
  2981. #if defined(__MINGW32__)
  2982. /* Enable unused function warning again */
  2983. #pragma GCC diagnostic pop
  2984. #endif
  2985. #endif
  2986. #if !defined(NO_CGI)
  2987. #define SIGKILL (0)
  2988. static int
  2989. kill(pid_t pid, int sig_num)
  2990. {
  2991. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2992. (void)CloseHandle((HANDLE)pid);
  2993. return 0;
  2994. }
  2995. static void
  2996. trim_trailing_whitespaces(char *s)
  2997. {
  2998. char *e = s + strlen(s) - 1;
  2999. while (e > s && isspace(*(unsigned char *)e)) {
  3000. *e-- = '\0';
  3001. }
  3002. }
  3003. static pid_t
  3004. spawn_process(struct mg_connection *conn,
  3005. const char *prog,
  3006. char *envblk,
  3007. char *envp[],
  3008. int fdin[2],
  3009. int fdout[2],
  3010. int fderr[2],
  3011. const char *dir)
  3012. {
  3013. HANDLE me;
  3014. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3015. cmdline[PATH_MAX], buf[PATH_MAX];
  3016. int truncated;
  3017. struct file file = STRUCT_FILE_INITIALIZER;
  3018. STARTUPINFOA si;
  3019. PROCESS_INFORMATION pi = {0};
  3020. (void)envp;
  3021. memset(&si, 0, sizeof(si));
  3022. si.cb = sizeof(si);
  3023. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3024. si.wShowWindow = SW_HIDE;
  3025. me = GetCurrentProcess();
  3026. DuplicateHandle(me,
  3027. (HANDLE)_get_osfhandle(fdin[0]),
  3028. me,
  3029. &si.hStdInput,
  3030. 0,
  3031. TRUE,
  3032. DUPLICATE_SAME_ACCESS);
  3033. DuplicateHandle(me,
  3034. (HANDLE)_get_osfhandle(fdout[1]),
  3035. me,
  3036. &si.hStdOutput,
  3037. 0,
  3038. TRUE,
  3039. DUPLICATE_SAME_ACCESS);
  3040. DuplicateHandle(me,
  3041. (HANDLE)_get_osfhandle(fderr[1]),
  3042. me,
  3043. &si.hStdError,
  3044. 0,
  3045. TRUE,
  3046. DUPLICATE_SAME_ACCESS);
  3047. /* Mark handles that should not be inherited. See
  3048. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3049. */
  3050. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3051. HANDLE_FLAG_INHERIT,
  3052. 0);
  3053. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3054. HANDLE_FLAG_INHERIT,
  3055. 0);
  3056. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3057. HANDLE_FLAG_INHERIT,
  3058. 0);
  3059. /* If CGI file is a script, try to read the interpreter line */
  3060. interp = conn->ctx->config[CGI_INTERPRETER];
  3061. if (interp == NULL) {
  3062. buf[0] = buf[1] = '\0';
  3063. /* Read the first line of the script into the buffer */
  3064. mg_snprintf(
  3065. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3066. if (truncated) {
  3067. pi.hProcess = (pid_t)-1;
  3068. goto spawn_cleanup;
  3069. }
  3070. if (mg_fopen(conn, cmdline, "r", &file)) {
  3071. p = (char *)file.membuf;
  3072. mg_fgets(buf, sizeof(buf), &file, &p);
  3073. mg_fclose(&file);
  3074. buf[sizeof(buf) - 1] = '\0';
  3075. }
  3076. if (buf[0] == '#' && buf[1] == '!') {
  3077. trim_trailing_whitespaces(buf + 2);
  3078. } else {
  3079. buf[2] = '\0';
  3080. }
  3081. interp = buf + 2;
  3082. }
  3083. if (interp[0] != '\0') {
  3084. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3085. interp = full_interp;
  3086. }
  3087. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3088. if (interp[0] != '\0') {
  3089. mg_snprintf(conn,
  3090. &truncated,
  3091. cmdline,
  3092. sizeof(cmdline),
  3093. "\"%s\" \"%s\\%s\"",
  3094. interp,
  3095. full_dir,
  3096. prog);
  3097. } else {
  3098. mg_snprintf(conn,
  3099. &truncated,
  3100. cmdline,
  3101. sizeof(cmdline),
  3102. "\"%s\\%s\"",
  3103. full_dir,
  3104. prog);
  3105. }
  3106. if (truncated) {
  3107. pi.hProcess = (pid_t)-1;
  3108. goto spawn_cleanup;
  3109. }
  3110. DEBUG_TRACE("Running [%s]", cmdline);
  3111. if (CreateProcessA(NULL,
  3112. cmdline,
  3113. NULL,
  3114. NULL,
  3115. TRUE,
  3116. CREATE_NEW_PROCESS_GROUP,
  3117. envblk,
  3118. NULL,
  3119. &si,
  3120. &pi) == 0) {
  3121. mg_cry(
  3122. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3123. pi.hProcess = (pid_t)-1;
  3124. /* goto spawn_cleanup; */
  3125. }
  3126. spawn_cleanup:
  3127. (void)CloseHandle(si.hStdOutput);
  3128. (void)CloseHandle(si.hStdError);
  3129. (void)CloseHandle(si.hStdInput);
  3130. if (pi.hThread != NULL) {
  3131. (void)CloseHandle(pi.hThread);
  3132. }
  3133. return (pid_t)pi.hProcess;
  3134. }
  3135. #endif /* !NO_CGI */
  3136. static int
  3137. set_non_blocking_mode(SOCKET sock)
  3138. {
  3139. unsigned long on = 1;
  3140. return ioctlsocket(sock, (long)FIONBIO, &on);
  3141. }
  3142. #else
  3143. static int
  3144. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3145. {
  3146. struct stat st;
  3147. if (!filep) {
  3148. return 0;
  3149. }
  3150. memset(filep, 0, sizeof(*filep));
  3151. if (conn && is_file_in_memory(conn, path, filep)) {
  3152. return 1;
  3153. }
  3154. if (0 == stat(path, &st)) {
  3155. filep->size = (uint64_t)(st.st_size);
  3156. filep->last_modified = st.st_mtime;
  3157. filep->is_directory = S_ISDIR(st.st_mode);
  3158. return 1;
  3159. }
  3160. return 0;
  3161. }
  3162. static void
  3163. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3164. {
  3165. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3166. if (conn) {
  3167. mg_cry(conn,
  3168. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3169. __func__,
  3170. strerror(ERRNO));
  3171. }
  3172. }
  3173. }
  3174. int
  3175. mg_start_thread(mg_thread_func_t func, void *param)
  3176. {
  3177. pthread_t thread_id;
  3178. pthread_attr_t attr;
  3179. int result;
  3180. (void)pthread_attr_init(&attr);
  3181. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3182. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3183. /* Compile-time option to control stack size,
  3184. * e.g. -DUSE_STACK_SIZE=16384 */
  3185. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3186. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3187. result = pthread_create(&thread_id, &attr, func, param);
  3188. pthread_attr_destroy(&attr);
  3189. return result;
  3190. }
  3191. /* Start a thread storing the thread context. */
  3192. static int
  3193. mg_start_thread_with_id(mg_thread_func_t func,
  3194. void *param,
  3195. pthread_t *threadidptr)
  3196. {
  3197. pthread_t thread_id;
  3198. pthread_attr_t attr;
  3199. int result;
  3200. (void)pthread_attr_init(&attr);
  3201. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3202. /* Compile-time option to control stack size,
  3203. * e.g. -DUSE_STACK_SIZE=16384 */
  3204. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3205. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3206. result = pthread_create(&thread_id, &attr, func, param);
  3207. pthread_attr_destroy(&attr);
  3208. if ((result == 0) && (threadidptr != NULL)) {
  3209. *threadidptr = thread_id;
  3210. }
  3211. return result;
  3212. }
  3213. /* Wait for a thread to finish. */
  3214. static int
  3215. mg_join_thread(pthread_t threadid)
  3216. {
  3217. int result;
  3218. result = pthread_join(threadid, NULL);
  3219. return result;
  3220. }
  3221. #ifndef NO_CGI
  3222. static pid_t
  3223. spawn_process(struct mg_connection *conn,
  3224. const char *prog,
  3225. char *envblk,
  3226. char *envp[],
  3227. int fdin[2],
  3228. int fdout[2],
  3229. int fderr[2],
  3230. const char *dir)
  3231. {
  3232. pid_t pid;
  3233. const char *interp;
  3234. (void)envblk;
  3235. if (conn == NULL) {
  3236. return 0;
  3237. }
  3238. if ((pid = fork()) == -1) {
  3239. /* Parent */
  3240. send_http_error(conn,
  3241. 500,
  3242. "Error: Creating CGI process\nfork(): %s",
  3243. strerror(ERRNO));
  3244. } else if (pid == 0) {
  3245. /* Child */
  3246. if (chdir(dir) != 0) {
  3247. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3248. } else if (dup2(fdin[0], 0) == -1) {
  3249. mg_cry(conn,
  3250. "%s: dup2(%d, 0): %s",
  3251. __func__,
  3252. fdin[0],
  3253. strerror(ERRNO));
  3254. } else if (dup2(fdout[1], 1) == -1) {
  3255. mg_cry(conn,
  3256. "%s: dup2(%d, 1): %s",
  3257. __func__,
  3258. fdout[1],
  3259. strerror(ERRNO));
  3260. } else if (dup2(fderr[1], 2) == -1) {
  3261. mg_cry(conn,
  3262. "%s: dup2(%d, 2): %s",
  3263. __func__,
  3264. fderr[1],
  3265. strerror(ERRNO));
  3266. } else {
  3267. /* Keep stderr and stdout in two different pipes.
  3268. * Stdout will be sent back to the client,
  3269. * stderr should go into a server error log. */
  3270. (void)close(fdin[0]);
  3271. (void)close(fdout[1]);
  3272. (void)close(fderr[1]);
  3273. /* Close write end fdin and read end fdout and fderr */
  3274. (void)close(fdin[1]);
  3275. (void)close(fdout[0]);
  3276. (void)close(fderr[0]);
  3277. /* After exec, all signal handlers are restored to their default
  3278. * values, with one exception of SIGCHLD. According to
  3279. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3280. * leave unchanged after exec if it was set to be ignored. Restore
  3281. * it to default action. */
  3282. signal(SIGCHLD, SIG_DFL);
  3283. interp = conn->ctx->config[CGI_INTERPRETER];
  3284. if (interp == NULL) {
  3285. (void)execle(prog, prog, NULL, envp);
  3286. mg_cry(conn,
  3287. "%s: execle(%s): %s",
  3288. __func__,
  3289. prog,
  3290. strerror(ERRNO));
  3291. } else {
  3292. (void)execle(interp, interp, prog, NULL, envp);
  3293. mg_cry(conn,
  3294. "%s: execle(%s %s): %s",
  3295. __func__,
  3296. interp,
  3297. prog,
  3298. strerror(ERRNO));
  3299. }
  3300. }
  3301. exit(EXIT_FAILURE);
  3302. }
  3303. return pid;
  3304. }
  3305. #endif /* !NO_CGI */
  3306. static int
  3307. set_non_blocking_mode(SOCKET sock)
  3308. {
  3309. int flags;
  3310. flags = fcntl(sock, F_GETFL, 0);
  3311. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3312. return 0;
  3313. }
  3314. #endif /* _WIN32 */
  3315. /* End of initial operating system specific define block. */
  3316. /* Get a random number (independent of C rand function) */
  3317. static uint64_t
  3318. get_random(void)
  3319. {
  3320. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3321. static uint64_t lcg = 0; /* Linear congruential generator */
  3322. struct timespec now;
  3323. memset(&now, 0, sizeof(now));
  3324. clock_gettime(CLOCK_MONOTONIC, &now);
  3325. if (lfsr == 0) {
  3326. /* lfsr will be only 0 if has not been initialized,
  3327. * so this code is called only once. */
  3328. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3329. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3330. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3331. + (uint64_t)(ptrdiff_t)&now;
  3332. } else {
  3333. /* Get the next step of both random number generators. */
  3334. lfsr = (lfsr >> 1)
  3335. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3336. << 63);
  3337. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3338. }
  3339. /* Combining two pseudo-random number generators and a high resolution part
  3340. * of the current server time will make it hard (impossible?) to guess the
  3341. * next number. */
  3342. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3343. }
  3344. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3345. * descriptor. Return number of bytes written. */
  3346. static int
  3347. push(struct mg_context *ctx,
  3348. FILE *fp,
  3349. SOCKET sock,
  3350. SSL *ssl,
  3351. const char *buf,
  3352. int len,
  3353. double timeout)
  3354. {
  3355. struct timespec start, now;
  3356. int n, err;
  3357. #ifdef _WIN32
  3358. typedef int len_t;
  3359. #else
  3360. typedef size_t len_t;
  3361. #endif
  3362. if (timeout > 0) {
  3363. memset(&start, 0, sizeof(start));
  3364. memset(&now, 0, sizeof(now));
  3365. clock_gettime(CLOCK_MONOTONIC, &start);
  3366. }
  3367. if (ctx == NULL) {
  3368. return -1;
  3369. }
  3370. #ifdef NO_SSL
  3371. if (ssl) {
  3372. return -1;
  3373. }
  3374. #endif
  3375. do {
  3376. #ifndef NO_SSL
  3377. if (ssl != NULL) {
  3378. n = SSL_write(ssl, buf, len);
  3379. if (n <= 0) {
  3380. err = SSL_get_error(ssl, n);
  3381. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3382. err = ERRNO;
  3383. } else if ((err == SSL_ERROR_WANT_READ)
  3384. || (err == SSL_ERROR_WANT_WRITE)) {
  3385. n = 0;
  3386. } else {
  3387. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3388. return -1;
  3389. }
  3390. } else {
  3391. err = 0;
  3392. }
  3393. } else
  3394. #endif
  3395. if (fp != NULL) {
  3396. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3397. if (ferror(fp)) {
  3398. n = -1;
  3399. err = ERRNO;
  3400. } else {
  3401. err = 0;
  3402. }
  3403. } else {
  3404. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3405. err = (n < 0) ? ERRNO : 0;
  3406. if (n == 0) {
  3407. /* shutdown of the socket at client side */
  3408. return -1;
  3409. }
  3410. }
  3411. if (ctx->stop_flag) {
  3412. return -1;
  3413. }
  3414. if ((n > 0) || (n == 0 && len == 0)) {
  3415. /* some data has been read, or no data was requested */
  3416. return n;
  3417. }
  3418. if (n < 0) {
  3419. /* socket error - check errno */
  3420. DEBUG_TRACE("send() failed, error %d", err);
  3421. /* TODO: error handling depending on the error code.
  3422. * These codes are different between Windows and Linux.
  3423. */
  3424. return -1;
  3425. }
  3426. /* This code is not reached in the moment.
  3427. * ==> Fix the TODOs above first. */
  3428. if (timeout > 0) {
  3429. clock_gettime(CLOCK_MONOTONIC, &now);
  3430. }
  3431. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3432. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3433. used */
  3434. return -1;
  3435. }
  3436. static int64_t
  3437. push_all(struct mg_context *ctx,
  3438. FILE *fp,
  3439. SOCKET sock,
  3440. SSL *ssl,
  3441. const char *buf,
  3442. int64_t len)
  3443. {
  3444. double timeout = -1.0;
  3445. int64_t n, nwritten = 0;
  3446. if (ctx == NULL) {
  3447. return -1;
  3448. }
  3449. if (ctx->config[REQUEST_TIMEOUT]) {
  3450. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3451. }
  3452. while (len > 0 && ctx->stop_flag == 0) {
  3453. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3454. if (n < 0) {
  3455. if (nwritten == 0) {
  3456. nwritten = n; /* Propagate the error */
  3457. }
  3458. break;
  3459. } else if (n == 0) {
  3460. break; /* No more data to write */
  3461. } else {
  3462. nwritten += n;
  3463. len -= n;
  3464. }
  3465. }
  3466. return nwritten;
  3467. }
  3468. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3469. * Return negative value on error, or number of bytes read on success. */
  3470. static int
  3471. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3472. {
  3473. int nread, err;
  3474. struct timespec start, now;
  3475. #ifdef _WIN32
  3476. typedef int len_t;
  3477. #else
  3478. typedef size_t len_t;
  3479. #endif
  3480. if (timeout > 0) {
  3481. memset(&start, 0, sizeof(start));
  3482. memset(&now, 0, sizeof(now));
  3483. clock_gettime(CLOCK_MONOTONIC, &start);
  3484. }
  3485. do {
  3486. if (fp != NULL) {
  3487. #if !defined(_WIN32_WCE)
  3488. /* Use read() instead of fread(), because if we're reading from the
  3489. * CGI pipe, fread() may block until IO buffer is filled up. We
  3490. * cannot afford to block and must pass all read bytes immediately
  3491. * to the client. */
  3492. nread = (int)read(fileno(fp), buf, (size_t)len);
  3493. #else
  3494. /* WinCE does not support CGI pipes */
  3495. nread = (int)fread(buf, 1, (size_t)len, fp);
  3496. #endif
  3497. err = (nread < 0) ? ERRNO : 0;
  3498. #ifndef NO_SSL
  3499. } else if (conn->ssl != NULL) {
  3500. nread = SSL_read(conn->ssl, buf, len);
  3501. if (nread <= 0) {
  3502. err = SSL_get_error(conn->ssl, nread);
  3503. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3504. err = ERRNO;
  3505. } else if ((err == SSL_ERROR_WANT_READ)
  3506. || (err == SSL_ERROR_WANT_WRITE)) {
  3507. nread = 0;
  3508. } else {
  3509. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3510. return -1;
  3511. }
  3512. } else {
  3513. err = 0;
  3514. }
  3515. #endif
  3516. } else {
  3517. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3518. err = (nread < 0) ? ERRNO : 0;
  3519. if (nread == 0) {
  3520. /* shutdown of the socket at client side */
  3521. return -1;
  3522. }
  3523. }
  3524. if (conn->ctx->stop_flag) {
  3525. return -1;
  3526. }
  3527. if ((nread > 0) || (nread == 0 && len == 0)) {
  3528. /* some data has been read, or no data was requested */
  3529. return nread;
  3530. }
  3531. if (nread < 0) {
  3532. /* socket error - check errno */
  3533. #ifdef _WIN32
  3534. if (err == WSAEWOULDBLOCK) {
  3535. /* standard case if called from close_socket_gracefully */
  3536. return -1;
  3537. } else if (err == WSAETIMEDOUT) {
  3538. /* timeout is handled by the while loop */
  3539. } else {
  3540. DEBUG_TRACE("recv() failed, error %d", err);
  3541. return -1;
  3542. }
  3543. #else
  3544. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3545. * if the timeout is reached and if the socket was set to non-
  3546. * blocking in close_socket_gracefully, so we can not distinguish
  3547. * here. We have to wait for the timeout in both cases for now.
  3548. */
  3549. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3550. /* EAGAIN/EWOULDBLOCK:
  3551. * standard case if called from close_socket_gracefully
  3552. * => should return -1 */
  3553. /* or timeout occured
  3554. * => the code must stay in the while loop */
  3555. /* EINTR can be generated on a socket with a timeout set even
  3556. * when SA_RESTART is effective for all relevant signals
  3557. * (see signal(7)).
  3558. * => stay in the while loop */
  3559. } else {
  3560. DEBUG_TRACE("recv() failed, error %d", err);
  3561. return -1;
  3562. }
  3563. #endif
  3564. }
  3565. if (timeout > 0) {
  3566. clock_gettime(CLOCK_MONOTONIC, &now);
  3567. }
  3568. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3569. /* Timeout occured, but no data available. */
  3570. return -1;
  3571. }
  3572. static int
  3573. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3574. {
  3575. int n, nread = 0;
  3576. double timeout = -1.0;
  3577. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3578. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3579. }
  3580. while (len > 0 && conn->ctx->stop_flag == 0) {
  3581. n = pull(fp, conn, buf + nread, len, timeout);
  3582. if (n < 0) {
  3583. if (nread == 0) {
  3584. nread = n; /* Propagate the error */
  3585. }
  3586. break;
  3587. } else if (n == 0) {
  3588. break; /* No more data to read */
  3589. } else {
  3590. conn->consumed_content += n;
  3591. nread += n;
  3592. len -= n;
  3593. }
  3594. }
  3595. return nread;
  3596. }
  3597. static void
  3598. discard_unread_request_data(struct mg_connection *conn)
  3599. {
  3600. char buf[MG_BUF_LEN];
  3601. size_t to_read;
  3602. int nread;
  3603. if (conn == NULL) {
  3604. return;
  3605. }
  3606. to_read = sizeof(buf);
  3607. if (conn->is_chunked) {
  3608. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3609. * completely */
  3610. while (conn->is_chunked == 1) {
  3611. nread = mg_read(conn, buf, to_read);
  3612. if (nread <= 0) {
  3613. break;
  3614. }
  3615. }
  3616. } else {
  3617. /* Not chunked: content length is known */
  3618. while (conn->consumed_content < conn->content_len) {
  3619. if (to_read
  3620. > (size_t)(conn->content_len - conn->consumed_content)) {
  3621. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3622. }
  3623. nread = mg_read(conn, buf, to_read);
  3624. if (nread <= 0) {
  3625. break;
  3626. }
  3627. }
  3628. }
  3629. }
  3630. static int
  3631. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3632. {
  3633. int64_t n, buffered_len, nread;
  3634. int64_t len64 =
  3635. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3636. * int, we may not read more
  3637. * bytes */
  3638. const char *body;
  3639. if (conn == NULL) {
  3640. return 0;
  3641. }
  3642. /* If Content-Length is not set for a PUT or POST request, read until
  3643. * socket is closed */
  3644. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3645. conn->content_len = INT64_MAX;
  3646. conn->must_close = 1;
  3647. }
  3648. nread = 0;
  3649. if (conn->consumed_content < conn->content_len) {
  3650. /* Adjust number of bytes to read. */
  3651. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3652. if (left_to_read < len64) {
  3653. /* Do not read more than the total content length of the request.
  3654. */
  3655. len64 = left_to_read;
  3656. }
  3657. /* Return buffered data */
  3658. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3659. - conn->consumed_content;
  3660. if (buffered_len > 0) {
  3661. if (len64 < buffered_len) {
  3662. buffered_len = len64;
  3663. }
  3664. body = conn->buf + conn->request_len + conn->consumed_content;
  3665. memcpy(buf, body, (size_t)buffered_len);
  3666. len64 -= buffered_len;
  3667. conn->consumed_content += buffered_len;
  3668. nread += buffered_len;
  3669. buf = (char *)buf + buffered_len;
  3670. }
  3671. /* We have returned all buffered data. Read new data from the remote
  3672. * socket.
  3673. */
  3674. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3675. nread += n;
  3676. } else {
  3677. nread = ((nread > 0) ? nread : n);
  3678. }
  3679. }
  3680. return (int)nread;
  3681. }
  3682. static char
  3683. mg_getc(struct mg_connection *conn)
  3684. {
  3685. char c;
  3686. if (conn == NULL) {
  3687. return 0;
  3688. }
  3689. conn->content_len++;
  3690. if (mg_read_inner(conn, &c, 1) <= 0) {
  3691. return (char)0;
  3692. }
  3693. return c;
  3694. }
  3695. int
  3696. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3697. {
  3698. if (len > INT_MAX) {
  3699. len = INT_MAX;
  3700. }
  3701. if (conn == NULL) {
  3702. return 0;
  3703. }
  3704. if (conn->is_chunked) {
  3705. size_t all_read = 0;
  3706. while (len > 0) {
  3707. if (conn->is_chunked == 2) {
  3708. /* No more data left to read */
  3709. return 0;
  3710. }
  3711. if (conn->chunk_remainder) {
  3712. /* copy from the remainder of the last received chunk */
  3713. long read_ret;
  3714. size_t read_now =
  3715. ((conn->chunk_remainder > len) ? (len)
  3716. : (conn->chunk_remainder));
  3717. conn->content_len += (int)read_now;
  3718. read_ret =
  3719. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3720. all_read += (size_t)read_ret;
  3721. conn->chunk_remainder -= read_now;
  3722. len -= read_now;
  3723. if (conn->chunk_remainder == 0) {
  3724. /* the rest of the data in the current chunk has been read
  3725. */
  3726. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3727. /* Protocol violation */
  3728. return -1;
  3729. }
  3730. }
  3731. } else {
  3732. /* fetch a new chunk */
  3733. int i = 0;
  3734. char lenbuf[64];
  3735. char *end = 0;
  3736. unsigned long chunkSize = 0;
  3737. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3738. lenbuf[i] = mg_getc(conn);
  3739. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3740. continue;
  3741. }
  3742. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3743. lenbuf[i + 1] = 0;
  3744. chunkSize = strtoul(lenbuf, &end, 16);
  3745. if (chunkSize == 0) {
  3746. /* regular end of content */
  3747. conn->is_chunked = 2;
  3748. }
  3749. break;
  3750. }
  3751. if (!isalnum(lenbuf[i])) {
  3752. /* illegal character for chunk length */
  3753. return -1;
  3754. }
  3755. }
  3756. if ((end == NULL) || (*end != '\r')) {
  3757. /* chunksize not set correctly */
  3758. return -1;
  3759. }
  3760. if (chunkSize == 0) {
  3761. break;
  3762. }
  3763. conn->chunk_remainder = chunkSize;
  3764. }
  3765. }
  3766. return (int)all_read;
  3767. }
  3768. return mg_read_inner(conn, buf, len);
  3769. }
  3770. int
  3771. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3772. {
  3773. time_t now;
  3774. int64_t n, total, allowed;
  3775. if (conn == NULL) {
  3776. return 0;
  3777. }
  3778. if (conn->throttle > 0) {
  3779. if ((now = time(NULL)) != conn->last_throttle_time) {
  3780. conn->last_throttle_time = now;
  3781. conn->last_throttle_bytes = 0;
  3782. }
  3783. allowed = conn->throttle - conn->last_throttle_bytes;
  3784. if (allowed > (int64_t)len) {
  3785. allowed = (int64_t)len;
  3786. }
  3787. if ((total = push_all(conn->ctx,
  3788. NULL,
  3789. conn->client.sock,
  3790. conn->ssl,
  3791. (const char *)buf,
  3792. (int64_t)allowed)) == allowed) {
  3793. buf = (const char *)buf + total;
  3794. conn->last_throttle_bytes += total;
  3795. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3796. allowed = (conn->throttle > ((int64_t)len - total))
  3797. ? (int64_t)len - total
  3798. : conn->throttle;
  3799. if ((n = push_all(conn->ctx,
  3800. NULL,
  3801. conn->client.sock,
  3802. conn->ssl,
  3803. (const char *)buf,
  3804. (int64_t)allowed)) != allowed) {
  3805. break;
  3806. }
  3807. sleep(1);
  3808. conn->last_throttle_bytes = allowed;
  3809. conn->last_throttle_time = time(NULL);
  3810. buf = (const char *)buf + n;
  3811. total += n;
  3812. }
  3813. }
  3814. } else {
  3815. total = push_all(conn->ctx,
  3816. NULL,
  3817. conn->client.sock,
  3818. conn->ssl,
  3819. (const char *)buf,
  3820. (int64_t)len);
  3821. }
  3822. return (int)total;
  3823. }
  3824. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3825. static int
  3826. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3827. {
  3828. va_list ap_copy;
  3829. size_t size = MG_BUF_LEN / 4;
  3830. int len = -1;
  3831. *buf = NULL;
  3832. while (len < 0) {
  3833. if (*buf) {
  3834. mg_free(*buf);
  3835. }
  3836. size *= 4;
  3837. *buf = (char *)mg_malloc(size);
  3838. if (!*buf) {
  3839. break;
  3840. }
  3841. va_copy(ap_copy, ap);
  3842. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3843. va_end(ap_copy);
  3844. (*buf)[size - 1] = 0;
  3845. }
  3846. return len;
  3847. }
  3848. /* Print message to buffer. If buffer is large enough to hold the message,
  3849. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3850. * and return allocated buffer. */
  3851. static int
  3852. alloc_vprintf(char **out_buf,
  3853. char *prealloc_buf,
  3854. size_t prealloc_size,
  3855. const char *fmt,
  3856. va_list ap)
  3857. {
  3858. va_list ap_copy;
  3859. int len;
  3860. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3861. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3862. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3863. * Therefore, we make two passes: on first pass, get required message
  3864. * length.
  3865. * On second pass, actually print the message. */
  3866. va_copy(ap_copy, ap);
  3867. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3868. va_end(ap_copy);
  3869. if (len < 0) {
  3870. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3871. * Switch to alternative code path that uses incremental allocations.
  3872. */
  3873. va_copy(ap_copy, ap);
  3874. len = alloc_vprintf2(out_buf, fmt, ap);
  3875. va_end(ap_copy);
  3876. } else if ((size_t)(len) >= prealloc_size) {
  3877. /* The pre-allocated buffer not large enough. */
  3878. /* Allocate a new buffer. */
  3879. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3880. if (!*out_buf) {
  3881. /* Allocation failed. Return -1 as "out of memory" error. */
  3882. return -1;
  3883. }
  3884. /* Buffer allocation successful. Store the string there. */
  3885. va_copy(ap_copy, ap);
  3886. IGNORE_UNUSED_RESULT(
  3887. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3888. va_end(ap_copy);
  3889. } else {
  3890. /* The pre-allocated buffer is large enough.
  3891. * Use it to store the string and return the address. */
  3892. va_copy(ap_copy, ap);
  3893. IGNORE_UNUSED_RESULT(
  3894. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3895. va_end(ap_copy);
  3896. *out_buf = prealloc_buf;
  3897. }
  3898. return len;
  3899. }
  3900. static int
  3901. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3902. {
  3903. char mem[MG_BUF_LEN];
  3904. char *buf = NULL;
  3905. int len;
  3906. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3907. len = mg_write(conn, buf, (size_t)len);
  3908. }
  3909. if (buf != mem && buf != NULL) {
  3910. mg_free(buf);
  3911. }
  3912. return len;
  3913. }
  3914. int
  3915. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3916. {
  3917. va_list ap;
  3918. int result;
  3919. va_start(ap, fmt);
  3920. result = mg_vprintf(conn, fmt, ap);
  3921. va_end(ap);
  3922. return result;
  3923. }
  3924. int
  3925. mg_url_decode(const char *src,
  3926. int src_len,
  3927. char *dst,
  3928. int dst_len,
  3929. int is_form_url_encoded)
  3930. {
  3931. int i, j, a, b;
  3932. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  3933. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  3934. if (i < src_len - 2 && src[i] == '%'
  3935. && isxdigit(*(const unsigned char *)(src + i + 1))
  3936. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3937. a = tolower(*(const unsigned char *)(src + i + 1));
  3938. b = tolower(*(const unsigned char *)(src + i + 2));
  3939. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3940. i += 2;
  3941. } else if (is_form_url_encoded && src[i] == '+') {
  3942. dst[j] = ' ';
  3943. } else {
  3944. dst[j] = src[i];
  3945. }
  3946. }
  3947. dst[j] = '\0'; /* Null-terminate the destination */
  3948. return (i >= src_len) ? j : -1;
  3949. }
  3950. int
  3951. mg_get_var(const char *data,
  3952. size_t data_len,
  3953. const char *name,
  3954. char *dst,
  3955. size_t dst_len)
  3956. {
  3957. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3958. }
  3959. int
  3960. mg_get_var2(const char *data,
  3961. size_t data_len,
  3962. const char *name,
  3963. char *dst,
  3964. size_t dst_len,
  3965. size_t occurrence)
  3966. {
  3967. const char *p, *e, *s;
  3968. size_t name_len;
  3969. int len;
  3970. if (dst == NULL || dst_len == 0) {
  3971. len = -2;
  3972. } else if (data == NULL || name == NULL || data_len == 0) {
  3973. len = -1;
  3974. dst[0] = '\0';
  3975. } else {
  3976. name_len = strlen(name);
  3977. e = data + data_len;
  3978. len = -1;
  3979. dst[0] = '\0';
  3980. /* data is "var1=val1&var2=val2...". Find variable first */
  3981. for (p = data; p + name_len < e; p++) {
  3982. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3983. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3984. /* Point p to variable value */
  3985. p += name_len + 1;
  3986. /* Point s to the end of the value */
  3987. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3988. if (s == NULL) {
  3989. s = e;
  3990. }
  3991. /* assert(s >= p); */
  3992. if (s < p) {
  3993. return -3;
  3994. }
  3995. /* Decode variable into destination buffer */
  3996. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3997. /* Redirect error code from -1 to -2 (destination buffer too
  3998. * small). */
  3999. if (len == -1) {
  4000. len = -2;
  4001. }
  4002. break;
  4003. }
  4004. }
  4005. }
  4006. return len;
  4007. }
  4008. int
  4009. mg_get_cookie(const char *cookie_header,
  4010. const char *var_name,
  4011. char *dst,
  4012. size_t dst_size)
  4013. {
  4014. const char *s, *p, *end;
  4015. int name_len, len = -1;
  4016. if (dst == NULL || dst_size == 0) {
  4017. len = -2;
  4018. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4019. len = -1;
  4020. dst[0] = '\0';
  4021. } else {
  4022. name_len = (int)strlen(var_name);
  4023. end = s + strlen(s);
  4024. dst[0] = '\0';
  4025. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4026. if (s[name_len] == '=') {
  4027. s += name_len + 1;
  4028. if ((p = strchr(s, ' ')) == NULL) {
  4029. p = end;
  4030. }
  4031. if (p[-1] == ';') {
  4032. p--;
  4033. }
  4034. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4035. s++;
  4036. p--;
  4037. }
  4038. if ((size_t)(p - s) < dst_size) {
  4039. len = (int)(p - s);
  4040. mg_strlcpy(dst, s, (size_t)len + 1);
  4041. } else {
  4042. len = -3;
  4043. }
  4044. break;
  4045. }
  4046. }
  4047. }
  4048. return len;
  4049. }
  4050. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4051. static void
  4052. base64_encode(const unsigned char *src, int src_len, char *dst)
  4053. {
  4054. static const char *b64 =
  4055. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4056. int i, j, a, b, c;
  4057. for (i = j = 0; i < src_len; i += 3) {
  4058. a = src[i];
  4059. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4060. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4061. dst[j++] = b64[a >> 2];
  4062. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4063. if (i + 1 < src_len) {
  4064. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4065. }
  4066. if (i + 2 < src_len) {
  4067. dst[j++] = b64[c & 63];
  4068. }
  4069. }
  4070. while (j % 4 != 0) {
  4071. dst[j++] = '=';
  4072. }
  4073. dst[j++] = '\0';
  4074. }
  4075. #endif
  4076. #if defined(USE_LUA)
  4077. static unsigned char
  4078. b64reverse(char letter)
  4079. {
  4080. if (letter >= 'A' && letter <= 'Z') {
  4081. return letter - 'A';
  4082. }
  4083. if (letter >= 'a' && letter <= 'z') {
  4084. return letter - 'a' + 26;
  4085. }
  4086. if (letter >= '0' && letter <= '9') {
  4087. return letter - '0' + 52;
  4088. }
  4089. if (letter == '+') {
  4090. return 62;
  4091. }
  4092. if (letter == '/') {
  4093. return 63;
  4094. }
  4095. if (letter == '=') {
  4096. return 255; /* normal end */
  4097. }
  4098. return 254; /* error */
  4099. }
  4100. static int
  4101. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4102. {
  4103. int i;
  4104. unsigned char a, b, c, d;
  4105. *dst_len = 0;
  4106. for (i = 0; i < src_len; i += 4) {
  4107. a = b64reverse(src[i]);
  4108. if (a >= 254) {
  4109. return i;
  4110. }
  4111. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4112. if (b >= 254) {
  4113. return i + 1;
  4114. }
  4115. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4116. if (c == 254) {
  4117. return i + 2;
  4118. }
  4119. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4120. if (d == 254) {
  4121. return i + 3;
  4122. }
  4123. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4124. if (c != 255) {
  4125. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4126. if (d != 255) {
  4127. dst[(*dst_len)++] = (c << 6) + d;
  4128. }
  4129. }
  4130. }
  4131. return -1;
  4132. }
  4133. #endif
  4134. static int
  4135. is_put_or_delete_method(const struct mg_connection *conn)
  4136. {
  4137. if (conn) {
  4138. const char *s = conn->request_info.request_method;
  4139. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4140. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4141. }
  4142. return 0;
  4143. }
  4144. static void
  4145. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4146. char *filename, /* out: filename */
  4147. size_t filename_buf_len, /* in: size of filename buffer */
  4148. struct file *filep, /* out: file structure */
  4149. int *is_found, /* out: file is found (directly) */
  4150. int *is_script_resource, /* out: handled by a script? */
  4151. int *is_websocket_request, /* out: websocket connetion? */
  4152. int *is_put_or_delete_request /* out: put/delete a file? */
  4153. )
  4154. {
  4155. /* TODO (high): Restructure this function */
  4156. #if !defined(NO_FILES)
  4157. const char *uri = conn->request_info.local_uri;
  4158. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4159. const char *rewrite;
  4160. struct vec a, b;
  4161. int match_len;
  4162. char gz_path[PATH_MAX];
  4163. char const *accept_encoding;
  4164. int truncated;
  4165. #if !defined(NO_CGI) || defined(USE_LUA)
  4166. char *p;
  4167. #endif
  4168. #else
  4169. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4170. #endif
  4171. memset(filep, 0, sizeof(*filep));
  4172. *filename = 0;
  4173. *is_found = 0;
  4174. *is_script_resource = 0;
  4175. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4176. #if defined(USE_WEBSOCKET)
  4177. *is_websocket_request = is_websocket_protocol(conn);
  4178. #if !defined(NO_FILES)
  4179. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4180. root = conn->ctx->config[WEBSOCKET_ROOT];
  4181. }
  4182. #endif /* !NO_FILES */
  4183. #else /* USE_WEBSOCKET */
  4184. *is_websocket_request = 0;
  4185. #endif /* USE_WEBSOCKET */
  4186. #if !defined(NO_FILES)
  4187. /* Note that root == NULL is a regular use case here. This occurs,
  4188. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4189. * config is not required. */
  4190. if (root == NULL) {
  4191. /* all file related outputs have already been set to 0, just return
  4192. */
  4193. return;
  4194. }
  4195. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4196. * of the path one byte on the right.
  4197. * If document_root is NULL, leave the file empty. */
  4198. mg_snprintf(
  4199. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4200. if (truncated) {
  4201. goto interpret_cleanup;
  4202. }
  4203. rewrite = conn->ctx->config[REWRITE];
  4204. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4205. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4206. mg_snprintf(conn,
  4207. &truncated,
  4208. filename,
  4209. filename_buf_len - 1,
  4210. "%.*s%s",
  4211. (int)b.len,
  4212. b.ptr,
  4213. uri + match_len);
  4214. break;
  4215. }
  4216. }
  4217. if (truncated) {
  4218. goto interpret_cleanup;
  4219. }
  4220. /* Local file path and name, corresponding to requested URI
  4221. * is now stored in "filename" variable. */
  4222. if (mg_stat(conn, filename, filep)) {
  4223. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4224. /* File exists. Check if it is a script type. */
  4225. if (0
  4226. #if !defined(NO_CGI)
  4227. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4228. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4229. filename) > 0
  4230. #endif
  4231. #if defined(USE_LUA)
  4232. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4233. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4234. filename) > 0
  4235. #endif
  4236. #if defined(USE_DUKTAPE)
  4237. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4238. strlen(
  4239. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4240. filename) > 0
  4241. #endif
  4242. ) {
  4243. /* The request addresses a CGI script or a Lua script. The URI
  4244. * corresponds to the script itself (like /path/script.cgi),
  4245. * and there is no additional resource path
  4246. * (like /path/script.cgi/something).
  4247. * Requests that modify (replace or delete) a resource, like
  4248. * PUT and DELETE requests, should replace/delete the script
  4249. * file.
  4250. * Requests that read or write from/to a resource, like GET and
  4251. * POST requests, should call the script and return the
  4252. * generated response. */
  4253. *is_script_resource = !*is_put_or_delete_request;
  4254. }
  4255. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4256. *is_found = 1;
  4257. return;
  4258. }
  4259. /* If we can't find the actual file, look for the file
  4260. * with the same name but a .gz extension. If we find it,
  4261. * use that and set the gzipped flag in the file struct
  4262. * to indicate that the response need to have the content-
  4263. * encoding: gzip header.
  4264. * We can only do this if the browser declares support. */
  4265. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4266. if (strstr(accept_encoding, "gzip") != NULL) {
  4267. mg_snprintf(
  4268. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4269. if (truncated) {
  4270. goto interpret_cleanup;
  4271. }
  4272. if (mg_stat(conn, gz_path, filep)) {
  4273. if (filep) {
  4274. filep->gzipped = 1;
  4275. *is_found = 1;
  4276. }
  4277. /* Currently gz files can not be scripts. */
  4278. return;
  4279. }
  4280. }
  4281. }
  4282. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4283. /* Support PATH_INFO for CGI scripts. */
  4284. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4285. if (*p == '/') {
  4286. *p = '\0';
  4287. if ((0
  4288. #if !defined(NO_CGI)
  4289. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4290. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4291. filename) > 0
  4292. #endif
  4293. #if defined(USE_LUA)
  4294. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4295. strlen(
  4296. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4297. filename) > 0
  4298. #endif
  4299. #if defined(USE_DUKTAPE)
  4300. || match_prefix(
  4301. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4302. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4303. filename) > 0
  4304. #endif
  4305. ) && mg_stat(conn, filename, filep)) {
  4306. /* Shift PATH_INFO block one character right, e.g.
  4307. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4308. * conn->path_info is pointing to the local variable "path"
  4309. * declared in handle_request(), so PATH_INFO is not valid
  4310. * after handle_request returns. */
  4311. conn->path_info = p + 1;
  4312. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4313. * trailing \0 */
  4314. p[1] = '/';
  4315. *is_script_resource = 1;
  4316. break;
  4317. } else {
  4318. *p = '/';
  4319. }
  4320. }
  4321. }
  4322. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4323. #endif /* !defined(NO_FILES) */
  4324. return;
  4325. #if !defined(NO_FILES)
  4326. /* Reset all outputs */
  4327. interpret_cleanup:
  4328. memset(filep, 0, sizeof(*filep));
  4329. *filename = 0;
  4330. *is_found = 0;
  4331. *is_script_resource = 0;
  4332. *is_websocket_request = 0;
  4333. *is_put_or_delete_request = 0;
  4334. #endif /* !defined(NO_FILES) */
  4335. }
  4336. /* Check whether full request is buffered. Return:
  4337. * -1 if request is malformed
  4338. * 0 if request is not yet fully buffered
  4339. * >0 actual request length, including last \r\n\r\n */
  4340. static int
  4341. get_request_len(const char *buf, int buflen)
  4342. {
  4343. const char *s, *e;
  4344. int len = 0;
  4345. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4346. /* Control characters are not allowed but >=128 is. */
  4347. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4348. && *(const unsigned char *)s < 128) {
  4349. len = -1;
  4350. break; /* [i_a] abort scan as soon as one malformed character is
  4351. * found; */
  4352. /* don't let subsequent \r\n\r\n win us over anyhow */
  4353. } else if (s[0] == '\n' && s[1] == '\n') {
  4354. len = (int)(s - buf) + 2;
  4355. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4356. len = (int)(s - buf) + 3;
  4357. }
  4358. return len;
  4359. }
  4360. #if !defined(NO_CACHING)
  4361. /* Convert month to the month number. Return -1 on error, or month number */
  4362. static int
  4363. get_month_index(const char *s)
  4364. {
  4365. size_t i;
  4366. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4367. if (!strcmp(s, month_names[i])) {
  4368. return (int)i;
  4369. }
  4370. }
  4371. return -1;
  4372. }
  4373. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4374. static time_t
  4375. parse_date_string(const char *datetime)
  4376. {
  4377. char month_str[32] = {0};
  4378. int second, minute, hour, day, month, year;
  4379. time_t result = (time_t)0;
  4380. struct tm tm;
  4381. if ((sscanf(datetime,
  4382. "%d/%3s/%d %d:%d:%d",
  4383. &day,
  4384. month_str,
  4385. &year,
  4386. &hour,
  4387. &minute,
  4388. &second) == 6) || (sscanf(datetime,
  4389. "%d %3s %d %d:%d:%d",
  4390. &day,
  4391. month_str,
  4392. &year,
  4393. &hour,
  4394. &minute,
  4395. &second) == 6)
  4396. || (sscanf(datetime,
  4397. "%*3s, %d %3s %d %d:%d:%d",
  4398. &day,
  4399. month_str,
  4400. &year,
  4401. &hour,
  4402. &minute,
  4403. &second) == 6) || (sscanf(datetime,
  4404. "%d-%3s-%d %d:%d:%d",
  4405. &day,
  4406. month_str,
  4407. &year,
  4408. &hour,
  4409. &minute,
  4410. &second) == 6)) {
  4411. month = get_month_index(month_str);
  4412. if ((month >= 0) && (year >= 1970)) {
  4413. memset(&tm, 0, sizeof(tm));
  4414. tm.tm_year = year - 1900;
  4415. tm.tm_mon = month;
  4416. tm.tm_mday = day;
  4417. tm.tm_hour = hour;
  4418. tm.tm_min = minute;
  4419. tm.tm_sec = second;
  4420. result = timegm(&tm);
  4421. }
  4422. }
  4423. return result;
  4424. }
  4425. #endif /* !NO_CACHING */
  4426. /* Protect against directory disclosure attack by removing '..',
  4427. * excessive '/' and '\' characters */
  4428. static void
  4429. remove_double_dots_and_double_slashes(char *s)
  4430. {
  4431. char *p = s;
  4432. while (*s != '\0') {
  4433. *p++ = *s++;
  4434. if (s[-1] == '/' || s[-1] == '\\') {
  4435. /* Skip all following slashes, backslashes and double-dots */
  4436. while (s[0] != '\0') {
  4437. if (s[0] == '/' || s[0] == '\\') {
  4438. s++;
  4439. } else if (s[0] == '.' && s[1] == '.') {
  4440. s += 2;
  4441. } else {
  4442. break;
  4443. }
  4444. }
  4445. }
  4446. }
  4447. *p = '\0';
  4448. }
  4449. static const struct {
  4450. const char *extension;
  4451. size_t ext_len;
  4452. const char *mime_type;
  4453. } builtin_mime_types[] = {
  4454. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4455. * application types */
  4456. {".doc", 4, "application/msword"},
  4457. {".eps", 4, "application/postscript"},
  4458. {".exe", 4, "application/octet-stream"},
  4459. {".js", 3, "application/javascript"},
  4460. {".json", 5, "application/json"},
  4461. {".pdf", 4, "application/pdf"},
  4462. {".ps", 3, "application/postscript"},
  4463. {".rtf", 4, "application/rtf"},
  4464. {".xhtml", 6, "application/xhtml+xml"},
  4465. {".xsl", 4, "application/xml"},
  4466. {".xslt", 5, "application/xml"},
  4467. /* fonts */
  4468. {".ttf", 4, "application/font-sfnt"},
  4469. {".cff", 4, "application/font-sfnt"},
  4470. {".otf", 4, "application/font-sfnt"},
  4471. {".aat", 4, "application/font-sfnt"},
  4472. {".sil", 4, "application/font-sfnt"},
  4473. {".pfr", 4, "application/font-tdpfr"},
  4474. {".woff", 5, "application/font-woff"},
  4475. /* audio */
  4476. {".mp3", 4, "audio/mpeg"},
  4477. {".oga", 4, "audio/ogg"},
  4478. {".ogg", 4, "audio/ogg"},
  4479. /* image */
  4480. {".gif", 4, "image/gif"},
  4481. {".ief", 4, "image/ief"},
  4482. {".jpeg", 5, "image/jpeg"},
  4483. {".jpg", 4, "image/jpeg"},
  4484. {".jpm", 4, "image/jpm"},
  4485. {".jpx", 4, "image/jpx"},
  4486. {".png", 4, "image/png"},
  4487. {".svg", 4, "image/svg+xml"},
  4488. {".tif", 4, "image/tiff"},
  4489. {".tiff", 5, "image/tiff"},
  4490. /* model */
  4491. {".wrl", 4, "model/vrml"},
  4492. /* text */
  4493. {".css", 4, "text/css"},
  4494. {".csv", 4, "text/csv"},
  4495. {".htm", 4, "text/html"},
  4496. {".html", 5, "text/html"},
  4497. {".sgm", 4, "text/sgml"},
  4498. {".shtm", 5, "text/html"},
  4499. {".shtml", 6, "text/html"},
  4500. {".txt", 4, "text/plain"},
  4501. {".xml", 4, "text/xml"},
  4502. /* video */
  4503. {".mov", 4, "video/quicktime"},
  4504. {".mp4", 4, "video/mp4"},
  4505. {".mpeg", 5, "video/mpeg"},
  4506. {".mpg", 4, "video/mpeg"},
  4507. {".ogv", 4, "video/ogg"},
  4508. {".qt", 3, "video/quicktime"},
  4509. /* not registered types
  4510. * (http://reference.sitepoint.com/html/mime-types-full,
  4511. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4512. {".arj", 4, "application/x-arj-compressed"},
  4513. {".gz", 3, "application/x-gunzip"},
  4514. {".rar", 4, "application/x-arj-compressed"},
  4515. {".swf", 4, "application/x-shockwave-flash"},
  4516. {".tar", 4, "application/x-tar"},
  4517. {".tgz", 4, "application/x-tar-gz"},
  4518. {".torrent", 8, "application/x-bittorrent"},
  4519. {".ppt", 4, "application/x-mspowerpoint"},
  4520. {".xls", 4, "application/x-msexcel"},
  4521. {".zip", 4, "application/x-zip-compressed"},
  4522. {".aac",
  4523. 4,
  4524. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4525. {".aif", 4, "audio/x-aif"},
  4526. {".m3u", 4, "audio/x-mpegurl"},
  4527. {".mid", 4, "audio/x-midi"},
  4528. {".ra", 3, "audio/x-pn-realaudio"},
  4529. {".ram", 4, "audio/x-pn-realaudio"},
  4530. {".wav", 4, "audio/x-wav"},
  4531. {".bmp", 4, "image/bmp"},
  4532. {".ico", 4, "image/x-icon"},
  4533. {".pct", 4, "image/x-pct"},
  4534. {".pict", 5, "image/pict"},
  4535. {".rgb", 4, "image/x-rgb"},
  4536. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4537. {".asf", 4, "video/x-ms-asf"},
  4538. {".avi", 4, "video/x-msvideo"},
  4539. {".m4v", 4, "video/x-m4v"},
  4540. {NULL, 0, NULL}};
  4541. const char *
  4542. mg_get_builtin_mime_type(const char *path)
  4543. {
  4544. const char *ext;
  4545. size_t i, path_len;
  4546. path_len = strlen(path);
  4547. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4548. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4549. if (path_len > builtin_mime_types[i].ext_len
  4550. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4551. return builtin_mime_types[i].mime_type;
  4552. }
  4553. }
  4554. return "text/plain";
  4555. }
  4556. /* Look at the "path" extension and figure what mime type it has.
  4557. * Store mime type in the vector. */
  4558. static void
  4559. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4560. {
  4561. struct vec ext_vec, mime_vec;
  4562. const char *list, *ext;
  4563. size_t path_len;
  4564. path_len = strlen(path);
  4565. if (ctx == NULL || vec == NULL) {
  4566. return;
  4567. }
  4568. /* Scan user-defined mime types first, in case user wants to
  4569. * override default mime types. */
  4570. list = ctx->config[EXTRA_MIME_TYPES];
  4571. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4572. /* ext now points to the path suffix */
  4573. ext = path + path_len - ext_vec.len;
  4574. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4575. *vec = mime_vec;
  4576. return;
  4577. }
  4578. }
  4579. vec->ptr = mg_get_builtin_mime_type(path);
  4580. vec->len = strlen(vec->ptr);
  4581. }
  4582. /* Stringify binary data. Output buffer must be twice as big as input,
  4583. * because each byte takes 2 bytes in string representation */
  4584. static void
  4585. bin2str(char *to, const unsigned char *p, size_t len)
  4586. {
  4587. static const char *hex = "0123456789abcdef";
  4588. for (; len--; p++) {
  4589. *to++ = hex[p[0] >> 4];
  4590. *to++ = hex[p[0] & 0x0f];
  4591. }
  4592. *to = '\0';
  4593. }
  4594. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4595. char *
  4596. mg_md5(char buf[33], ...)
  4597. {
  4598. md5_byte_t hash[16];
  4599. const char *p;
  4600. va_list ap;
  4601. md5_state_t ctx;
  4602. md5_init(&ctx);
  4603. va_start(ap, buf);
  4604. while ((p = va_arg(ap, const char *)) != NULL) {
  4605. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4606. }
  4607. va_end(ap);
  4608. md5_finish(&ctx, hash);
  4609. bin2str(buf, hash, sizeof(hash));
  4610. return buf;
  4611. }
  4612. /* Check the user's password, return 1 if OK */
  4613. static int
  4614. check_password(const char *method,
  4615. const char *ha1,
  4616. const char *uri,
  4617. const char *nonce,
  4618. const char *nc,
  4619. const char *cnonce,
  4620. const char *qop,
  4621. const char *response)
  4622. {
  4623. char ha2[32 + 1], expected_response[32 + 1];
  4624. /* Some of the parameters may be NULL */
  4625. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4626. || qop == NULL
  4627. || response == NULL) {
  4628. return 0;
  4629. }
  4630. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4631. if (strlen(response) != 32) {
  4632. return 0;
  4633. }
  4634. mg_md5(ha2, method, ":", uri, NULL);
  4635. mg_md5(expected_response,
  4636. ha1,
  4637. ":",
  4638. nonce,
  4639. ":",
  4640. nc,
  4641. ":",
  4642. cnonce,
  4643. ":",
  4644. qop,
  4645. ":",
  4646. ha2,
  4647. NULL);
  4648. return mg_strcasecmp(response, expected_response) == 0;
  4649. }
  4650. /* Use the global passwords file, if specified by auth_gpass option,
  4651. * or search for .htpasswd in the requested directory. */
  4652. static void
  4653. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4654. {
  4655. if (conn != NULL && conn->ctx != NULL) {
  4656. char name[PATH_MAX];
  4657. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4658. struct file file = STRUCT_FILE_INITIALIZER;
  4659. int truncated;
  4660. if (gpass != NULL) {
  4661. /* Use global passwords file */
  4662. if (!mg_fopen(conn, gpass, "r", filep)) {
  4663. #ifdef DEBUG
  4664. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4665. #endif
  4666. }
  4667. /* Important: using local struct file to test path for is_directory
  4668. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4669. * was opened. */
  4670. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4671. mg_snprintf(conn,
  4672. &truncated,
  4673. name,
  4674. sizeof(name),
  4675. "%s/%s",
  4676. path,
  4677. PASSWORDS_FILE_NAME);
  4678. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4679. #ifdef DEBUG
  4680. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4681. #endif
  4682. }
  4683. } else {
  4684. /* Try to find .htpasswd in requested directory. */
  4685. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4686. if (e[0] == '/') {
  4687. break;
  4688. }
  4689. }
  4690. mg_snprintf(conn,
  4691. &truncated,
  4692. name,
  4693. sizeof(name),
  4694. "%.*s/%s",
  4695. (int)(e - p),
  4696. p,
  4697. PASSWORDS_FILE_NAME);
  4698. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4699. #ifdef DEBUG
  4700. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4701. #endif
  4702. }
  4703. }
  4704. }
  4705. }
  4706. /* Parsed Authorization header */
  4707. struct ah {
  4708. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4709. };
  4710. /* Return 1 on success. Always initializes the ah structure. */
  4711. static int
  4712. parse_auth_header(struct mg_connection *conn,
  4713. char *buf,
  4714. size_t buf_size,
  4715. struct ah *ah)
  4716. {
  4717. char *name, *value, *s;
  4718. const char *auth_header;
  4719. uint64_t nonce;
  4720. if (!ah || !conn) {
  4721. return 0;
  4722. }
  4723. (void)memset(ah, 0, sizeof(*ah));
  4724. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4725. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4726. return 0;
  4727. }
  4728. /* Make modifiable copy of the auth header */
  4729. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4730. s = buf;
  4731. /* Parse authorization header */
  4732. for (;;) {
  4733. /* Gobble initial spaces */
  4734. while (isspace(*(unsigned char *)s)) {
  4735. s++;
  4736. }
  4737. name = skip_quoted(&s, "=", " ", 0);
  4738. /* Value is either quote-delimited, or ends at first comma or space. */
  4739. if (s[0] == '\"') {
  4740. s++;
  4741. value = skip_quoted(&s, "\"", " ", '\\');
  4742. if (s[0] == ',') {
  4743. s++;
  4744. }
  4745. } else {
  4746. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4747. * spaces */
  4748. }
  4749. if (*name == '\0') {
  4750. break;
  4751. }
  4752. if (!strcmp(name, "username")) {
  4753. ah->user = value;
  4754. } else if (!strcmp(name, "cnonce")) {
  4755. ah->cnonce = value;
  4756. } else if (!strcmp(name, "response")) {
  4757. ah->response = value;
  4758. } else if (!strcmp(name, "uri")) {
  4759. ah->uri = value;
  4760. } else if (!strcmp(name, "qop")) {
  4761. ah->qop = value;
  4762. } else if (!strcmp(name, "nc")) {
  4763. ah->nc = value;
  4764. } else if (!strcmp(name, "nonce")) {
  4765. ah->nonce = value;
  4766. }
  4767. }
  4768. #ifndef NO_NONCE_CHECK
  4769. /* Read the nonce from the response. */
  4770. if (ah->nonce == NULL) {
  4771. return 0;
  4772. }
  4773. s = NULL;
  4774. nonce = strtoull(ah->nonce, &s, 10);
  4775. if ((s == NULL) || (*s != 0)) {
  4776. return 0;
  4777. }
  4778. /* Convert the nonce from the client to a number. */
  4779. nonce ^= conn->ctx->auth_nonce_mask;
  4780. /* The converted number corresponds to the time the nounce has been
  4781. * created. This should not be earlier than the server start. */
  4782. /* Server side nonce check is valuable in all situations but one:
  4783. * if the server restarts frequently, but the client should not see
  4784. * that, so the server should accept nonces from previous starts. */
  4785. /* However, the reasonable default is to not accept a nonce from a
  4786. * previous start, so if anyone changed the access rights between
  4787. * two restarts, a new login is required. */
  4788. if (nonce < (uint64_t)conn->ctx->start_time) {
  4789. /* nonce is from a previous start of the server and no longer valid
  4790. * (replay attack?) */
  4791. return 0;
  4792. }
  4793. /* Check if the nonce is too high, so it has not (yet) been used by the
  4794. * server. */
  4795. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4796. return 0;
  4797. }
  4798. #else
  4799. (void)nonce;
  4800. #endif
  4801. /* CGI needs it as REMOTE_USER */
  4802. if (ah->user != NULL) {
  4803. conn->request_info.remote_user = mg_strdup(ah->user);
  4804. } else {
  4805. return 0;
  4806. }
  4807. return 1;
  4808. }
  4809. static const char *
  4810. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4811. {
  4812. const char *eof;
  4813. size_t len;
  4814. const char *memend;
  4815. if (!filep) {
  4816. return NULL;
  4817. }
  4818. if (filep->membuf != NULL && *p != NULL) {
  4819. memend = (const char *)&filep->membuf[filep->size];
  4820. /* Search for \n from p till the end of stream */
  4821. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4822. if (eof != NULL) {
  4823. eof += 1; /* Include \n */
  4824. } else {
  4825. eof = memend; /* Copy remaining data */
  4826. }
  4827. len =
  4828. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4829. memcpy(buf, *p, len);
  4830. buf[len] = '\0';
  4831. *p += len;
  4832. return len ? eof : NULL;
  4833. } else if (filep->fp != NULL) {
  4834. return fgets(buf, (int)size, filep->fp);
  4835. } else {
  4836. return NULL;
  4837. }
  4838. }
  4839. struct read_auth_file_struct {
  4840. struct mg_connection *conn;
  4841. struct ah ah;
  4842. char *domain;
  4843. char buf[256 + 256 + 40];
  4844. char *f_user;
  4845. char *f_domain;
  4846. char *f_ha1;
  4847. };
  4848. static int
  4849. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4850. {
  4851. char *p;
  4852. int is_authorized = 0;
  4853. struct file fp;
  4854. size_t l;
  4855. if (!filep || !workdata) {
  4856. return 0;
  4857. }
  4858. /* Loop over passwords file */
  4859. p = (char *)filep->membuf;
  4860. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4861. l = strlen(workdata->buf);
  4862. while (l > 0) {
  4863. if (isspace(workdata->buf[l - 1])
  4864. || iscntrl(workdata->buf[l - 1])) {
  4865. l--;
  4866. workdata->buf[l] = 0;
  4867. } else
  4868. break;
  4869. }
  4870. if (l < 1) {
  4871. continue;
  4872. }
  4873. workdata->f_user = workdata->buf;
  4874. if (workdata->f_user[0] == ':') {
  4875. /* user names may not contain a ':' and may not be empty,
  4876. * so lines starting with ':' may be used for a special purpose */
  4877. if (workdata->f_user[1] == '#') {
  4878. /* :# is a comment */
  4879. continue;
  4880. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4881. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4882. is_authorized = read_auth_file(&fp, workdata);
  4883. mg_fclose(&fp);
  4884. } else {
  4885. mg_cry(workdata->conn,
  4886. "%s: cannot open authorization file: %s",
  4887. __func__,
  4888. workdata->buf);
  4889. }
  4890. continue;
  4891. }
  4892. /* everything is invalid for the moment (might change in the
  4893. * future) */
  4894. mg_cry(workdata->conn,
  4895. "%s: syntax error in authorization file: %s",
  4896. __func__,
  4897. workdata->buf);
  4898. continue;
  4899. }
  4900. workdata->f_domain = strchr(workdata->f_user, ':');
  4901. if (workdata->f_domain == NULL) {
  4902. mg_cry(workdata->conn,
  4903. "%s: syntax error in authorization file: %s",
  4904. __func__,
  4905. workdata->buf);
  4906. continue;
  4907. }
  4908. *(workdata->f_domain) = 0;
  4909. (workdata->f_domain)++;
  4910. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4911. if (workdata->f_ha1 == NULL) {
  4912. mg_cry(workdata->conn,
  4913. "%s: syntax error in authorization file: %s",
  4914. __func__,
  4915. workdata->buf);
  4916. continue;
  4917. }
  4918. *(workdata->f_ha1) = 0;
  4919. (workdata->f_ha1)++;
  4920. if (!strcmp(workdata->ah.user, workdata->f_user)
  4921. && !strcmp(workdata->domain, workdata->f_domain)) {
  4922. return check_password(workdata->conn->request_info.request_method,
  4923. workdata->f_ha1,
  4924. workdata->ah.uri,
  4925. workdata->ah.nonce,
  4926. workdata->ah.nc,
  4927. workdata->ah.cnonce,
  4928. workdata->ah.qop,
  4929. workdata->ah.response);
  4930. }
  4931. }
  4932. return is_authorized;
  4933. }
  4934. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4935. static int
  4936. authorize(struct mg_connection *conn, struct file *filep)
  4937. {
  4938. struct read_auth_file_struct workdata;
  4939. char buf[MG_BUF_LEN];
  4940. if (!conn || !conn->ctx) {
  4941. return 0;
  4942. }
  4943. memset(&workdata, 0, sizeof(workdata));
  4944. workdata.conn = conn;
  4945. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4946. return 0;
  4947. }
  4948. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4949. return read_auth_file(filep, &workdata);
  4950. }
  4951. /* Return 1 if request is authorised, 0 otherwise. */
  4952. static int
  4953. check_authorization(struct mg_connection *conn, const char *path)
  4954. {
  4955. char fname[PATH_MAX];
  4956. struct vec uri_vec, filename_vec;
  4957. const char *list;
  4958. struct file file = STRUCT_FILE_INITIALIZER;
  4959. int authorized = 1, truncated;
  4960. if (!conn || !conn->ctx) {
  4961. return 0;
  4962. }
  4963. list = conn->ctx->config[PROTECT_URI];
  4964. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4965. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4966. mg_snprintf(conn,
  4967. &truncated,
  4968. fname,
  4969. sizeof(fname),
  4970. "%.*s",
  4971. (int)filename_vec.len,
  4972. filename_vec.ptr);
  4973. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4974. mg_cry(conn,
  4975. "%s: cannot open %s: %s",
  4976. __func__,
  4977. fname,
  4978. strerror(errno));
  4979. }
  4980. break;
  4981. }
  4982. }
  4983. if (!is_file_opened(&file)) {
  4984. open_auth_file(conn, path, &file);
  4985. }
  4986. if (is_file_opened(&file)) {
  4987. authorized = authorize(conn, &file);
  4988. mg_fclose(&file);
  4989. }
  4990. return authorized;
  4991. }
  4992. static void
  4993. send_authorization_request(struct mg_connection *conn)
  4994. {
  4995. char date[64];
  4996. time_t curtime = time(NULL);
  4997. if (conn && conn->ctx) {
  4998. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4999. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5000. nonce += conn->ctx->nonce_count;
  5001. ++conn->ctx->nonce_count;
  5002. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5003. nonce ^= conn->ctx->auth_nonce_mask;
  5004. conn->status_code = 401;
  5005. conn->must_close = 1;
  5006. gmt_time_string(date, sizeof(date), &curtime);
  5007. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5008. send_no_cache_header(conn);
  5009. mg_printf(conn,
  5010. "Date: %s\r\n"
  5011. "Connection: %s\r\n"
  5012. "Content-Length: 0\r\n"
  5013. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5014. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5015. date,
  5016. suggest_connection_header(conn),
  5017. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5018. nonce);
  5019. }
  5020. }
  5021. #if !defined(NO_FILES)
  5022. static int
  5023. is_authorized_for_put(struct mg_connection *conn)
  5024. {
  5025. if (conn) {
  5026. struct file file = STRUCT_FILE_INITIALIZER;
  5027. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5028. int ret = 0;
  5029. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5030. ret = authorize(conn, &file);
  5031. mg_fclose(&file);
  5032. }
  5033. return ret;
  5034. }
  5035. return 0;
  5036. }
  5037. #endif
  5038. int
  5039. mg_modify_passwords_file(const char *fname,
  5040. const char *domain,
  5041. const char *user,
  5042. const char *pass)
  5043. {
  5044. int found, i;
  5045. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5046. FILE *fp, *fp2;
  5047. found = 0;
  5048. fp = fp2 = NULL;
  5049. /* Regard empty password as no password - remove user record. */
  5050. if (pass != NULL && pass[0] == '\0') {
  5051. pass = NULL;
  5052. }
  5053. /* Other arguments must not be empty */
  5054. if (fname == NULL || domain == NULL || user == NULL) {
  5055. return 0;
  5056. }
  5057. /* Using the given file format, user name and domain must not contain ':'
  5058. */
  5059. if (strchr(user, ':') != NULL) {
  5060. return 0;
  5061. }
  5062. if (strchr(domain, ':') != NULL) {
  5063. return 0;
  5064. }
  5065. /* Do not allow control characters like newline in user name and domain.
  5066. * Do not allow excessively long names either. */
  5067. for (i = 0; i < 255 && user[i] != 0; i++) {
  5068. if (iscntrl(user[i])) {
  5069. return 0;
  5070. }
  5071. }
  5072. if (user[i]) {
  5073. return 0;
  5074. }
  5075. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5076. if (iscntrl(domain[i])) {
  5077. return 0;
  5078. }
  5079. }
  5080. if (domain[i]) {
  5081. return 0;
  5082. }
  5083. /* The maximum length of the path to the password file is limited */
  5084. if ((strlen(fname) + 4) >= PATH_MAX) {
  5085. return 0;
  5086. }
  5087. /* Create a temporary file name. Length has been checked before. */
  5088. strcpy(tmp, fname);
  5089. strcat(tmp, ".tmp");
  5090. /* Create the file if does not exist */
  5091. /* Use of fopen here is OK, since fname is only ASCII */
  5092. if ((fp = fopen(fname, "a+")) != NULL) {
  5093. (void)fclose(fp);
  5094. }
  5095. /* Open the given file and temporary file */
  5096. if ((fp = fopen(fname, "r")) == NULL) {
  5097. return 0;
  5098. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5099. fclose(fp);
  5100. return 0;
  5101. }
  5102. /* Copy the stuff to temporary file */
  5103. while (fgets(line, sizeof(line), fp) != NULL) {
  5104. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5105. continue;
  5106. }
  5107. u[255] = 0;
  5108. d[255] = 0;
  5109. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5110. found++;
  5111. if (pass != NULL) {
  5112. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5113. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5114. }
  5115. } else {
  5116. fprintf(fp2, "%s", line);
  5117. }
  5118. }
  5119. /* If new user, just add it */
  5120. if (!found && pass != NULL) {
  5121. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5122. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5123. }
  5124. /* Close files */
  5125. fclose(fp);
  5126. fclose(fp2);
  5127. /* Put the temp file in place of real file */
  5128. IGNORE_UNUSED_RESULT(remove(fname));
  5129. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5130. return 1;
  5131. }
  5132. static int
  5133. is_valid_port(unsigned long port)
  5134. {
  5135. return port < 0xffff;
  5136. }
  5137. static int
  5138. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5139. {
  5140. struct addrinfo hints, *res, *ressave;
  5141. int func_ret = 0;
  5142. int gai_ret;
  5143. memset(&hints, 0, sizeof(struct addrinfo));
  5144. hints.ai_family = af;
  5145. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5146. if (gai_ret != 0) {
  5147. /* gai_strerror could be used to convert gai_ret to a string */
  5148. /* POSIX return values: see
  5149. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5150. */
  5151. /* Windows return values: see
  5152. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5153. */
  5154. return 0;
  5155. }
  5156. ressave = res;
  5157. while (res) {
  5158. if (dstlen >= res->ai_addrlen) {
  5159. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5160. func_ret = 1;
  5161. }
  5162. res = res->ai_next;
  5163. }
  5164. freeaddrinfo(ressave);
  5165. return func_ret;
  5166. }
  5167. static int
  5168. connect_socket(struct mg_context *ctx /* may be NULL */,
  5169. const char *host,
  5170. int port,
  5171. int use_ssl,
  5172. char *ebuf,
  5173. size_t ebuf_len,
  5174. SOCKET *sock /* output: socket, must not be NULL */,
  5175. union usa *sa /* output: socket address, must not be NULL */
  5176. )
  5177. {
  5178. int ip_ver = 0;
  5179. *sock = INVALID_SOCKET;
  5180. memset(sa, 0, sizeof(*sa));
  5181. if (ebuf_len > 0) {
  5182. *ebuf = 0;
  5183. }
  5184. if (host == NULL) {
  5185. mg_snprintf(NULL,
  5186. NULL, /* No truncation check for ebuf */
  5187. ebuf,
  5188. ebuf_len,
  5189. "%s",
  5190. "NULL host");
  5191. return 0;
  5192. }
  5193. if (port < 0 || !is_valid_port((unsigned)port)) {
  5194. mg_snprintf(NULL,
  5195. NULL, /* No truncation check for ebuf */
  5196. ebuf,
  5197. ebuf_len,
  5198. "%s",
  5199. "invalid port");
  5200. return 0;
  5201. }
  5202. #if !defined(NO_SSL)
  5203. if (use_ssl && (SSLv23_client_method == NULL)) {
  5204. mg_snprintf(NULL,
  5205. NULL, /* No truncation check for ebuf */
  5206. ebuf,
  5207. ebuf_len,
  5208. "%s",
  5209. "SSL is not initialized");
  5210. return 0;
  5211. }
  5212. #else
  5213. (void)use_ssl;
  5214. #endif
  5215. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5216. sa->sin.sin_port = htons((uint16_t)port);
  5217. ip_ver = 4;
  5218. #ifdef USE_IPV6
  5219. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5220. sa->sin6.sin6_port = htons((uint16_t)port);
  5221. ip_ver = 6;
  5222. } else if (host[0] == '[') {
  5223. /* While getaddrinfo on Windows will work with [::1],
  5224. * getaddrinfo on Linux only works with ::1 (without []). */
  5225. size_t l = strlen(host + 1);
  5226. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5227. if (h) {
  5228. h[l - 1] = 0;
  5229. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5230. sa->sin6.sin6_port = htons((uint16_t)port);
  5231. ip_ver = 6;
  5232. }
  5233. mg_free(h);
  5234. }
  5235. #endif
  5236. }
  5237. if (ip_ver == 0) {
  5238. mg_snprintf(NULL,
  5239. NULL, /* No truncation check for ebuf */
  5240. ebuf,
  5241. ebuf_len,
  5242. "%s",
  5243. "host not found");
  5244. return 0;
  5245. }
  5246. if (ip_ver == 4) {
  5247. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5248. }
  5249. #ifdef USE_IPV6
  5250. else if (ip_ver == 6) {
  5251. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5252. }
  5253. #endif
  5254. if (*sock == INVALID_SOCKET) {
  5255. mg_snprintf(NULL,
  5256. NULL, /* No truncation check for ebuf */
  5257. ebuf,
  5258. ebuf_len,
  5259. "socket(): %s",
  5260. strerror(ERRNO));
  5261. return 0;
  5262. }
  5263. set_close_on_exec(*sock, fc(ctx));
  5264. if ((ip_ver == 4)
  5265. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5266. == 0)) {
  5267. /* connected with IPv4 */
  5268. return 1;
  5269. }
  5270. #ifdef USE_IPV6
  5271. if ((ip_ver == 6)
  5272. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5273. == 0)) {
  5274. /* connected with IPv6 */
  5275. return 1;
  5276. }
  5277. #endif
  5278. /* Not connected */
  5279. mg_snprintf(NULL,
  5280. NULL, /* No truncation check for ebuf */
  5281. ebuf,
  5282. ebuf_len,
  5283. "connect(%s:%d): %s",
  5284. host,
  5285. port,
  5286. strerror(ERRNO));
  5287. closesocket(*sock);
  5288. *sock = INVALID_SOCKET;
  5289. return 0;
  5290. }
  5291. int
  5292. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5293. {
  5294. static const char *dont_escape = "._-$,;~()";
  5295. static const char *hex = "0123456789abcdef";
  5296. char *pos = dst;
  5297. const char *end = dst + dst_len - 1;
  5298. for (; *src != '\0' && pos < end; src++, pos++) {
  5299. if (isalnum(*(const unsigned char *)src)
  5300. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5301. *pos = *src;
  5302. } else if (pos + 2 < end) {
  5303. pos[0] = '%';
  5304. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5305. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5306. pos += 2;
  5307. } else {
  5308. break;
  5309. }
  5310. }
  5311. *pos = '\0';
  5312. return (*src == '\0') ? (int)(pos - dst) : -1;
  5313. }
  5314. static void
  5315. print_dir_entry(struct de *de)
  5316. {
  5317. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5318. struct tm *tm;
  5319. if (de->file.is_directory) {
  5320. mg_snprintf(de->conn,
  5321. NULL, /* Buffer is big enough */
  5322. size,
  5323. sizeof(size),
  5324. "%s",
  5325. "[DIRECTORY]");
  5326. } else {
  5327. /* We use (signed) cast below because MSVC 6 compiler cannot
  5328. * convert unsigned __int64 to double. Sigh. */
  5329. if (de->file.size < 1024) {
  5330. mg_snprintf(de->conn,
  5331. NULL, /* Buffer is big enough */
  5332. size,
  5333. sizeof(size),
  5334. "%d",
  5335. (int)de->file.size);
  5336. } else if (de->file.size < 0x100000) {
  5337. mg_snprintf(de->conn,
  5338. NULL, /* Buffer is big enough */
  5339. size,
  5340. sizeof(size),
  5341. "%.1fk",
  5342. (double)de->file.size / 1024.0);
  5343. } else if (de->file.size < 0x40000000) {
  5344. mg_snprintf(de->conn,
  5345. NULL, /* Buffer is big enough */
  5346. size,
  5347. sizeof(size),
  5348. "%.1fM",
  5349. (double)de->file.size / 1048576);
  5350. } else {
  5351. mg_snprintf(de->conn,
  5352. NULL, /* Buffer is big enough */
  5353. size,
  5354. sizeof(size),
  5355. "%.1fG",
  5356. (double)de->file.size / 1073741824);
  5357. }
  5358. }
  5359. /* Note: mg_snprintf will not cause a buffer overflow above.
  5360. * So, string truncation checks are not required here. */
  5361. tm = localtime(&de->file.last_modified);
  5362. if (tm != NULL) {
  5363. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5364. } else {
  5365. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5366. mod[sizeof(mod) - 1] = '\0';
  5367. }
  5368. mg_url_encode(de->file_name, href, sizeof(href));
  5369. de->conn->num_bytes_sent +=
  5370. mg_printf(de->conn,
  5371. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5372. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5373. de->conn->request_info.local_uri,
  5374. href,
  5375. de->file.is_directory ? "/" : "",
  5376. de->file_name,
  5377. de->file.is_directory ? "/" : "",
  5378. mod,
  5379. size);
  5380. }
  5381. /* This function is called from send_directory() and used for
  5382. * sorting directory entries by size, or name, or modification time.
  5383. * On windows, __cdecl specification is needed in case if project is built
  5384. * with __stdcall convention. qsort always requires __cdels callback. */
  5385. static int WINCDECL
  5386. compare_dir_entries(const void *p1, const void *p2)
  5387. {
  5388. if (p1 && p2) {
  5389. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5390. const char *query_string = a->conn->request_info.query_string;
  5391. int cmp_result = 0;
  5392. if (query_string == NULL) {
  5393. query_string = "na";
  5394. }
  5395. if (a->file.is_directory && !b->file.is_directory) {
  5396. return -1; /* Always put directories on top */
  5397. } else if (!a->file.is_directory && b->file.is_directory) {
  5398. return 1; /* Always put directories on top */
  5399. } else if (*query_string == 'n') {
  5400. cmp_result = strcmp(a->file_name, b->file_name);
  5401. } else if (*query_string == 's') {
  5402. cmp_result = (a->file.size == b->file.size)
  5403. ? 0
  5404. : ((a->file.size > b->file.size) ? 1 : -1);
  5405. } else if (*query_string == 'd') {
  5406. cmp_result =
  5407. (a->file.last_modified == b->file.last_modified)
  5408. ? 0
  5409. : ((a->file.last_modified > b->file.last_modified) ? 1
  5410. : -1);
  5411. }
  5412. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5413. }
  5414. return 0;
  5415. }
  5416. static int
  5417. must_hide_file(struct mg_connection *conn, const char *path)
  5418. {
  5419. if (conn && conn->ctx) {
  5420. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5421. const char *pattern = conn->ctx->config[HIDE_FILES];
  5422. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5423. || (pattern != NULL
  5424. && match_prefix(pattern, strlen(pattern), path) > 0);
  5425. }
  5426. return 0;
  5427. }
  5428. static int
  5429. scan_directory(struct mg_connection *conn,
  5430. const char *dir,
  5431. void *data,
  5432. void (*cb)(struct de *, void *))
  5433. {
  5434. char path[PATH_MAX];
  5435. struct dirent *dp;
  5436. DIR *dirp;
  5437. struct de de;
  5438. int truncated;
  5439. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5440. return 0;
  5441. } else {
  5442. de.conn = conn;
  5443. while ((dp = mg_readdir(dirp)) != NULL) {
  5444. /* Do not show current dir and hidden files */
  5445. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5446. || must_hide_file(conn, dp->d_name)) {
  5447. continue;
  5448. }
  5449. mg_snprintf(
  5450. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5451. /* If we don't memset stat structure to zero, mtime will have
  5452. * garbage and strftime() will segfault later on in
  5453. * print_dir_entry(). memset is required only if mg_stat()
  5454. * fails. For more details, see
  5455. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5456. memset(&de.file, 0, sizeof(de.file));
  5457. if (truncated) {
  5458. /* If the path is not complete, skip processing. */
  5459. continue;
  5460. }
  5461. if (!mg_stat(conn, path, &de.file)) {
  5462. mg_cry(conn,
  5463. "%s: mg_stat(%s) failed: %s",
  5464. __func__,
  5465. path,
  5466. strerror(ERRNO));
  5467. }
  5468. de.file_name = dp->d_name;
  5469. cb(&de, data);
  5470. }
  5471. (void)mg_closedir(dirp);
  5472. }
  5473. return 1;
  5474. }
  5475. #if !defined(NO_FILES)
  5476. static int
  5477. remove_directory(struct mg_connection *conn, const char *dir)
  5478. {
  5479. char path[PATH_MAX];
  5480. struct dirent *dp;
  5481. DIR *dirp;
  5482. struct de de;
  5483. int truncated;
  5484. int ok = 1;
  5485. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5486. return 0;
  5487. } else {
  5488. de.conn = conn;
  5489. while ((dp = mg_readdir(dirp)) != NULL) {
  5490. /* Do not show current dir (but show hidden files as they will
  5491. * also be removed) */
  5492. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5493. continue;
  5494. }
  5495. mg_snprintf(
  5496. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5497. /* If we don't memset stat structure to zero, mtime will have
  5498. * garbage and strftime() will segfault later on in
  5499. * print_dir_entry(). memset is required only if mg_stat()
  5500. * fails. For more details, see
  5501. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5502. memset(&de.file, 0, sizeof(de.file));
  5503. if (truncated) {
  5504. /* Do not delete anything shorter */
  5505. ok = 0;
  5506. continue;
  5507. }
  5508. if (!mg_stat(conn, path, &de.file)) {
  5509. mg_cry(conn,
  5510. "%s: mg_stat(%s) failed: %s",
  5511. __func__,
  5512. path,
  5513. strerror(ERRNO));
  5514. ok = 0;
  5515. }
  5516. if (de.file.membuf == NULL) {
  5517. /* file is not in memory */
  5518. if (de.file.is_directory) {
  5519. if (remove_directory(conn, path) == 0) {
  5520. ok = 0;
  5521. }
  5522. } else {
  5523. if (mg_remove(conn, path) == 0) {
  5524. ok = 0;
  5525. }
  5526. }
  5527. } else {
  5528. /* file is in memory. It can not be deleted. */
  5529. ok = 0;
  5530. }
  5531. }
  5532. (void)mg_closedir(dirp);
  5533. IGNORE_UNUSED_RESULT(rmdir(dir));
  5534. }
  5535. return ok;
  5536. }
  5537. #endif
  5538. struct dir_scan_data {
  5539. struct de *entries;
  5540. unsigned int num_entries;
  5541. unsigned int arr_size;
  5542. };
  5543. /* Behaves like realloc(), but frees original pointer on failure */
  5544. static void *
  5545. realloc2(void *ptr, size_t size)
  5546. {
  5547. void *new_ptr = mg_realloc(ptr, size);
  5548. if (new_ptr == NULL) {
  5549. mg_free(ptr);
  5550. }
  5551. return new_ptr;
  5552. }
  5553. static void
  5554. dir_scan_callback(struct de *de, void *data)
  5555. {
  5556. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5557. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5558. dsd->arr_size *= 2;
  5559. dsd->entries =
  5560. (struct de *)realloc2(dsd->entries,
  5561. dsd->arr_size * sizeof(dsd->entries[0]));
  5562. }
  5563. if (dsd->entries == NULL) {
  5564. /* TODO(lsm, low): propagate an error to the caller */
  5565. dsd->num_entries = 0;
  5566. } else {
  5567. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5568. dsd->entries[dsd->num_entries].file = de->file;
  5569. dsd->entries[dsd->num_entries].conn = de->conn;
  5570. dsd->num_entries++;
  5571. }
  5572. }
  5573. static void
  5574. handle_directory_request(struct mg_connection *conn, const char *dir)
  5575. {
  5576. unsigned int i;
  5577. int sort_direction;
  5578. struct dir_scan_data data = {NULL, 0, 128};
  5579. char date[64];
  5580. time_t curtime = time(NULL);
  5581. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5582. send_http_error(conn,
  5583. 500,
  5584. "Error: Cannot open directory\nopendir(%s): %s",
  5585. dir,
  5586. strerror(ERRNO));
  5587. return;
  5588. }
  5589. gmt_time_string(date, sizeof(date), &curtime);
  5590. if (!conn) {
  5591. return;
  5592. }
  5593. sort_direction = ((conn->request_info.query_string != NULL)
  5594. && (conn->request_info.query_string[1] == 'd'))
  5595. ? 'a'
  5596. : 'd';
  5597. conn->must_close = 1;
  5598. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5599. send_static_cache_header(conn);
  5600. mg_printf(conn,
  5601. "Date: %s\r\n"
  5602. "Connection: close\r\n"
  5603. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5604. date);
  5605. conn->num_bytes_sent +=
  5606. mg_printf(conn,
  5607. "<html><head><title>Index of %s</title>"
  5608. "<style>th {text-align: left;}</style></head>"
  5609. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5610. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5611. "<th><a href=\"?d%c\">Modified</a></th>"
  5612. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5613. "<tr><td colspan=\"3\"><hr></td></tr>",
  5614. conn->request_info.local_uri,
  5615. conn->request_info.local_uri,
  5616. sort_direction,
  5617. sort_direction,
  5618. sort_direction);
  5619. /* Print first entry - link to a parent directory */
  5620. conn->num_bytes_sent +=
  5621. mg_printf(conn,
  5622. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5623. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5624. conn->request_info.local_uri,
  5625. "..",
  5626. "Parent directory",
  5627. "-",
  5628. "-");
  5629. /* Sort and print directory entries */
  5630. if (data.entries != NULL) {
  5631. qsort(data.entries,
  5632. (size_t)data.num_entries,
  5633. sizeof(data.entries[0]),
  5634. compare_dir_entries);
  5635. for (i = 0; i < data.num_entries; i++) {
  5636. print_dir_entry(&data.entries[i]);
  5637. mg_free(data.entries[i].file_name);
  5638. }
  5639. mg_free(data.entries);
  5640. }
  5641. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5642. conn->status_code = 200;
  5643. }
  5644. /* Send len bytes from the opened file to the client. */
  5645. static void
  5646. send_file_data(struct mg_connection *conn,
  5647. struct file *filep,
  5648. int64_t offset,
  5649. int64_t len)
  5650. {
  5651. char buf[MG_BUF_LEN];
  5652. int to_read, num_read, num_written;
  5653. int64_t size;
  5654. if (!filep || !conn) {
  5655. return;
  5656. }
  5657. /* Sanity check the offset */
  5658. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5659. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5660. if (len > 0 && filep->membuf != NULL && size > 0) {
  5661. /* file stored in memory */
  5662. if (len > size - offset) {
  5663. len = size - offset;
  5664. }
  5665. mg_write(conn, filep->membuf + offset, (size_t)len);
  5666. } else if (len > 0 && filep->fp != NULL) {
  5667. /* file stored on disk */
  5668. #if defined(__linux__)
  5669. /* sendfile is only available for Linux */
  5670. if (conn->throttle == 0 && conn->ssl == 0) {
  5671. off_t sf_offs = (off_t)offset;
  5672. ssize_t sf_sent;
  5673. int sf_file = fileno(filep->fp);
  5674. int loop_cnt = 0;
  5675. do {
  5676. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5677. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5678. size_t sf_tosend =
  5679. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5680. sf_sent =
  5681. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5682. if (sf_sent > 0) {
  5683. conn->num_bytes_sent += sf_sent;
  5684. len -= sf_sent;
  5685. offset += sf_sent;
  5686. } else if (loop_cnt == 0) {
  5687. /* This file can not be sent using sendfile.
  5688. * This might be the case for pseudo-files in the
  5689. * /sys/ and /proc/ file system.
  5690. * Use the regular user mode copy code instead. */
  5691. break;
  5692. } else if (sf_sent == 0) {
  5693. /* No error, but 0 bytes sent. May be EOF? */
  5694. return;
  5695. }
  5696. loop_cnt++;
  5697. } while ((len > 0) && (sf_sent >= 0));
  5698. if (sf_sent > 0) {
  5699. return; /* OK */
  5700. }
  5701. /* sf_sent<0 means error, thus fall back to the classic way */
  5702. /* This is always the case, if sf_file is not a "normal" file,
  5703. * e.g., for sending data from the output of a CGI process. */
  5704. offset = (int64_t)sf_offs;
  5705. }
  5706. #endif
  5707. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5708. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5709. send_http_error(
  5710. conn,
  5711. 500,
  5712. "%s",
  5713. "Error: Unable to access file at requested position.");
  5714. } else {
  5715. while (len > 0) {
  5716. /* Calculate how much to read from the file in the buffer */
  5717. to_read = sizeof(buf);
  5718. if ((int64_t)to_read > len) {
  5719. to_read = (int)len;
  5720. }
  5721. /* Read from file, exit the loop on error */
  5722. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5723. <= 0) {
  5724. break;
  5725. }
  5726. /* Send read bytes to the client, exit the loop on error */
  5727. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5728. != num_read) {
  5729. break;
  5730. }
  5731. /* Both read and were successful, adjust counters */
  5732. conn->num_bytes_sent += num_written;
  5733. len -= num_written;
  5734. }
  5735. }
  5736. }
  5737. }
  5738. static int
  5739. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5740. {
  5741. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5742. }
  5743. static void
  5744. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5745. {
  5746. if (filep != NULL && buf != NULL) {
  5747. mg_snprintf(NULL,
  5748. NULL, /* All calls to construct_etag use 64 byte buffer */
  5749. buf,
  5750. buf_len,
  5751. "\"%lx.%" INT64_FMT "\"",
  5752. (unsigned long)filep->last_modified,
  5753. filep->size);
  5754. }
  5755. }
  5756. static void
  5757. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5758. {
  5759. if (filep != NULL && filep->fp != NULL) {
  5760. #ifdef _WIN32
  5761. (void)conn; /* Unused. */
  5762. #else
  5763. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5764. mg_cry(conn,
  5765. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5766. __func__,
  5767. strerror(ERRNO));
  5768. }
  5769. #endif
  5770. }
  5771. }
  5772. static void
  5773. handle_static_file_request(struct mg_connection *conn,
  5774. const char *path,
  5775. struct file *filep,
  5776. const char *mime_type)
  5777. {
  5778. char date[64], lm[64], etag[64];
  5779. char range[128]; /* large enough, so there will be no overflow */
  5780. const char *msg = "OK", *hdr;
  5781. time_t curtime = time(NULL);
  5782. int64_t cl, r1, r2;
  5783. struct vec mime_vec;
  5784. int n, truncated;
  5785. char gz_path[PATH_MAX];
  5786. const char *encoding = "";
  5787. const char *cors1, *cors2, *cors3;
  5788. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5789. return;
  5790. }
  5791. if (mime_type == NULL) {
  5792. get_mime_type(conn->ctx, path, &mime_vec);
  5793. } else {
  5794. mime_vec.ptr = mime_type;
  5795. mime_vec.len = strlen(mime_type);
  5796. }
  5797. if (filep->size > INT64_MAX) {
  5798. send_http_error(conn,
  5799. 500,
  5800. "Error: File size is too large to send\n%" INT64_FMT,
  5801. filep->size);
  5802. }
  5803. cl = (int64_t)filep->size;
  5804. conn->status_code = 200;
  5805. range[0] = '\0';
  5806. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5807. * it's important to rewrite the filename after resolving
  5808. * the mime type from it, to preserve the actual file's type */
  5809. if (filep->gzipped) {
  5810. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5811. if (truncated) {
  5812. send_http_error(conn,
  5813. 500,
  5814. "Error: Path of zipped file too long (%s)",
  5815. path);
  5816. return;
  5817. }
  5818. path = gz_path;
  5819. encoding = "Content-Encoding: gzip\r\n";
  5820. }
  5821. if (!mg_fopen(conn, path, "rb", filep)) {
  5822. send_http_error(conn,
  5823. 500,
  5824. "Error: Cannot open file\nfopen(%s): %s",
  5825. path,
  5826. strerror(ERRNO));
  5827. return;
  5828. }
  5829. fclose_on_exec(filep, conn);
  5830. /* If Range: header specified, act accordingly */
  5831. r1 = r2 = 0;
  5832. hdr = mg_get_header(conn, "Range");
  5833. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5834. && r2 >= 0) {
  5835. /* actually, range requests don't play well with a pre-gzipped
  5836. * file (since the range is specified in the uncompressed space) */
  5837. if (filep->gzipped) {
  5838. send_http_error(
  5839. conn,
  5840. 501,
  5841. "%s",
  5842. "Error: Range requests in gzipped files are not supported");
  5843. mg_fclose(filep);
  5844. return;
  5845. }
  5846. conn->status_code = 206;
  5847. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5848. mg_snprintf(conn,
  5849. NULL, /* range buffer is big enough */
  5850. range,
  5851. sizeof(range),
  5852. "Content-Range: bytes "
  5853. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5854. r1,
  5855. r1 + cl - 1,
  5856. filep->size);
  5857. msg = "Partial Content";
  5858. }
  5859. hdr = mg_get_header(conn, "Origin");
  5860. if (hdr) {
  5861. /* Cross-origin resource sharing (CORS), see
  5862. * http://www.html5rocks.com/en/tutorials/cors/,
  5863. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5864. * preflight is not supported for files. */
  5865. cors1 = "Access-Control-Allow-Origin: ";
  5866. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5867. cors3 = "\r\n";
  5868. } else {
  5869. cors1 = cors2 = cors3 = "";
  5870. }
  5871. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5872. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5873. gmt_time_string(date, sizeof(date), &curtime);
  5874. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5875. construct_etag(etag, sizeof(etag), filep);
  5876. (void)mg_printf(conn,
  5877. "HTTP/1.1 %d %s\r\n"
  5878. "%s%s%s"
  5879. "Date: %s\r\n",
  5880. conn->status_code,
  5881. msg,
  5882. cors1,
  5883. cors2,
  5884. cors3,
  5885. date);
  5886. send_static_cache_header(conn);
  5887. (void)mg_printf(conn,
  5888. "Last-Modified: %s\r\n"
  5889. "Etag: %s\r\n"
  5890. "Content-Type: %.*s\r\n"
  5891. "Content-Length: %" INT64_FMT "\r\n"
  5892. "Connection: %s\r\n"
  5893. "Accept-Ranges: bytes\r\n"
  5894. "%s%s\r\n",
  5895. lm,
  5896. etag,
  5897. (int)mime_vec.len,
  5898. mime_vec.ptr,
  5899. cl,
  5900. suggest_connection_header(conn),
  5901. range,
  5902. encoding);
  5903. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5904. send_file_data(conn, filep, r1, cl);
  5905. }
  5906. mg_fclose(filep);
  5907. }
  5908. #if !defined(NO_CACHING)
  5909. static void
  5910. handle_not_modified_static_file_request(struct mg_connection *conn,
  5911. struct file *filep)
  5912. {
  5913. char date[64], lm[64], etag[64];
  5914. time_t curtime = time(NULL);
  5915. if (conn == NULL || filep == NULL) {
  5916. return;
  5917. }
  5918. conn->status_code = 304;
  5919. gmt_time_string(date, sizeof(date), &curtime);
  5920. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5921. construct_etag(etag, sizeof(etag), filep);
  5922. (void)mg_printf(conn,
  5923. "HTTP/1.1 %d %s\r\n"
  5924. "Date: %s\r\n",
  5925. conn->status_code,
  5926. mg_get_response_code_text(conn, conn->status_code),
  5927. date);
  5928. send_static_cache_header(conn);
  5929. (void)mg_printf(conn,
  5930. "Last-Modified: %s\r\n"
  5931. "Etag: %s\r\n"
  5932. "Connection: %s\r\n"
  5933. "\r\n",
  5934. lm,
  5935. etag,
  5936. suggest_connection_header(conn));
  5937. }
  5938. #endif
  5939. void
  5940. mg_send_file(struct mg_connection *conn, const char *path)
  5941. {
  5942. mg_send_mime_file(conn, path, NULL);
  5943. }
  5944. void
  5945. mg_send_mime_file(struct mg_connection *conn,
  5946. const char *path,
  5947. const char *mime_type)
  5948. {
  5949. struct file file = STRUCT_FILE_INITIALIZER;
  5950. if (mg_stat(conn, path, &file)) {
  5951. if (file.is_directory) {
  5952. if (!conn) {
  5953. return;
  5954. }
  5955. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5956. "yes")) {
  5957. handle_directory_request(conn, path);
  5958. } else {
  5959. send_http_error(conn,
  5960. 403,
  5961. "%s",
  5962. "Error: Directory listing denied");
  5963. }
  5964. } else {
  5965. handle_static_file_request(conn, path, &file, mime_type);
  5966. }
  5967. } else {
  5968. send_http_error(conn, 404, "%s", "Error: File not found");
  5969. }
  5970. }
  5971. /* For a given PUT path, create all intermediate subdirectories.
  5972. * Return 0 if the path itself is a directory.
  5973. * Return 1 if the path leads to a file.
  5974. * Return -1 for if the path is too long.
  5975. * Return -2 if path can not be created.
  5976. */
  5977. static int
  5978. put_dir(struct mg_connection *conn, const char *path)
  5979. {
  5980. char buf[PATH_MAX];
  5981. const char *s, *p;
  5982. struct file file = STRUCT_FILE_INITIALIZER;
  5983. size_t len;
  5984. int res = 1;
  5985. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5986. len = (size_t)(p - path);
  5987. if (len >= sizeof(buf)) {
  5988. /* path too long */
  5989. res = -1;
  5990. break;
  5991. }
  5992. memcpy(buf, path, len);
  5993. buf[len] = '\0';
  5994. /* Try to create intermediate directory */
  5995. DEBUG_TRACE("mkdir(%s)", buf);
  5996. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  5997. /* path does not exixt and can not be created */
  5998. res = -2;
  5999. break;
  6000. }
  6001. /* Is path itself a directory? */
  6002. if (p[1] == '\0') {
  6003. res = 0;
  6004. }
  6005. }
  6006. return res;
  6007. }
  6008. static void
  6009. remove_bad_file(const struct mg_connection *conn, const char *path)
  6010. {
  6011. int r = mg_remove(conn, path);
  6012. if (r != 0) {
  6013. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6014. }
  6015. }
  6016. long long
  6017. mg_store_body(struct mg_connection *conn, const char *path)
  6018. {
  6019. char buf[MG_BUF_LEN];
  6020. long long len = 0;
  6021. int ret, n;
  6022. struct file fi;
  6023. if (conn->consumed_content != 0) {
  6024. mg_cry(conn, "%s: Contents already consumed", __func__);
  6025. return -11;
  6026. }
  6027. ret = put_dir(conn, path);
  6028. if (ret < 0) {
  6029. /* -1 for path too long,
  6030. * -2 for path can not be created. */
  6031. return ret;
  6032. }
  6033. if (ret != 1) {
  6034. /* Return 0 means, path itself is a directory. */
  6035. return 0;
  6036. }
  6037. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6038. return -12;
  6039. }
  6040. ret = mg_read(conn, buf, sizeof(buf));
  6041. while (ret > 0) {
  6042. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6043. if (n != ret) {
  6044. mg_fclose(&fi);
  6045. remove_bad_file(conn, path);
  6046. return -13;
  6047. }
  6048. ret = mg_read(conn, buf, sizeof(buf));
  6049. }
  6050. /* TODO: mg_fclose should return an error,
  6051. * and every caller should check and handle it. */
  6052. if (fclose(fi.fp) != 0) {
  6053. remove_bad_file(conn, path);
  6054. return -14;
  6055. }
  6056. return len;
  6057. }
  6058. /* Parse HTTP headers from the given buffer, advance buf pointer
  6059. * to the point where parsing stopped.
  6060. * All parameters must be valid pointers (not NULL).
  6061. * Return <0 on error. */
  6062. static int
  6063. parse_http_headers(char **buf, struct mg_request_info *ri)
  6064. {
  6065. int i;
  6066. ri->num_headers = 0;
  6067. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6068. char *dp = *buf;
  6069. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6070. dp++;
  6071. }
  6072. if (dp == *buf) {
  6073. /* End of headers reached. */
  6074. break;
  6075. }
  6076. if (*dp != ':') {
  6077. /* This is not a valid field. */
  6078. return -1;
  6079. }
  6080. /* End of header key (*dp == ':') */
  6081. /* Truncate here and set the key name */
  6082. *dp = 0;
  6083. ri->http_headers[i].name = *buf;
  6084. do {
  6085. dp++;
  6086. } while (*dp == ' ');
  6087. /* The rest of the line is the value */
  6088. ri->http_headers[i].value = dp;
  6089. *buf = dp + strcspn(dp, "\r\n");
  6090. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6091. *buf = NULL;
  6092. }
  6093. ri->num_headers = i + 1;
  6094. if (*buf) {
  6095. (*buf)[0] = 0;
  6096. (*buf)[1] = 0;
  6097. *buf += 2;
  6098. } else {
  6099. *buf = dp;
  6100. break;
  6101. }
  6102. if ((*buf)[0] == '\r') {
  6103. /* This is the end of the header */
  6104. break;
  6105. }
  6106. }
  6107. return ri->num_headers;
  6108. }
  6109. static int
  6110. is_valid_http_method(const char *method)
  6111. {
  6112. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6113. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6114. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6115. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6116. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6117. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6118. /* TRACE method (RFC 2616) is not supported for security reasons */
  6119. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6120. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6121. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6122. /* Unsupported WEBDAV Methods: */
  6123. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6124. /* + 11 methods from RFC 3253 */
  6125. /* ORDERPATCH (RFC 3648) */
  6126. /* ACL (RFC 3744) */
  6127. /* SEARCH (RFC 5323) */
  6128. /* + MicroSoft extensions
  6129. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6130. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6131. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6132. }
  6133. /* Parse HTTP request, fill in mg_request_info structure.
  6134. * This function modifies the buffer by NUL-terminating
  6135. * HTTP request components, header names and header values.
  6136. * Parameters:
  6137. * buf (in/out): pointer to the HTTP header to parse and split
  6138. * len (in): length of HTTP header buffer
  6139. * re (out): parsed header as mg_request_info
  6140. * buf and ri must be valid pointers (not NULL), len>0.
  6141. * Returns <0 on error. */
  6142. static int
  6143. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6144. {
  6145. int is_request, request_length;
  6146. char *start_line;
  6147. request_length = get_request_len(buf, len);
  6148. if (request_length > 0) {
  6149. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6150. * remote_port */
  6151. ri->remote_user = ri->request_method = ri->request_uri =
  6152. ri->http_version = NULL;
  6153. ri->num_headers = 0;
  6154. buf[request_length - 1] = '\0';
  6155. /* RFC says that all initial whitespaces should be ingored */
  6156. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6157. buf++;
  6158. }
  6159. start_line = skip(&buf, "\r\n");
  6160. ri->request_method = skip(&start_line, " ");
  6161. ri->request_uri = skip(&start_line, " ");
  6162. ri->http_version = start_line;
  6163. /* HTTP message could be either HTTP request:
  6164. * "GET / HTTP/1.0 ..."
  6165. * or a HTTP response:
  6166. * "HTTP/1.0 200 OK ..."
  6167. * otherwise it is invalid.
  6168. */
  6169. is_request = is_valid_http_method(ri->request_method);
  6170. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6171. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6172. /* Not a valid request or response: invalid */
  6173. return -1;
  6174. }
  6175. if (is_request) {
  6176. ri->http_version += 5;
  6177. }
  6178. if (parse_http_headers(&buf, ri) < 0) {
  6179. /* Error while parsing headers */
  6180. return -1;
  6181. }
  6182. }
  6183. return request_length;
  6184. }
  6185. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6186. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6187. * buffer (which marks the end of HTTP request). Buffer buf may already
  6188. * have some data. The length of the data is stored in nread.
  6189. * Upon every read operation, increase nread by the number of bytes read. */
  6190. static int
  6191. read_request(FILE *fp,
  6192. struct mg_connection *conn,
  6193. char *buf,
  6194. int bufsiz,
  6195. int *nread)
  6196. {
  6197. int request_len, n = 0;
  6198. struct timespec last_action_time;
  6199. double request_timeout;
  6200. if (!conn) {
  6201. return 0;
  6202. }
  6203. memset(&last_action_time, 0, sizeof(last_action_time));
  6204. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6205. /* value of request_timeout is in seconds, config in milliseconds */
  6206. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6207. } else {
  6208. request_timeout = -1.0;
  6209. }
  6210. request_len = get_request_len(buf, *nread);
  6211. /* first time reading from this connection */
  6212. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6213. while (
  6214. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6215. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6216. <= request_timeout) || (request_timeout < 0))
  6217. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6218. > 0)) {
  6219. *nread += n;
  6220. /* assert(*nread <= bufsiz); */
  6221. if (*nread > bufsiz) {
  6222. return -2;
  6223. }
  6224. request_len = get_request_len(buf, *nread);
  6225. if (request_timeout > 0.0) {
  6226. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6227. }
  6228. }
  6229. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6230. }
  6231. #if !defined(NO_FILES)
  6232. /* For given directory path, substitute it to valid index file.
  6233. * Return 1 if index file has been found, 0 if not found.
  6234. * If the file is found, it's stats is returned in stp. */
  6235. static int
  6236. substitute_index_file(struct mg_connection *conn,
  6237. char *path,
  6238. size_t path_len,
  6239. struct file *filep)
  6240. {
  6241. if (conn && conn->ctx) {
  6242. const char *list = conn->ctx->config[INDEX_FILES];
  6243. struct file file = STRUCT_FILE_INITIALIZER;
  6244. struct vec filename_vec;
  6245. size_t n = strlen(path);
  6246. int found = 0;
  6247. /* The 'path' given to us points to the directory. Remove all trailing
  6248. * directory separator characters from the end of the path, and
  6249. * then append single directory separator character. */
  6250. while (n > 0 && path[n - 1] == '/') {
  6251. n--;
  6252. }
  6253. path[n] = '/';
  6254. /* Traverse index files list. For each entry, append it to the given
  6255. * path and see if the file exists. If it exists, break the loop */
  6256. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6257. /* Ignore too long entries that may overflow path buffer */
  6258. if (filename_vec.len > path_len - (n + 2)) {
  6259. continue;
  6260. }
  6261. /* Prepare full path to the index file */
  6262. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6263. /* Does it exist? */
  6264. if (mg_stat(conn, path, &file)) {
  6265. /* Yes it does, break the loop */
  6266. *filep = file;
  6267. found = 1;
  6268. break;
  6269. }
  6270. }
  6271. /* If no index file exists, restore directory path */
  6272. if (!found) {
  6273. path[n] = '\0';
  6274. }
  6275. return found;
  6276. }
  6277. return 0;
  6278. }
  6279. #endif
  6280. #if !defined(NO_CACHING)
  6281. /* Return True if we should reply 304 Not Modified. */
  6282. static int
  6283. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6284. {
  6285. char etag[64];
  6286. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6287. const char *inm = mg_get_header(conn, "If-None-Match");
  6288. construct_etag(etag, sizeof(etag), filep);
  6289. if (!filep) {
  6290. return 0;
  6291. }
  6292. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6293. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6294. }
  6295. #endif /* !NO_CACHING */
  6296. #if !defined(NO_CGI) || !defined(NO_FILES)
  6297. static int
  6298. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6299. {
  6300. const char *expect, *body;
  6301. char buf[MG_BUF_LEN];
  6302. int to_read, nread, success = 0;
  6303. int64_t buffered_len;
  6304. double timeout = -1.0;
  6305. if (!conn) {
  6306. return 0;
  6307. }
  6308. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6309. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6310. }
  6311. expect = mg_get_header(conn, "Expect");
  6312. /* assert(fp != NULL); */
  6313. if (!fp) {
  6314. send_http_error(conn, 500, "%s", "Error: NULL File");
  6315. return 0;
  6316. }
  6317. if (conn->content_len == -1 && !conn->is_chunked) {
  6318. /* Content length is not specified by the client. */
  6319. send_http_error(conn,
  6320. 411,
  6321. "%s",
  6322. "Error: Client did not specify content length");
  6323. } else if ((expect != NULL)
  6324. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6325. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6326. send_http_error(conn,
  6327. 417,
  6328. "Error: Can not fulfill expectation %s",
  6329. expect);
  6330. } else {
  6331. if (expect != NULL) {
  6332. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6333. conn->status_code = 100;
  6334. } else {
  6335. conn->status_code = 200;
  6336. }
  6337. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6338. - conn->consumed_content;
  6339. /* assert(buffered_len >= 0); */
  6340. /* assert(conn->consumed_content == 0); */
  6341. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6342. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6343. return 0;
  6344. }
  6345. if (buffered_len > 0) {
  6346. if ((int64_t)buffered_len > conn->content_len) {
  6347. buffered_len = (int)conn->content_len;
  6348. }
  6349. body = conn->buf + conn->request_len + conn->consumed_content;
  6350. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6351. conn->consumed_content += buffered_len;
  6352. }
  6353. nread = 0;
  6354. while (conn->consumed_content < conn->content_len) {
  6355. to_read = sizeof(buf);
  6356. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6357. to_read = (int)(conn->content_len - conn->consumed_content);
  6358. }
  6359. nread = pull(NULL, conn, buf, to_read, timeout);
  6360. if (nread <= 0
  6361. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6362. break;
  6363. }
  6364. conn->consumed_content += nread;
  6365. }
  6366. if (conn->consumed_content == conn->content_len) {
  6367. success = (nread >= 0);
  6368. }
  6369. /* Each error code path in this function must send an error */
  6370. if (!success) {
  6371. /* NOTE: Maybe some data has already been sent. */
  6372. /* TODO (low): If some data has been sent, a correct error
  6373. * reply can no longer be sent, so just close the connection */
  6374. send_http_error(conn, 500, "%s", "");
  6375. }
  6376. }
  6377. return success;
  6378. }
  6379. #endif
  6380. #if !defined(NO_CGI)
  6381. /* This structure helps to create an environment for the spawned CGI program.
  6382. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6383. * last element must be NULL.
  6384. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6385. * strings must reside in a contiguous buffer. The end of the buffer is
  6386. * marked by two '\0' characters.
  6387. * We satisfy both worlds: we create an envp array (which is vars), all
  6388. * entries are actually pointers inside buf. */
  6389. struct cgi_environment {
  6390. struct mg_connection *conn;
  6391. /* Data block */
  6392. char *buf; /* Environment buffer */
  6393. size_t buflen; /* Space available in buf */
  6394. size_t bufused; /* Space taken in buf */
  6395. /* Index block */
  6396. char **var; /* char **envp */
  6397. size_t varlen; /* Number of variables available in var */
  6398. size_t varused; /* Number of variables stored in var */
  6399. };
  6400. static void addenv(struct cgi_environment *env,
  6401. PRINTF_FORMAT_STRING(const char *fmt),
  6402. ...) PRINTF_ARGS(2, 3);
  6403. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6404. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6405. static void
  6406. addenv(struct cgi_environment *env, const char *fmt, ...)
  6407. {
  6408. size_t n, space;
  6409. int truncated;
  6410. char *added;
  6411. va_list ap;
  6412. /* Calculate how much space is left in the buffer */
  6413. space = (env->buflen - env->bufused);
  6414. /* Calculate an estimate for the required space */
  6415. n = strlen(fmt) + 2 + 128;
  6416. do {
  6417. if (space <= n) {
  6418. /* Allocate new buffer */
  6419. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6420. added = (char *)mg_realloc(env->buf, n);
  6421. if (!added) {
  6422. /* Out of memory */
  6423. mg_cry(env->conn,
  6424. "%s: Cannot allocate memory for CGI variable [%s]",
  6425. __func__,
  6426. fmt);
  6427. return;
  6428. }
  6429. env->buf = added;
  6430. env->buflen = n;
  6431. space = (env->buflen - env->bufused);
  6432. }
  6433. /* Make a pointer to the free space int the buffer */
  6434. added = env->buf + env->bufused;
  6435. /* Copy VARIABLE=VALUE\0 string into the free space */
  6436. va_start(ap, fmt);
  6437. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6438. va_end(ap);
  6439. /* Do not add truncated strings to the environment */
  6440. if (truncated) {
  6441. /* Reallocate the buffer */
  6442. space = 0;
  6443. n = 1;
  6444. }
  6445. } while (truncated);
  6446. /* Calculate number of bytes added to the environment */
  6447. n = strlen(added) + 1;
  6448. env->bufused += n;
  6449. /* Now update the variable index */
  6450. space = (env->varlen - env->varused);
  6451. if (space < 2) {
  6452. mg_cry(env->conn,
  6453. "%s: Cannot register CGI variable [%s]",
  6454. __func__,
  6455. fmt);
  6456. return;
  6457. }
  6458. /* Append a pointer to the added string into the envp array */
  6459. env->var[env->varused] = added;
  6460. env->varused++;
  6461. }
  6462. static void
  6463. prepare_cgi_environment(struct mg_connection *conn,
  6464. const char *prog,
  6465. struct cgi_environment *env)
  6466. {
  6467. const char *s;
  6468. struct vec var_vec;
  6469. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6470. int i, truncated;
  6471. if (conn == NULL || prog == NULL || env == NULL) {
  6472. return;
  6473. }
  6474. env->conn = conn;
  6475. env->buflen = CGI_ENVIRONMENT_SIZE;
  6476. env->bufused = 0;
  6477. env->buf = (char *)mg_malloc(env->buflen);
  6478. env->varlen = MAX_CGI_ENVIR_VARS;
  6479. env->varused = 0;
  6480. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6481. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6482. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6483. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6484. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6485. /* Prepare the environment block */
  6486. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6487. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6488. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6489. #if defined(USE_IPV6)
  6490. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6491. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6492. } else
  6493. #endif
  6494. {
  6495. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6496. }
  6497. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6498. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6499. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6500. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6501. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6502. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6503. /* SCRIPT_NAME */
  6504. addenv(env,
  6505. "SCRIPT_NAME=%.*s",
  6506. (int)strlen(conn->request_info.local_uri)
  6507. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6508. conn->request_info.local_uri);
  6509. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6510. if (conn->path_info == NULL) {
  6511. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6512. } else {
  6513. addenv(env,
  6514. "PATH_TRANSLATED=%s%s",
  6515. conn->ctx->config[DOCUMENT_ROOT],
  6516. conn->path_info);
  6517. }
  6518. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6519. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6520. addenv(env, "CONTENT_TYPE=%s", s);
  6521. }
  6522. if (conn->request_info.query_string != NULL) {
  6523. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6524. }
  6525. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6526. addenv(env, "CONTENT_LENGTH=%s", s);
  6527. }
  6528. if ((s = getenv("PATH")) != NULL) {
  6529. addenv(env, "PATH=%s", s);
  6530. }
  6531. if (conn->path_info != NULL) {
  6532. addenv(env, "PATH_INFO=%s", conn->path_info);
  6533. }
  6534. if (conn->status_code > 0) {
  6535. /* CGI error handler should show the status code */
  6536. addenv(env, "STATUS=%d", conn->status_code);
  6537. }
  6538. #if defined(_WIN32)
  6539. if ((s = getenv("COMSPEC")) != NULL) {
  6540. addenv(env, "COMSPEC=%s", s);
  6541. }
  6542. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6543. addenv(env, "SYSTEMROOT=%s", s);
  6544. }
  6545. if ((s = getenv("SystemDrive")) != NULL) {
  6546. addenv(env, "SystemDrive=%s", s);
  6547. }
  6548. if ((s = getenv("ProgramFiles")) != NULL) {
  6549. addenv(env, "ProgramFiles=%s", s);
  6550. }
  6551. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6552. addenv(env, "ProgramFiles(x86)=%s", s);
  6553. }
  6554. #else
  6555. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6556. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6557. }
  6558. #endif /* _WIN32 */
  6559. if ((s = getenv("PERLLIB")) != NULL) {
  6560. addenv(env, "PERLLIB=%s", s);
  6561. }
  6562. if (conn->request_info.remote_user != NULL) {
  6563. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6564. addenv(env, "%s", "AUTH_TYPE=Digest");
  6565. }
  6566. /* Add all headers as HTTP_* variables */
  6567. for (i = 0; i < conn->request_info.num_headers; i++) {
  6568. (void)mg_snprintf(conn,
  6569. &truncated,
  6570. http_var_name,
  6571. sizeof(http_var_name),
  6572. "HTTP_%s",
  6573. conn->request_info.http_headers[i].name);
  6574. if (truncated) {
  6575. mg_cry(conn,
  6576. "%s: HTTP header variable too long [%s]",
  6577. __func__,
  6578. conn->request_info.http_headers[i].name);
  6579. continue;
  6580. }
  6581. /* Convert variable name into uppercase, and change - to _ */
  6582. for (p = http_var_name; *p != '\0'; p++) {
  6583. if (*p == '-') {
  6584. *p = '_';
  6585. }
  6586. *p = (char)toupper(*(unsigned char *)p);
  6587. }
  6588. addenv(env,
  6589. "%s=%s",
  6590. http_var_name,
  6591. conn->request_info.http_headers[i].value);
  6592. }
  6593. /* Add user-specified variables */
  6594. s = conn->ctx->config[CGI_ENVIRONMENT];
  6595. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6596. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6597. }
  6598. env->var[env->varused] = NULL;
  6599. env->buf[env->bufused] = '\0';
  6600. }
  6601. static void
  6602. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6603. {
  6604. char *buf;
  6605. size_t buflen;
  6606. int headers_len, data_len, i, truncated;
  6607. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6608. const char *status, *status_text, *connection_state;
  6609. char *pbuf, dir[PATH_MAX], *p;
  6610. struct mg_request_info ri;
  6611. struct cgi_environment blk;
  6612. FILE *in = NULL, *out = NULL, *err = NULL;
  6613. struct file fout = STRUCT_FILE_INITIALIZER;
  6614. pid_t pid = (pid_t)-1;
  6615. if (conn == NULL) {
  6616. return;
  6617. }
  6618. buf = NULL;
  6619. buflen = 16384;
  6620. prepare_cgi_environment(conn, prog, &blk);
  6621. /* CGI must be executed in its own directory. 'dir' must point to the
  6622. * directory containing executable program, 'p' must point to the
  6623. * executable program name relative to 'dir'. */
  6624. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6625. if (truncated) {
  6626. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6627. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6628. goto done;
  6629. }
  6630. if ((p = strrchr(dir, '/')) != NULL) {
  6631. *p++ = '\0';
  6632. } else {
  6633. dir[0] = '.', dir[1] = '\0';
  6634. p = (char *)prog;
  6635. }
  6636. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6637. status = strerror(ERRNO);
  6638. mg_cry(conn,
  6639. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6640. prog,
  6641. status);
  6642. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6643. goto done;
  6644. }
  6645. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6646. if (pid == (pid_t)-1) {
  6647. status = strerror(ERRNO);
  6648. mg_cry(conn,
  6649. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6650. prog,
  6651. status);
  6652. send_http_error(conn,
  6653. 500,
  6654. "Error: Cannot spawn CGI process [%s]: %s",
  6655. prog,
  6656. status);
  6657. goto done;
  6658. }
  6659. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6660. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6661. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6662. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6663. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6664. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6665. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6666. /* Parent closes only one side of the pipes.
  6667. * If we don't mark them as closed, close() attempt before
  6668. * return from this function throws an exception on Windows.
  6669. * Windows does not like when closed descriptor is closed again. */
  6670. (void)close(fdin[0]);
  6671. (void)close(fdout[1]);
  6672. (void)close(fderr[1]);
  6673. fdin[0] = fdout[1] = fderr[1] = -1;
  6674. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6675. status = strerror(ERRNO);
  6676. mg_cry(conn,
  6677. "Error: CGI program \"%s\": Can not open stdin: %s",
  6678. prog,
  6679. status);
  6680. send_http_error(conn,
  6681. 500,
  6682. "Error: CGI can not open fdin\nfopen: %s",
  6683. status);
  6684. goto done;
  6685. }
  6686. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6687. status = strerror(ERRNO);
  6688. mg_cry(conn,
  6689. "Error: CGI program \"%s\": Can not open stdout: %s",
  6690. prog,
  6691. status);
  6692. send_http_error(conn,
  6693. 500,
  6694. "Error: CGI can not open fdout\nfopen: %s",
  6695. status);
  6696. goto done;
  6697. }
  6698. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6699. status = strerror(ERRNO);
  6700. mg_cry(conn,
  6701. "Error: CGI program \"%s\": Can not open stderr: %s",
  6702. prog,
  6703. status);
  6704. send_http_error(conn,
  6705. 500,
  6706. "Error: CGI can not open fdout\nfopen: %s",
  6707. status);
  6708. goto done;
  6709. }
  6710. setbuf(in, NULL);
  6711. setbuf(out, NULL);
  6712. setbuf(err, NULL);
  6713. fout.fp = out;
  6714. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6715. /* This is a POST/PUT request, or another request with body data. */
  6716. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6717. /* Error sending the body data */
  6718. mg_cry(conn,
  6719. "Error: CGI program \"%s\": Forward body data failed",
  6720. prog);
  6721. goto done;
  6722. }
  6723. }
  6724. /* Close so child gets an EOF. */
  6725. fclose(in);
  6726. in = NULL;
  6727. fdin[1] = -1;
  6728. /* Now read CGI reply into a buffer. We need to set correct
  6729. * status code, thus we need to see all HTTP headers first.
  6730. * Do not send anything back to client, until we buffer in all
  6731. * HTTP headers. */
  6732. data_len = 0;
  6733. buf = (char *)mg_malloc(buflen);
  6734. if (buf == NULL) {
  6735. send_http_error(conn,
  6736. 500,
  6737. "Error: Not enough memory for CGI buffer (%u bytes)",
  6738. (unsigned int)buflen);
  6739. mg_cry(conn,
  6740. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6741. "bytes)",
  6742. prog,
  6743. (unsigned int)buflen);
  6744. goto done;
  6745. }
  6746. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6747. if (headers_len <= 0) {
  6748. /* Could not parse the CGI response. Check if some error message on
  6749. * stderr. */
  6750. i = pull_all(err, conn, buf, (int)buflen);
  6751. if (i > 0) {
  6752. mg_cry(conn,
  6753. "Error: CGI program \"%s\" sent error "
  6754. "message: [%.*s]",
  6755. prog,
  6756. i,
  6757. buf);
  6758. send_http_error(conn,
  6759. 500,
  6760. "Error: CGI program \"%s\" sent error "
  6761. "message: [%.*s]",
  6762. prog,
  6763. i,
  6764. buf);
  6765. } else {
  6766. mg_cry(conn,
  6767. "Error: CGI program sent malformed or too big "
  6768. "(>%u bytes) HTTP headers: [%.*s]",
  6769. (unsigned)buflen,
  6770. data_len,
  6771. buf);
  6772. send_http_error(conn,
  6773. 500,
  6774. "Error: CGI program sent malformed or too big "
  6775. "(>%u bytes) HTTP headers: [%.*s]",
  6776. (unsigned)buflen,
  6777. data_len,
  6778. buf);
  6779. }
  6780. goto done;
  6781. }
  6782. pbuf = buf;
  6783. buf[headers_len - 1] = '\0';
  6784. parse_http_headers(&pbuf, &ri);
  6785. /* Make up and send the status line */
  6786. status_text = "OK";
  6787. if ((status = get_header(&ri, "Status")) != NULL) {
  6788. conn->status_code = atoi(status);
  6789. status_text = status;
  6790. while (isdigit(*(const unsigned char *)status_text)
  6791. || *status_text == ' ') {
  6792. status_text++;
  6793. }
  6794. } else if (get_header(&ri, "Location") != NULL) {
  6795. conn->status_code = 302;
  6796. } else {
  6797. conn->status_code = 200;
  6798. }
  6799. connection_state = get_header(&ri, "Connection");
  6800. if (!header_has_option(connection_state, "keep-alive")) {
  6801. conn->must_close = 1;
  6802. }
  6803. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6804. /* Send headers */
  6805. for (i = 0; i < ri.num_headers; i++) {
  6806. mg_printf(conn,
  6807. "%s: %s\r\n",
  6808. ri.http_headers[i].name,
  6809. ri.http_headers[i].value);
  6810. }
  6811. mg_write(conn, "\r\n", 2);
  6812. /* Send chunk of data that may have been read after the headers */
  6813. conn->num_bytes_sent +=
  6814. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6815. /* Read the rest of CGI output and send to the client */
  6816. send_file_data(conn, &fout, 0, INT64_MAX);
  6817. done:
  6818. mg_free(blk.var);
  6819. mg_free(blk.buf);
  6820. if (pid != (pid_t)-1) {
  6821. kill(pid, SIGKILL);
  6822. #if !defined(_WIN32)
  6823. {
  6824. int st;
  6825. while (waitpid(pid, &st, 0) != -1)
  6826. ; /* clean zombies */
  6827. }
  6828. #endif
  6829. }
  6830. if (fdin[0] != -1) {
  6831. close(fdin[0]);
  6832. }
  6833. if (fdout[1] != -1) {
  6834. close(fdout[1]);
  6835. }
  6836. if (in != NULL) {
  6837. fclose(in);
  6838. } else if (fdin[1] != -1) {
  6839. close(fdin[1]);
  6840. }
  6841. if (out != NULL) {
  6842. fclose(out);
  6843. } else if (fdout[0] != -1) {
  6844. close(fdout[0]);
  6845. }
  6846. if (err != NULL) {
  6847. fclose(err);
  6848. } else if (fderr[0] != -1) {
  6849. close(fderr[0]);
  6850. }
  6851. if (buf != NULL) {
  6852. mg_free(buf);
  6853. }
  6854. }
  6855. #endif /* !NO_CGI */
  6856. #if !defined(NO_FILES)
  6857. static void
  6858. mkcol(struct mg_connection *conn, const char *path)
  6859. {
  6860. int rc, body_len;
  6861. struct de de;
  6862. char date[64];
  6863. time_t curtime = time(NULL);
  6864. if (conn == NULL) {
  6865. return;
  6866. }
  6867. /* TODO (mid): Check the send_http_error situations in this function */
  6868. memset(&de.file, 0, sizeof(de.file));
  6869. if (!mg_stat(conn, path, &de.file)) {
  6870. mg_cry(conn,
  6871. "%s: mg_stat(%s) failed: %s",
  6872. __func__,
  6873. path,
  6874. strerror(ERRNO));
  6875. }
  6876. if (de.file.last_modified) {
  6877. /* TODO (high): This check does not seem to make any sense ! */
  6878. send_http_error(
  6879. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6880. return;
  6881. }
  6882. body_len = conn->data_len - conn->request_len;
  6883. if (body_len > 0) {
  6884. send_http_error(
  6885. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6886. return;
  6887. }
  6888. rc = mg_mkdir(conn, path, 0755);
  6889. if (rc == 0) {
  6890. conn->status_code = 201;
  6891. gmt_time_string(date, sizeof(date), &curtime);
  6892. mg_printf(conn,
  6893. "HTTP/1.1 %d Created\r\n"
  6894. "Date: %s\r\n",
  6895. conn->status_code,
  6896. date);
  6897. send_static_cache_header(conn);
  6898. mg_printf(conn,
  6899. "Content-Length: 0\r\n"
  6900. "Connection: %s\r\n\r\n",
  6901. suggest_connection_header(conn));
  6902. } else if (rc == -1) {
  6903. if (errno == EEXIST) {
  6904. send_http_error(
  6905. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6906. } else if (errno == EACCES) {
  6907. send_http_error(
  6908. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6909. } else if (errno == ENOENT) {
  6910. send_http_error(
  6911. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6912. } else {
  6913. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6914. }
  6915. }
  6916. }
  6917. static void
  6918. put_file(struct mg_connection *conn, const char *path)
  6919. {
  6920. struct file file = STRUCT_FILE_INITIALIZER;
  6921. const char *range;
  6922. int64_t r1, r2;
  6923. int rc;
  6924. char date[64];
  6925. time_t curtime = time(NULL);
  6926. if (conn == NULL) {
  6927. return;
  6928. }
  6929. if (mg_stat(conn, path, &file)) {
  6930. /* File already exists */
  6931. conn->status_code = 200;
  6932. if (file.is_directory) {
  6933. /* This is an already existing directory,
  6934. * so there is nothing to do for the server. */
  6935. rc = 0;
  6936. } else {
  6937. /* File exists and is not a directory. */
  6938. /* Can it be replaced? */
  6939. if (file.membuf != NULL) {
  6940. /* This is an "in-memory" file, that can not be replaced */
  6941. send_http_error(
  6942. conn,
  6943. 405,
  6944. "Error: Put not possible\nReplacing %s is not supported",
  6945. path);
  6946. return;
  6947. }
  6948. /* Check if the server may write this file */
  6949. if (access(path, W_OK) == 0) {
  6950. /* Access granted */
  6951. conn->status_code = 200;
  6952. rc = 1;
  6953. } else {
  6954. send_http_error(
  6955. conn,
  6956. 403,
  6957. "Error: Put not possible\nReplacing %s is not allowed",
  6958. path);
  6959. return;
  6960. }
  6961. }
  6962. } else {
  6963. /* File should be created */
  6964. conn->status_code = 201;
  6965. rc = put_dir(conn, path);
  6966. }
  6967. if (rc == 0) {
  6968. /* put_dir returns 0 if path is a directory */
  6969. gmt_time_string(date, sizeof(date), &curtime);
  6970. mg_printf(conn,
  6971. "HTTP/1.1 %d %s\r\n",
  6972. conn->status_code,
  6973. mg_get_response_code_text(NULL, conn->status_code));
  6974. send_no_cache_header(conn);
  6975. mg_printf(conn,
  6976. "Date: %s\r\n"
  6977. "Content-Length: 0\r\n"
  6978. "Connection: %s\r\n\r\n",
  6979. date,
  6980. suggest_connection_header(conn));
  6981. /* Request to create a directory has been fulfilled successfully.
  6982. * No need to put a file. */
  6983. return;
  6984. }
  6985. if (rc == -1) {
  6986. /* put_dir returns -1 if the path is too long */
  6987. send_http_error(conn,
  6988. 414,
  6989. "Error: Path too long\nput_dir(%s): %s",
  6990. path,
  6991. strerror(ERRNO));
  6992. return;
  6993. }
  6994. if (rc == -2) {
  6995. /* put_dir returns -2 if the directory can not be created */
  6996. send_http_error(conn,
  6997. 500,
  6998. "Error: Can not create directory\nput_dir(%s): %s",
  6999. path,
  7000. strerror(ERRNO));
  7001. return;
  7002. }
  7003. /* A file should be created or overwritten. */
  7004. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7005. mg_fclose(&file);
  7006. send_http_error(conn,
  7007. 500,
  7008. "Error: Can not create file\nfopen(%s): %s",
  7009. path,
  7010. strerror(ERRNO));
  7011. return;
  7012. }
  7013. fclose_on_exec(&file, conn);
  7014. range = mg_get_header(conn, "Content-Range");
  7015. r1 = r2 = 0;
  7016. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7017. conn->status_code = 206; /* Partial content */
  7018. fseeko(file.fp, r1, SEEK_SET);
  7019. }
  7020. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7021. /* forward_body_data failed.
  7022. * The error code has already been sent to the client,
  7023. * and conn->status_code is already set. */
  7024. mg_fclose(&file);
  7025. return;
  7026. }
  7027. gmt_time_string(date, sizeof(date), &curtime);
  7028. mg_printf(conn,
  7029. "HTTP/1.1 %d %s\r\n",
  7030. conn->status_code,
  7031. mg_get_response_code_text(NULL, conn->status_code));
  7032. send_no_cache_header(conn);
  7033. mg_printf(conn,
  7034. "Date: %s\r\n"
  7035. "Content-Length: 0\r\n"
  7036. "Connection: %s\r\n\r\n",
  7037. date,
  7038. suggest_connection_header(conn));
  7039. mg_fclose(&file);
  7040. }
  7041. static void
  7042. delete_file(struct mg_connection *conn, const char *path)
  7043. {
  7044. struct de de;
  7045. memset(&de.file, 0, sizeof(de.file));
  7046. if (!mg_stat(conn, path, &de.file)) {
  7047. /* mg_stat returns 0 if the file does not exist */
  7048. send_http_error(conn,
  7049. 404,
  7050. "Error: Cannot delete file\nFile %s not found",
  7051. path);
  7052. return;
  7053. }
  7054. if (de.file.membuf != NULL) {
  7055. /* the file is cached in memory */
  7056. send_http_error(
  7057. conn,
  7058. 405,
  7059. "Error: Delete not possible\nDeleting %s is not supported",
  7060. path);
  7061. return;
  7062. }
  7063. if (de.file.is_directory) {
  7064. if (remove_directory(conn, path)) {
  7065. /* Delete is successful: Return 204 without content. */
  7066. send_http_error(conn, 204, "%s", "");
  7067. } else {
  7068. /* Delete is not successful: Return 500 (Server error). */
  7069. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7070. }
  7071. return;
  7072. }
  7073. /* This is an existing file (not a directory).
  7074. * Check if write permission is granted. */
  7075. if (access(path, W_OK) != 0) {
  7076. /* File is read only */
  7077. send_http_error(
  7078. conn,
  7079. 403,
  7080. "Error: Delete not possible\nDeleting %s is not allowed",
  7081. path);
  7082. return;
  7083. }
  7084. /* Try to delete it. */
  7085. if (mg_remove(conn, path) == 0) {
  7086. /* Delete was successful: Return 204 without content. */
  7087. send_http_error(conn, 204, "%s", "");
  7088. } else {
  7089. /* Delete not successful (file locked). */
  7090. send_http_error(conn,
  7091. 423,
  7092. "Error: Cannot delete file\nremove(%s): %s",
  7093. path,
  7094. strerror(ERRNO));
  7095. }
  7096. }
  7097. #endif /* !NO_FILES */
  7098. static void
  7099. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7100. static void
  7101. do_ssi_include(struct mg_connection *conn,
  7102. const char *ssi,
  7103. char *tag,
  7104. int include_level)
  7105. {
  7106. char file_name[MG_BUF_LEN], path[512], *p;
  7107. struct file file = STRUCT_FILE_INITIALIZER;
  7108. size_t len;
  7109. int truncated = 0;
  7110. if (conn == NULL) {
  7111. return;
  7112. }
  7113. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7114. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7115. * always < MG_BUF_LEN. */
  7116. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7117. /* File name is relative to the webserver root */
  7118. file_name[511] = 0;
  7119. (void)mg_snprintf(conn,
  7120. &truncated,
  7121. path,
  7122. sizeof(path),
  7123. "%s/%s",
  7124. conn->ctx->config[DOCUMENT_ROOT],
  7125. file_name);
  7126. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7127. /* File name is relative to the webserver working directory
  7128. * or it is absolute system path */
  7129. file_name[511] = 0;
  7130. (void)
  7131. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7132. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7133. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7134. /* File name is relative to the currect document */
  7135. file_name[511] = 0;
  7136. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7137. if (!truncated) {
  7138. if ((p = strrchr(path, '/')) != NULL) {
  7139. p[1] = '\0';
  7140. }
  7141. len = strlen(path);
  7142. (void)mg_snprintf(conn,
  7143. &truncated,
  7144. path + len,
  7145. sizeof(path) - len,
  7146. "%s",
  7147. file_name);
  7148. }
  7149. } else {
  7150. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7151. return;
  7152. }
  7153. if (truncated) {
  7154. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7155. return;
  7156. }
  7157. if (!mg_fopen(conn, path, "rb", &file)) {
  7158. mg_cry(conn,
  7159. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7160. tag,
  7161. path,
  7162. strerror(ERRNO));
  7163. } else {
  7164. fclose_on_exec(&file, conn);
  7165. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7166. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7167. path) > 0) {
  7168. send_ssi_file(conn, path, &file, include_level + 1);
  7169. } else {
  7170. send_file_data(conn, &file, 0, INT64_MAX);
  7171. }
  7172. mg_fclose(&file);
  7173. }
  7174. }
  7175. #if !defined(NO_POPEN)
  7176. static void
  7177. do_ssi_exec(struct mg_connection *conn, char *tag)
  7178. {
  7179. char cmd[1024] = "";
  7180. struct file file = STRUCT_FILE_INITIALIZER;
  7181. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7182. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7183. } else {
  7184. cmd[1023] = 0;
  7185. if ((file.fp = popen(cmd, "r")) == NULL) {
  7186. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7187. } else {
  7188. send_file_data(conn, &file, 0, INT64_MAX);
  7189. pclose(file.fp);
  7190. }
  7191. }
  7192. }
  7193. #endif /* !NO_POPEN */
  7194. static int
  7195. mg_fgetc(struct file *filep, int offset)
  7196. {
  7197. if (filep == NULL) {
  7198. return EOF;
  7199. }
  7200. if (filep->membuf != NULL && offset >= 0
  7201. && ((unsigned int)(offset)) < filep->size) {
  7202. return ((const unsigned char *)filep->membuf)[offset];
  7203. } else if (filep->fp != NULL) {
  7204. return fgetc(filep->fp);
  7205. } else {
  7206. return EOF;
  7207. }
  7208. }
  7209. static void
  7210. send_ssi_file(struct mg_connection *conn,
  7211. const char *path,
  7212. struct file *filep,
  7213. int include_level)
  7214. {
  7215. char buf[MG_BUF_LEN];
  7216. int ch, offset, len, in_ssi_tag;
  7217. if (include_level > 10) {
  7218. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7219. return;
  7220. }
  7221. in_ssi_tag = len = offset = 0;
  7222. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7223. if (in_ssi_tag && ch == '>') {
  7224. in_ssi_tag = 0;
  7225. buf[len++] = (char)ch;
  7226. buf[len] = '\0';
  7227. /* assert(len <= (int) sizeof(buf)); */
  7228. if (len > (int)sizeof(buf)) {
  7229. break;
  7230. }
  7231. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7232. /* Not an SSI tag, pass it */
  7233. (void)mg_write(conn, buf, (size_t)len);
  7234. } else {
  7235. if (!memcmp(buf + 5, "include", 7)) {
  7236. do_ssi_include(conn, path, buf + 12, include_level);
  7237. #if !defined(NO_POPEN)
  7238. } else if (!memcmp(buf + 5, "exec", 4)) {
  7239. do_ssi_exec(conn, buf + 9);
  7240. #endif /* !NO_POPEN */
  7241. } else {
  7242. mg_cry(conn,
  7243. "%s: unknown SSI "
  7244. "command: \"%s\"",
  7245. path,
  7246. buf);
  7247. }
  7248. }
  7249. len = 0;
  7250. } else if (in_ssi_tag) {
  7251. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7252. /* Not an SSI tag */
  7253. in_ssi_tag = 0;
  7254. } else if (len == (int)sizeof(buf) - 2) {
  7255. mg_cry(conn, "%s: SSI tag is too large", path);
  7256. len = 0;
  7257. }
  7258. buf[len++] = (char)(ch & 0xff);
  7259. } else if (ch == '<') {
  7260. in_ssi_tag = 1;
  7261. if (len > 0) {
  7262. mg_write(conn, buf, (size_t)len);
  7263. }
  7264. len = 0;
  7265. buf[len++] = (char)(ch & 0xff);
  7266. } else {
  7267. buf[len++] = (char)(ch & 0xff);
  7268. if (len == (int)sizeof(buf)) {
  7269. mg_write(conn, buf, (size_t)len);
  7270. len = 0;
  7271. }
  7272. }
  7273. }
  7274. /* Send the rest of buffered data */
  7275. if (len > 0) {
  7276. mg_write(conn, buf, (size_t)len);
  7277. }
  7278. }
  7279. static void
  7280. handle_ssi_file_request(struct mg_connection *conn,
  7281. const char *path,
  7282. struct file *filep)
  7283. {
  7284. char date[64];
  7285. time_t curtime = time(NULL);
  7286. const char *cors1, *cors2, *cors3;
  7287. if (conn == NULL || path == NULL || filep == NULL) {
  7288. return;
  7289. }
  7290. if (mg_get_header(conn, "Origin")) {
  7291. /* Cross-origin resource sharing (CORS). */
  7292. cors1 = "Access-Control-Allow-Origin: ";
  7293. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7294. cors3 = "\r\n";
  7295. } else {
  7296. cors1 = cors2 = cors3 = "";
  7297. }
  7298. if (!mg_fopen(conn, path, "rb", filep)) {
  7299. /* File exists (precondition for calling this function),
  7300. * but can not be opened by the server. */
  7301. send_http_error(conn,
  7302. 500,
  7303. "Error: Cannot read file\nfopen(%s): %s",
  7304. path,
  7305. strerror(ERRNO));
  7306. } else {
  7307. conn->must_close = 1;
  7308. gmt_time_string(date, sizeof(date), &curtime);
  7309. fclose_on_exec(filep, conn);
  7310. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7311. send_no_cache_header(conn);
  7312. mg_printf(conn,
  7313. "%s%s%s"
  7314. "Date: %s\r\n"
  7315. "Content-Type: text/html\r\n"
  7316. "Connection: %s\r\n\r\n",
  7317. cors1,
  7318. cors2,
  7319. cors3,
  7320. date,
  7321. suggest_connection_header(conn));
  7322. send_ssi_file(conn, path, filep, 0);
  7323. mg_fclose(filep);
  7324. }
  7325. }
  7326. #if !defined(NO_FILES)
  7327. static void
  7328. send_options(struct mg_connection *conn)
  7329. {
  7330. char date[64];
  7331. time_t curtime = time(NULL);
  7332. if (!conn) {
  7333. return;
  7334. }
  7335. conn->status_code = 200;
  7336. conn->must_close = 1;
  7337. gmt_time_string(date, sizeof(date), &curtime);
  7338. mg_printf(conn,
  7339. "HTTP/1.1 200 OK\r\n"
  7340. "Date: %s\r\n"
  7341. /* TODO: "Cache-Control" (?) */
  7342. "Connection: %s\r\n"
  7343. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7344. "PROPFIND, MKCOL\r\n"
  7345. "DAV: 1\r\n\r\n",
  7346. date,
  7347. suggest_connection_header(conn));
  7348. }
  7349. /* Writes PROPFIND properties for a collection element */
  7350. static void
  7351. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7352. {
  7353. char mtime[64];
  7354. if (conn == NULL || uri == NULL || filep == NULL) {
  7355. return;
  7356. }
  7357. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7358. conn->num_bytes_sent +=
  7359. mg_printf(conn,
  7360. "<d:response>"
  7361. "<d:href>%s</d:href>"
  7362. "<d:propstat>"
  7363. "<d:prop>"
  7364. "<d:resourcetype>%s</d:resourcetype>"
  7365. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7366. "<d:getlastmodified>%s</d:getlastmodified>"
  7367. "</d:prop>"
  7368. "<d:status>HTTP/1.1 200 OK</d:status>"
  7369. "</d:propstat>"
  7370. "</d:response>\n",
  7371. uri,
  7372. filep->is_directory ? "<d:collection/>" : "",
  7373. filep->size,
  7374. mtime);
  7375. }
  7376. static void
  7377. print_dav_dir_entry(struct de *de, void *data)
  7378. {
  7379. char href[PATH_MAX];
  7380. char href_encoded[PATH_MAX * 3 /* worst case */];
  7381. int truncated;
  7382. struct mg_connection *conn = (struct mg_connection *)data;
  7383. if (!de || !conn) {
  7384. return;
  7385. }
  7386. mg_snprintf(conn,
  7387. &truncated,
  7388. href,
  7389. sizeof(href),
  7390. "%s%s",
  7391. conn->request_info.local_uri,
  7392. de->file_name);
  7393. if (!truncated) {
  7394. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7395. print_props(conn, href_encoded, &de->file);
  7396. }
  7397. }
  7398. static void
  7399. handle_propfind(struct mg_connection *conn,
  7400. const char *path,
  7401. struct file *filep)
  7402. {
  7403. const char *depth = mg_get_header(conn, "Depth");
  7404. char date[64];
  7405. time_t curtime = time(NULL);
  7406. gmt_time_string(date, sizeof(date), &curtime);
  7407. if (!conn || !path || !filep || !conn->ctx) {
  7408. return;
  7409. }
  7410. conn->must_close = 1;
  7411. conn->status_code = 207;
  7412. mg_printf(conn,
  7413. "HTTP/1.1 207 Multi-Status\r\n"
  7414. "Date: %s\r\n",
  7415. date);
  7416. send_static_cache_header(conn);
  7417. mg_printf(conn,
  7418. "Connection: %s\r\n"
  7419. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7420. suggest_connection_header(conn));
  7421. conn->num_bytes_sent +=
  7422. mg_printf(conn,
  7423. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7424. "<d:multistatus xmlns:d='DAV:'>\n");
  7425. /* Print properties for the requested resource itself */
  7426. print_props(conn, conn->request_info.local_uri, filep);
  7427. /* If it is a directory, print directory entries too if Depth is not 0 */
  7428. if (filep && filep->is_directory
  7429. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7430. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7431. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7432. }
  7433. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7434. }
  7435. #endif
  7436. void
  7437. mg_lock_connection(struct mg_connection *conn)
  7438. {
  7439. if (conn) {
  7440. (void)pthread_mutex_lock(&conn->mutex);
  7441. }
  7442. }
  7443. void
  7444. mg_unlock_connection(struct mg_connection *conn)
  7445. {
  7446. if (conn) {
  7447. (void)pthread_mutex_unlock(&conn->mutex);
  7448. }
  7449. }
  7450. void
  7451. mg_lock_context(struct mg_context *ctx)
  7452. {
  7453. if (ctx) {
  7454. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7455. }
  7456. }
  7457. void
  7458. mg_unlock_context(struct mg_context *ctx)
  7459. {
  7460. if (ctx) {
  7461. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7462. }
  7463. }
  7464. #if defined(USE_TIMERS)
  7465. #include "timer.inl"
  7466. #endif /* USE_TIMERS */
  7467. #ifdef USE_LUA
  7468. #include "mod_lua.inl"
  7469. #endif /* USE_LUA */
  7470. #ifdef USE_DUKTAPE
  7471. #include "mod_duktape.inl"
  7472. #endif /* USE_DUKTAPE */
  7473. #if defined(USE_WEBSOCKET)
  7474. /* START OF SHA-1 code
  7475. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7476. #define SHA1HANDSOFF
  7477. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7478. *
  7479. * #if defined(__sun)
  7480. * #include "solarisfixes.h"
  7481. * #endif
  7482. */
  7483. static int
  7484. is_big_endian(void)
  7485. {
  7486. static const int n = 1;
  7487. return ((char *)&n)[0] == 0;
  7488. }
  7489. union char64long16 {
  7490. unsigned char c[64];
  7491. uint32_t l[16];
  7492. };
  7493. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7494. static uint32_t
  7495. blk0(union char64long16 *block, int i)
  7496. {
  7497. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7498. if (!is_big_endian()) {
  7499. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7500. | (rol(block->l[i], 8) & 0x00FF00FF);
  7501. }
  7502. return block->l[i];
  7503. }
  7504. #define blk(i) \
  7505. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7506. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7507. 1))
  7508. #define R0(v, w, x, y, z, i) \
  7509. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7510. w = rol(w, 30);
  7511. #define R1(v, w, x, y, z, i) \
  7512. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7513. w = rol(w, 30);
  7514. #define R2(v, w, x, y, z, i) \
  7515. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7516. w = rol(w, 30);
  7517. #define R3(v, w, x, y, z, i) \
  7518. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7519. w = rol(w, 30);
  7520. #define R4(v, w, x, y, z, i) \
  7521. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7522. w = rol(w, 30);
  7523. typedef struct {
  7524. uint32_t state[5];
  7525. uint32_t count[2];
  7526. unsigned char buffer[64];
  7527. } SHA1_CTX;
  7528. static void
  7529. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7530. {
  7531. uint32_t a, b, c, d, e;
  7532. union char64long16 block[1];
  7533. memcpy(block, buffer, 64);
  7534. a = state[0];
  7535. b = state[1];
  7536. c = state[2];
  7537. d = state[3];
  7538. e = state[4];
  7539. R0(a, b, c, d, e, 0);
  7540. R0(e, a, b, c, d, 1);
  7541. R0(d, e, a, b, c, 2);
  7542. R0(c, d, e, a, b, 3);
  7543. R0(b, c, d, e, a, 4);
  7544. R0(a, b, c, d, e, 5);
  7545. R0(e, a, b, c, d, 6);
  7546. R0(d, e, a, b, c, 7);
  7547. R0(c, d, e, a, b, 8);
  7548. R0(b, c, d, e, a, 9);
  7549. R0(a, b, c, d, e, 10);
  7550. R0(e, a, b, c, d, 11);
  7551. R0(d, e, a, b, c, 12);
  7552. R0(c, d, e, a, b, 13);
  7553. R0(b, c, d, e, a, 14);
  7554. R0(a, b, c, d, e, 15);
  7555. R1(e, a, b, c, d, 16);
  7556. R1(d, e, a, b, c, 17);
  7557. R1(c, d, e, a, b, 18);
  7558. R1(b, c, d, e, a, 19);
  7559. R2(a, b, c, d, e, 20);
  7560. R2(e, a, b, c, d, 21);
  7561. R2(d, e, a, b, c, 22);
  7562. R2(c, d, e, a, b, 23);
  7563. R2(b, c, d, e, a, 24);
  7564. R2(a, b, c, d, e, 25);
  7565. R2(e, a, b, c, d, 26);
  7566. R2(d, e, a, b, c, 27);
  7567. R2(c, d, e, a, b, 28);
  7568. R2(b, c, d, e, a, 29);
  7569. R2(a, b, c, d, e, 30);
  7570. R2(e, a, b, c, d, 31);
  7571. R2(d, e, a, b, c, 32);
  7572. R2(c, d, e, a, b, 33);
  7573. R2(b, c, d, e, a, 34);
  7574. R2(a, b, c, d, e, 35);
  7575. R2(e, a, b, c, d, 36);
  7576. R2(d, e, a, b, c, 37);
  7577. R2(c, d, e, a, b, 38);
  7578. R2(b, c, d, e, a, 39);
  7579. R3(a, b, c, d, e, 40);
  7580. R3(e, a, b, c, d, 41);
  7581. R3(d, e, a, b, c, 42);
  7582. R3(c, d, e, a, b, 43);
  7583. R3(b, c, d, e, a, 44);
  7584. R3(a, b, c, d, e, 45);
  7585. R3(e, a, b, c, d, 46);
  7586. R3(d, e, a, b, c, 47);
  7587. R3(c, d, e, a, b, 48);
  7588. R3(b, c, d, e, a, 49);
  7589. R3(a, b, c, d, e, 50);
  7590. R3(e, a, b, c, d, 51);
  7591. R3(d, e, a, b, c, 52);
  7592. R3(c, d, e, a, b, 53);
  7593. R3(b, c, d, e, a, 54);
  7594. R3(a, b, c, d, e, 55);
  7595. R3(e, a, b, c, d, 56);
  7596. R3(d, e, a, b, c, 57);
  7597. R3(c, d, e, a, b, 58);
  7598. R3(b, c, d, e, a, 59);
  7599. R4(a, b, c, d, e, 60);
  7600. R4(e, a, b, c, d, 61);
  7601. R4(d, e, a, b, c, 62);
  7602. R4(c, d, e, a, b, 63);
  7603. R4(b, c, d, e, a, 64);
  7604. R4(a, b, c, d, e, 65);
  7605. R4(e, a, b, c, d, 66);
  7606. R4(d, e, a, b, c, 67);
  7607. R4(c, d, e, a, b, 68);
  7608. R4(b, c, d, e, a, 69);
  7609. R4(a, b, c, d, e, 70);
  7610. R4(e, a, b, c, d, 71);
  7611. R4(d, e, a, b, c, 72);
  7612. R4(c, d, e, a, b, 73);
  7613. R4(b, c, d, e, a, 74);
  7614. R4(a, b, c, d, e, 75);
  7615. R4(e, a, b, c, d, 76);
  7616. R4(d, e, a, b, c, 77);
  7617. R4(c, d, e, a, b, 78);
  7618. R4(b, c, d, e, a, 79);
  7619. state[0] += a;
  7620. state[1] += b;
  7621. state[2] += c;
  7622. state[3] += d;
  7623. state[4] += e;
  7624. a = b = c = d = e = 0;
  7625. memset(block, '\0', sizeof(block));
  7626. }
  7627. static void
  7628. SHA1Init(SHA1_CTX *context)
  7629. {
  7630. context->state[0] = 0x67452301;
  7631. context->state[1] = 0xEFCDAB89;
  7632. context->state[2] = 0x98BADCFE;
  7633. context->state[3] = 0x10325476;
  7634. context->state[4] = 0xC3D2E1F0;
  7635. context->count[0] = context->count[1] = 0;
  7636. }
  7637. static void
  7638. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7639. {
  7640. uint32_t i, j;
  7641. j = context->count[0];
  7642. if ((context->count[0] += len << 3) < j) {
  7643. context->count[1]++;
  7644. }
  7645. context->count[1] += (len >> 29);
  7646. j = (j >> 3) & 63;
  7647. if ((j + len) > 63) {
  7648. memcpy(&context->buffer[j], data, (i = 64 - j));
  7649. SHA1Transform(context->state, context->buffer);
  7650. for (; i + 63 < len; i += 64) {
  7651. SHA1Transform(context->state, &data[i]);
  7652. }
  7653. j = 0;
  7654. } else
  7655. i = 0;
  7656. memcpy(&context->buffer[j], &data[i], len - i);
  7657. }
  7658. static void
  7659. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7660. {
  7661. unsigned i;
  7662. unsigned char finalcount[8], c;
  7663. for (i = 0; i < 8; i++) {
  7664. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7665. >> ((3 - (i & 3)) * 8)) & 255);
  7666. }
  7667. c = 0200;
  7668. SHA1Update(context, &c, 1);
  7669. while ((context->count[0] & 504) != 448) {
  7670. c = 0000;
  7671. SHA1Update(context, &c, 1);
  7672. }
  7673. SHA1Update(context, finalcount, 8);
  7674. for (i = 0; i < 20; i++) {
  7675. digest[i] = (unsigned char)((context->state[i >> 2]
  7676. >> ((3 - (i & 3)) * 8)) & 255);
  7677. }
  7678. memset(context, '\0', sizeof(*context));
  7679. memset(&finalcount, '\0', sizeof(finalcount));
  7680. }
  7681. /* END OF SHA1 CODE */
  7682. static int
  7683. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7684. {
  7685. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7686. const char *protocol = NULL;
  7687. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7688. SHA1_CTX sha_ctx;
  7689. int truncated;
  7690. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7691. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7692. if (truncated) {
  7693. conn->must_close = 1;
  7694. return 0;
  7695. }
  7696. SHA1Init(&sha_ctx);
  7697. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7698. SHA1Final((unsigned char *)sha, &sha_ctx);
  7699. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7700. mg_printf(conn,
  7701. "HTTP/1.1 101 Switching Protocols\r\n"
  7702. "Upgrade: websocket\r\n"
  7703. "Connection: Upgrade\r\n"
  7704. "Sec-WebSocket-Accept: %s\r\n",
  7705. b64_sha);
  7706. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7707. if (protocol) {
  7708. /* The protocol is a comma seperated list of names. */
  7709. /* The server must only return one value from this list. */
  7710. /* First check if it is a list or just a single value. */
  7711. const char *sep = strchr(protocol, ',');
  7712. if (sep == NULL) {
  7713. /* Just a single protocol -> accept it. */
  7714. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7715. } else {
  7716. /* Multiple protocols -> accept the first one. */
  7717. /* This is just a quick fix if the client offers multiple
  7718. * protocols. In order to get the behavior intended by
  7719. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7720. * required to have a list of websocket subprotocols accepted
  7721. * by the server. Then the server must either select a subprotocol
  7722. * supported by client and server, or the server has to abort the
  7723. * handshake by not returning a Sec-Websocket-Protocol header if
  7724. * no subprotocol is acceptable.
  7725. */
  7726. mg_printf(conn,
  7727. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7728. (int)(sep - protocol),
  7729. protocol);
  7730. }
  7731. /* TODO: Real subprotocol negotiation instead of just taking the first
  7732. * websocket subprotocol suggested by the client. */
  7733. } else {
  7734. mg_printf(conn, "%s", "\r\n");
  7735. }
  7736. return 1;
  7737. }
  7738. static void
  7739. read_websocket(struct mg_connection *conn,
  7740. mg_websocket_data_handler ws_data_handler,
  7741. void *callback_data)
  7742. {
  7743. /* Pointer to the beginning of the portion of the incoming websocket
  7744. * message queue.
  7745. * The original websocket upgrade request is never removed, so the queue
  7746. * begins after it. */
  7747. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7748. int n, error, exit_by_callback;
  7749. /* body_len is the length of the entire queue in bytes
  7750. * len is the length of the current message
  7751. * data_len is the length of the current message's data payload
  7752. * header_len is the length of the current message's header */
  7753. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7754. /* "The masking key is a 32-bit value chosen at random by the client."
  7755. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7756. */
  7757. unsigned char mask[4];
  7758. /* data points to the place where the message is stored when passed to
  7759. * the
  7760. * websocket_data callback. This is either mem on the stack, or a
  7761. * dynamically allocated buffer if it is too large. */
  7762. char mem[4096];
  7763. char *data = mem;
  7764. unsigned char mop; /* mask flag and opcode */
  7765. double timeout = -1.0;
  7766. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7767. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7768. }
  7769. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7770. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7771. }
  7772. mg_set_thread_name("wsock");
  7773. /* Loop continuously, reading messages from the socket, invoking the
  7774. * callback, and waiting repeatedly until an error occurs. */
  7775. while (!conn->ctx->stop_flag) {
  7776. header_len = 0;
  7777. assert(conn->data_len >= conn->request_len);
  7778. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7779. len = buf[1] & 127;
  7780. mask_len = (buf[1] & 128) ? 4 : 0;
  7781. if ((len < 126) && (body_len >= mask_len)) {
  7782. data_len = len;
  7783. header_len = 2 + mask_len;
  7784. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7785. header_len = 4 + mask_len;
  7786. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7787. } else if (body_len >= (10 + mask_len)) {
  7788. header_len = 10 + mask_len;
  7789. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7790. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7791. }
  7792. }
  7793. if (header_len > 0 && body_len >= header_len) {
  7794. /* Allocate space to hold websocket payload */
  7795. data = mem;
  7796. if (data_len > sizeof(mem)) {
  7797. data = (char *)mg_malloc(data_len);
  7798. if (data == NULL) {
  7799. /* Allocation failed, exit the loop and then close the
  7800. * connection */
  7801. mg_cry(conn, "websocket out of memory; closing connection");
  7802. break;
  7803. }
  7804. }
  7805. /* Copy the mask before we shift the queue and destroy it */
  7806. if (mask_len > 0) {
  7807. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7808. } else {
  7809. memset(mask, 0, sizeof(mask));
  7810. }
  7811. /* Read frame payload from the first message in the queue into
  7812. * data and advance the queue by moving the memory in place. */
  7813. assert(body_len >= header_len);
  7814. if (data_len + header_len > body_len) {
  7815. mop = buf[0]; /* current mask and opcode */
  7816. /* Overflow case */
  7817. len = body_len - header_len;
  7818. memcpy(data, buf + header_len, len);
  7819. error = 0;
  7820. while (len < data_len) {
  7821. n = pull(
  7822. NULL, conn, data + len, (int)(data_len - len), timeout);
  7823. if (n <= 0) {
  7824. error = 1;
  7825. break;
  7826. }
  7827. len += (size_t)n;
  7828. }
  7829. if (error) {
  7830. mg_cry(conn, "Websocket pull failed; closing connection");
  7831. break;
  7832. }
  7833. conn->data_len = conn->request_len;
  7834. } else {
  7835. mop = buf[0]; /* current mask and opcode, overwritten by
  7836. * memmove() */
  7837. /* Length of the message being read at the front of the
  7838. * queue */
  7839. len = data_len + header_len;
  7840. /* Copy the data payload into the data pointer for the
  7841. * callback */
  7842. memcpy(data, buf + header_len, data_len);
  7843. /* Move the queue forward len bytes */
  7844. memmove(buf, buf + len, body_len - len);
  7845. /* Mark the queue as advanced */
  7846. conn->data_len -= (int)len;
  7847. }
  7848. /* Apply mask if necessary */
  7849. if (mask_len > 0) {
  7850. for (i = 0; i < data_len; ++i) {
  7851. data[i] ^= mask[i & 3];
  7852. }
  7853. }
  7854. /* Exit the loop if callback signals to exit (server side),
  7855. * or "connection close" opcode received (client side). */
  7856. exit_by_callback = 0;
  7857. if ((ws_data_handler != NULL)
  7858. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7859. exit_by_callback = 1;
  7860. }
  7861. if (data != mem) {
  7862. mg_free(data);
  7863. }
  7864. if (exit_by_callback
  7865. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7866. /* Opcode == 8, connection close */
  7867. break;
  7868. }
  7869. /* Not breaking the loop, process next websocket frame. */
  7870. } else {
  7871. /* Read from the socket into the next available location in the
  7872. * message queue. */
  7873. if ((n = pull(NULL,
  7874. conn,
  7875. conn->buf + conn->data_len,
  7876. conn->buf_size - conn->data_len,
  7877. timeout)) <= 0) {
  7878. /* Error, no bytes read */
  7879. break;
  7880. }
  7881. conn->data_len += n;
  7882. }
  7883. }
  7884. mg_set_thread_name("worker");
  7885. }
  7886. static int
  7887. mg_websocket_write_exec(struct mg_connection *conn,
  7888. int opcode,
  7889. const char *data,
  7890. size_t dataLen,
  7891. uint32_t masking_key)
  7892. {
  7893. unsigned char header[14];
  7894. size_t headerLen = 1;
  7895. int retval = -1;
  7896. header[0] = 0x80 + (opcode & 0xF);
  7897. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7898. if (dataLen < 126) {
  7899. /* inline 7-bit length field */
  7900. header[1] = (unsigned char)dataLen;
  7901. headerLen = 2;
  7902. } else if (dataLen <= 0xFFFF) {
  7903. /* 16-bit length field */
  7904. header[1] = 126;
  7905. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7906. headerLen = 4;
  7907. } else {
  7908. /* 64-bit length field */
  7909. header[1] = 127;
  7910. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7911. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7912. headerLen = 10;
  7913. }
  7914. if (masking_key) {
  7915. /* add mask */
  7916. header[1] |= 0x80;
  7917. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7918. headerLen += 4;
  7919. }
  7920. /* Note that POSIX/Winsock's send() is threadsafe
  7921. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7922. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7923. * push(), although that is only a problem if the packet is large or
  7924. * outgoing buffer is full). */
  7925. (void)mg_lock_connection(conn);
  7926. retval = mg_write(conn, header, headerLen);
  7927. if (dataLen > 0) {
  7928. retval = mg_write(conn, data, dataLen);
  7929. }
  7930. mg_unlock_connection(conn);
  7931. return retval;
  7932. }
  7933. int
  7934. mg_websocket_write(struct mg_connection *conn,
  7935. int opcode,
  7936. const char *data,
  7937. size_t dataLen)
  7938. {
  7939. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7940. }
  7941. static void
  7942. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7943. {
  7944. size_t i = 0;
  7945. i = 0;
  7946. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7947. /* Convert in 32 bit words, if data is 4 byte aligned */
  7948. while (i < (in_len - 3)) {
  7949. *(uint32_t *)(void *)(out + i) =
  7950. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7951. i += 4;
  7952. }
  7953. }
  7954. if (i != in_len) {
  7955. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7956. while (i < in_len) {
  7957. *(uint8_t *)(void *)(out + i) =
  7958. *(uint8_t *)(void *)(in + i)
  7959. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7960. i++;
  7961. }
  7962. }
  7963. }
  7964. int
  7965. mg_websocket_client_write(struct mg_connection *conn,
  7966. int opcode,
  7967. const char *data,
  7968. size_t dataLen)
  7969. {
  7970. int retval = -1;
  7971. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7972. uint32_t masking_key = (uint32_t)get_random();
  7973. if (masked_data == NULL) {
  7974. /* Return -1 in an error case */
  7975. mg_cry(conn,
  7976. "Cannot allocate buffer for masked websocket response: "
  7977. "Out of memory");
  7978. return -1;
  7979. }
  7980. mask_data(data, dataLen, masking_key, masked_data);
  7981. retval = mg_websocket_write_exec(
  7982. conn, opcode, masked_data, dataLen, masking_key);
  7983. mg_free(masked_data);
  7984. return retval;
  7985. }
  7986. static void
  7987. handle_websocket_request(struct mg_connection *conn,
  7988. const char *path,
  7989. int is_callback_resource,
  7990. mg_websocket_connect_handler ws_connect_handler,
  7991. mg_websocket_ready_handler ws_ready_handler,
  7992. mg_websocket_data_handler ws_data_handler,
  7993. mg_websocket_close_handler ws_close_handler,
  7994. void *cbData)
  7995. {
  7996. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7997. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7998. int lua_websock = 0;
  7999. #if !defined(USE_LUA)
  8000. (void)path;
  8001. #endif
  8002. /* Step 1: Check websocket protocol version. */
  8003. /* Step 1.1: Check Sec-WebSocket-Key. */
  8004. if (!websock_key) {
  8005. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8006. * requires a Sec-WebSocket-Key header.
  8007. */
  8008. /* It could be the hixie draft version
  8009. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8010. */
  8011. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8012. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8013. char key3[8];
  8014. if ((key1 != NULL) && (key2 != NULL)) {
  8015. /* This version uses 8 byte body data in a GET request */
  8016. conn->content_len = 8;
  8017. if (8 == mg_read(conn, key3, 8)) {
  8018. /* This is the hixie version */
  8019. send_http_error(conn,
  8020. 426,
  8021. "%s",
  8022. "Protocol upgrade to RFC 6455 required");
  8023. return;
  8024. }
  8025. }
  8026. /* This is an unknown version */
  8027. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8028. return;
  8029. }
  8030. /* Step 1.2: Check websocket protocol version. */
  8031. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8032. if (version == NULL || strcmp(version, "13") != 0) {
  8033. /* Reject wrong versions */
  8034. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8035. return;
  8036. }
  8037. /* Step 1.3: Could check for "Host", but we do not really nead this
  8038. * value for anything, so just ignore it. */
  8039. /* Step 2: If a callback is responsible, call it. */
  8040. if (is_callback_resource) {
  8041. if (ws_connect_handler != NULL
  8042. && ws_connect_handler(conn, cbData) != 0) {
  8043. /* C callback has returned non-zero, do not proceed with
  8044. * handshake.
  8045. */
  8046. /* Note that C callbacks are no longer called when Lua is
  8047. * responsible, so C can no longer filter callbacks for Lua. */
  8048. return;
  8049. }
  8050. }
  8051. #if defined(USE_LUA)
  8052. /* Step 3: No callback. Check if Lua is responsible. */
  8053. else {
  8054. /* Step 3.1: Check if Lua is responsible. */
  8055. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8056. lua_websock =
  8057. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8058. strlen(
  8059. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8060. path);
  8061. }
  8062. if (lua_websock) {
  8063. /* Step 3.2: Lua is responsible: call it. */
  8064. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8065. if (!conn->lua_websocket_state) {
  8066. /* Lua rejected the new client */
  8067. return;
  8068. }
  8069. }
  8070. }
  8071. #endif
  8072. /* Step 4: Check if there is a responsible websocket handler. */
  8073. if (!is_callback_resource && !lua_websock) {
  8074. /* There is no callback, an Lua is not responsible either. */
  8075. /* Reply with a 404 Not Found or with nothing at all?
  8076. * TODO (mid): check the websocket standards, how to reply to
  8077. * requests to invalid websocket addresses. */
  8078. send_http_error(conn, 404, "%s", "Not found");
  8079. return;
  8080. }
  8081. /* Step 5: The websocket connection has been accepted */
  8082. if (!send_websocket_handshake(conn, websock_key)) {
  8083. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8084. return;
  8085. }
  8086. /* Step 6: Call the ready handler */
  8087. if (is_callback_resource) {
  8088. if (ws_ready_handler != NULL) {
  8089. ws_ready_handler(conn, cbData);
  8090. }
  8091. #if defined(USE_LUA)
  8092. } else if (lua_websock) {
  8093. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8094. /* the ready handler returned false */
  8095. return;
  8096. }
  8097. #endif
  8098. }
  8099. /* Step 7: Enter the read loop */
  8100. if (is_callback_resource) {
  8101. read_websocket(conn, ws_data_handler, cbData);
  8102. #if defined(USE_LUA)
  8103. } else if (lua_websock) {
  8104. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8105. #endif
  8106. }
  8107. /* Step 8: Call the close handler */
  8108. if (ws_close_handler) {
  8109. ws_close_handler(conn, cbData);
  8110. }
  8111. }
  8112. static int
  8113. is_websocket_protocol(const struct mg_connection *conn)
  8114. {
  8115. const char *upgrade, *connection;
  8116. /* A websocket protocoll has the following HTTP headers:
  8117. *
  8118. * Connection: Upgrade
  8119. * Upgrade: Websocket
  8120. */
  8121. upgrade = mg_get_header(conn, "Upgrade");
  8122. if (upgrade == NULL) {
  8123. return 0; /* fail early, don't waste time checking other header
  8124. * fields
  8125. */
  8126. }
  8127. if (!mg_strcasestr(upgrade, "websocket")) {
  8128. return 0;
  8129. }
  8130. connection = mg_get_header(conn, "Connection");
  8131. if (connection == NULL) {
  8132. return 0;
  8133. }
  8134. if (!mg_strcasestr(connection, "upgrade")) {
  8135. return 0;
  8136. }
  8137. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8138. * "Sec-WebSocket-Version" are also required.
  8139. * Don't check them here, since even an unsupported websocket protocol
  8140. * request still IS a websocket request (in contrast to a standard HTTP
  8141. * request). It will fail later in handle_websocket_request.
  8142. */
  8143. return 1;
  8144. }
  8145. #endif /* !USE_WEBSOCKET */
  8146. static int
  8147. isbyte(int n)
  8148. {
  8149. return n >= 0 && n <= 255;
  8150. }
  8151. static int
  8152. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8153. {
  8154. int n, a, b, c, d, slash = 32, len = 0;
  8155. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8156. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8157. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8158. && slash < 33) {
  8159. len = n;
  8160. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8161. | (uint32_t)d;
  8162. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8163. }
  8164. return len;
  8165. }
  8166. static int
  8167. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8168. {
  8169. int throttle = 0;
  8170. struct vec vec, val;
  8171. uint32_t net, mask;
  8172. char mult;
  8173. double v;
  8174. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8175. mult = ',';
  8176. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8177. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8178. && mult != ',')) {
  8179. continue;
  8180. }
  8181. v *= (lowercase(&mult) == 'k')
  8182. ? 1024
  8183. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8184. if (vec.len == 1 && vec.ptr[0] == '*') {
  8185. throttle = (int)v;
  8186. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8187. if ((remote_ip & mask) == net) {
  8188. throttle = (int)v;
  8189. }
  8190. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8191. throttle = (int)v;
  8192. }
  8193. }
  8194. return throttle;
  8195. }
  8196. static uint32_t
  8197. get_remote_ip(const struct mg_connection *conn)
  8198. {
  8199. if (!conn) {
  8200. return 0;
  8201. }
  8202. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8203. }
  8204. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8205. #include "handle_form.inl"
  8206. #if defined(MG_LEGACY_INTERFACE)
  8207. /* Implement the deprecated mg_upload function by calling the new
  8208. * mg_handle_form_request function. While mg_upload could only handle
  8209. * HTML forms sent as POST request in multipart/form-data format
  8210. * containing only file input elements, mg_handle_form_request can
  8211. * handle all form input elements and all standard request methods. */
  8212. struct mg_upload_user_data {
  8213. struct mg_connection *conn;
  8214. const char *destination_dir;
  8215. int num_uploaded_files;
  8216. };
  8217. /* Helper function for deprecated mg_upload. */
  8218. static int
  8219. mg_upload_field_found(const char *key,
  8220. const char *filename,
  8221. char *path,
  8222. size_t pathlen,
  8223. void *user_data)
  8224. {
  8225. int truncated = 0;
  8226. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8227. (void)key;
  8228. if (!filename) {
  8229. mg_cry(fud->conn, "%s: No filename set", __func__);
  8230. return FORM_FIELD_STORAGE_ABORT;
  8231. }
  8232. mg_snprintf(fud->conn,
  8233. &truncated,
  8234. path,
  8235. pathlen - 1,
  8236. "%s/%s",
  8237. fud->destination_dir,
  8238. filename);
  8239. if (!truncated) {
  8240. mg_cry(fud->conn, "%s: File path too long", __func__);
  8241. return FORM_FIELD_STORAGE_ABORT;
  8242. }
  8243. return FORM_FIELD_STORAGE_STORE;
  8244. }
  8245. /* Helper function for deprecated mg_upload. */
  8246. static int
  8247. mg_upload_field_get(const char *key,
  8248. const char *value,
  8249. size_t value_size,
  8250. void *user_data)
  8251. {
  8252. /* Function should never be called */
  8253. (void)key;
  8254. (void)value;
  8255. (void)value_size;
  8256. (void)user_data;
  8257. return 0;
  8258. }
  8259. /* Helper function for deprecated mg_upload. */
  8260. static int
  8261. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8262. {
  8263. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8264. (void)file_size;
  8265. fud->num_uploaded_files++;
  8266. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8267. return 0;
  8268. }
  8269. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8270. int
  8271. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8272. {
  8273. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8274. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8275. mg_upload_field_get,
  8276. mg_upload_field_stored,
  8277. 0};
  8278. int ret;
  8279. fdh.user_data = (void *)&fud;
  8280. ret = mg_handle_form_request(conn, &fdh);
  8281. if (ret < 0) {
  8282. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8283. }
  8284. return fud.num_uploaded_files;
  8285. }
  8286. #endif
  8287. static int
  8288. get_first_ssl_listener_index(const struct mg_context *ctx)
  8289. {
  8290. unsigned int i;
  8291. int idx = -1;
  8292. if (ctx) {
  8293. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8294. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8295. }
  8296. }
  8297. return idx;
  8298. }
  8299. static void
  8300. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8301. {
  8302. char host[1025];
  8303. const char *host_header;
  8304. size_t hostlen;
  8305. host_header = mg_get_header(conn, "Host");
  8306. hostlen = sizeof(host);
  8307. if (host_header != NULL) {
  8308. char *pos;
  8309. mg_strlcpy(host, host_header, hostlen);
  8310. host[hostlen - 1] = '\0';
  8311. pos = strchr(host, ':');
  8312. if (pos != NULL) {
  8313. *pos = '\0';
  8314. }
  8315. } else {
  8316. /* Cannot get host from the Host: header.
  8317. * Fallback to our IP address. */
  8318. if (conn) {
  8319. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8320. }
  8321. }
  8322. /* Send host, port, uri and (if it exists) ?query_string */
  8323. if (conn) {
  8324. mg_printf(conn,
  8325. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8326. host,
  8327. #if defined(USE_IPV6)
  8328. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8329. == AF_INET6)
  8330. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8331. .lsa.sin6.sin6_port)
  8332. :
  8333. #endif
  8334. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8335. .lsa.sin.sin_port),
  8336. conn->request_info.local_uri,
  8337. (conn->request_info.query_string == NULL) ? "" : "?",
  8338. (conn->request_info.query_string == NULL)
  8339. ? ""
  8340. : conn->request_info.query_string);
  8341. }
  8342. }
  8343. static void
  8344. mg_set_handler_type(struct mg_context *ctx,
  8345. const char *uri,
  8346. int handler_type,
  8347. int is_delete_request,
  8348. mg_request_handler handler,
  8349. mg_websocket_connect_handler connect_handler,
  8350. mg_websocket_ready_handler ready_handler,
  8351. mg_websocket_data_handler data_handler,
  8352. mg_websocket_close_handler close_handler,
  8353. mg_authorization_handler auth_handler,
  8354. void *cbdata)
  8355. {
  8356. struct mg_handler_info *tmp_rh, **lastref;
  8357. size_t urilen = strlen(uri);
  8358. if (handler_type == WEBSOCKET_HANDLER) {
  8359. /* assert(handler == NULL); */
  8360. /* assert(is_delete_request || connect_handler!=NULL ||
  8361. * ready_handler!=NULL || data_handler!=NULL ||
  8362. * close_handler!=NULL);
  8363. */
  8364. /* assert(auth_handler == NULL); */
  8365. if (handler != NULL) {
  8366. return;
  8367. }
  8368. if (!is_delete_request && connect_handler == NULL
  8369. && ready_handler == NULL
  8370. && data_handler == NULL
  8371. && close_handler == NULL) {
  8372. return;
  8373. }
  8374. if (auth_handler != NULL) {
  8375. return;
  8376. }
  8377. } else if (handler_type == REQUEST_HANDLER) {
  8378. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8379. * data_handler==NULL && close_handler==NULL); */
  8380. /* assert(is_delete_request || (handler!=NULL));
  8381. */
  8382. /* assert(auth_handler == NULL); */
  8383. if (connect_handler != NULL || ready_handler != NULL
  8384. || data_handler != NULL
  8385. || close_handler != NULL) {
  8386. return;
  8387. }
  8388. if (!is_delete_request && (handler == NULL)) {
  8389. return;
  8390. }
  8391. if (auth_handler != NULL) {
  8392. return;
  8393. }
  8394. } else { /* AUTH_HANDLER */
  8395. /* assert(handler == NULL); */
  8396. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8397. * data_handler==NULL && close_handler==NULL); */
  8398. /* assert(auth_handler != NULL); */
  8399. if (handler != NULL) {
  8400. return;
  8401. }
  8402. if (connect_handler != NULL || ready_handler != NULL
  8403. || data_handler != NULL
  8404. || close_handler != NULL) {
  8405. return;
  8406. }
  8407. if (!is_delete_request && (auth_handler == NULL)) {
  8408. return;
  8409. }
  8410. }
  8411. if (!ctx) {
  8412. return;
  8413. }
  8414. mg_lock_context(ctx);
  8415. /* first try to find an existing handler */
  8416. lastref = &(ctx->handlers);
  8417. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8418. if (tmp_rh->handler_type == handler_type) {
  8419. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8420. if (!is_delete_request) {
  8421. /* update existing handler */
  8422. if (handler_type == REQUEST_HANDLER) {
  8423. tmp_rh->handler = handler;
  8424. } else if (handler_type == WEBSOCKET_HANDLER) {
  8425. tmp_rh->connect_handler = connect_handler;
  8426. tmp_rh->ready_handler = ready_handler;
  8427. tmp_rh->data_handler = data_handler;
  8428. tmp_rh->close_handler = close_handler;
  8429. } else { /* AUTH_HANDLER */
  8430. tmp_rh->auth_handler = auth_handler;
  8431. }
  8432. tmp_rh->cbdata = cbdata;
  8433. } else {
  8434. /* remove existing handler */
  8435. *lastref = tmp_rh->next;
  8436. mg_free(tmp_rh->uri);
  8437. mg_free(tmp_rh);
  8438. }
  8439. mg_unlock_context(ctx);
  8440. return;
  8441. }
  8442. }
  8443. lastref = &(tmp_rh->next);
  8444. }
  8445. if (is_delete_request) {
  8446. /* no handler to set, this was a remove request to a non-existing
  8447. * handler */
  8448. mg_unlock_context(ctx);
  8449. return;
  8450. }
  8451. tmp_rh =
  8452. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8453. if (tmp_rh == NULL) {
  8454. mg_unlock_context(ctx);
  8455. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8456. return;
  8457. }
  8458. tmp_rh->uri = mg_strdup(uri);
  8459. if (!tmp_rh->uri) {
  8460. mg_unlock_context(ctx);
  8461. mg_free(tmp_rh);
  8462. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8463. return;
  8464. }
  8465. tmp_rh->uri_len = urilen;
  8466. if (handler_type == REQUEST_HANDLER) {
  8467. tmp_rh->handler = handler;
  8468. } else if (handler_type == WEBSOCKET_HANDLER) {
  8469. tmp_rh->connect_handler = connect_handler;
  8470. tmp_rh->ready_handler = ready_handler;
  8471. tmp_rh->data_handler = data_handler;
  8472. tmp_rh->close_handler = close_handler;
  8473. } else { /* AUTH_HANDLER */
  8474. tmp_rh->auth_handler = auth_handler;
  8475. }
  8476. tmp_rh->cbdata = cbdata;
  8477. tmp_rh->handler_type = handler_type;
  8478. tmp_rh->next = NULL;
  8479. *lastref = tmp_rh;
  8480. mg_unlock_context(ctx);
  8481. }
  8482. void
  8483. mg_set_request_handler(struct mg_context *ctx,
  8484. const char *uri,
  8485. mg_request_handler handler,
  8486. void *cbdata)
  8487. {
  8488. mg_set_handler_type(ctx,
  8489. uri,
  8490. REQUEST_HANDLER,
  8491. handler == NULL,
  8492. handler,
  8493. NULL,
  8494. NULL,
  8495. NULL,
  8496. NULL,
  8497. NULL,
  8498. cbdata);
  8499. }
  8500. void
  8501. mg_set_websocket_handler(struct mg_context *ctx,
  8502. const char *uri,
  8503. mg_websocket_connect_handler connect_handler,
  8504. mg_websocket_ready_handler ready_handler,
  8505. mg_websocket_data_handler data_handler,
  8506. mg_websocket_close_handler close_handler,
  8507. void *cbdata)
  8508. {
  8509. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8510. && (data_handler == NULL)
  8511. && (close_handler == NULL);
  8512. mg_set_handler_type(ctx,
  8513. uri,
  8514. WEBSOCKET_HANDLER,
  8515. is_delete_request,
  8516. NULL,
  8517. connect_handler,
  8518. ready_handler,
  8519. data_handler,
  8520. close_handler,
  8521. NULL,
  8522. cbdata);
  8523. }
  8524. void
  8525. mg_set_auth_handler(struct mg_context *ctx,
  8526. const char *uri,
  8527. mg_request_handler handler,
  8528. void *cbdata)
  8529. {
  8530. mg_set_handler_type(ctx,
  8531. uri,
  8532. AUTH_HANDLER,
  8533. handler == NULL,
  8534. NULL,
  8535. NULL,
  8536. NULL,
  8537. NULL,
  8538. NULL,
  8539. handler,
  8540. cbdata);
  8541. }
  8542. static int
  8543. get_request_handler(struct mg_connection *conn,
  8544. int handler_type,
  8545. mg_request_handler *handler,
  8546. mg_websocket_connect_handler *connect_handler,
  8547. mg_websocket_ready_handler *ready_handler,
  8548. mg_websocket_data_handler *data_handler,
  8549. mg_websocket_close_handler *close_handler,
  8550. mg_authorization_handler *auth_handler,
  8551. void **cbdata)
  8552. {
  8553. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8554. if (request_info) {
  8555. const char *uri = request_info->local_uri;
  8556. size_t urilen = strlen(uri);
  8557. struct mg_handler_info *tmp_rh;
  8558. if (!conn || !conn->ctx) {
  8559. return 0;
  8560. }
  8561. mg_lock_context(conn->ctx);
  8562. /* first try for an exact match */
  8563. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8564. tmp_rh = tmp_rh->next) {
  8565. if (tmp_rh->handler_type == handler_type) {
  8566. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8567. if (handler_type == WEBSOCKET_HANDLER) {
  8568. *connect_handler = tmp_rh->connect_handler;
  8569. *ready_handler = tmp_rh->ready_handler;
  8570. *data_handler = tmp_rh->data_handler;
  8571. *close_handler = tmp_rh->close_handler;
  8572. } else if (handler_type == REQUEST_HANDLER) {
  8573. *handler = tmp_rh->handler;
  8574. } else { /* AUTH_HANDLER */
  8575. *auth_handler = tmp_rh->auth_handler;
  8576. }
  8577. *cbdata = tmp_rh->cbdata;
  8578. mg_unlock_context(conn->ctx);
  8579. return 1;
  8580. }
  8581. }
  8582. }
  8583. /* next try for a partial match, we will accept uri/something */
  8584. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8585. tmp_rh = tmp_rh->next) {
  8586. if (tmp_rh->handler_type == handler_type) {
  8587. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8588. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8589. if (handler_type == WEBSOCKET_HANDLER) {
  8590. *connect_handler = tmp_rh->connect_handler;
  8591. *ready_handler = tmp_rh->ready_handler;
  8592. *data_handler = tmp_rh->data_handler;
  8593. *close_handler = tmp_rh->close_handler;
  8594. } else if (handler_type == REQUEST_HANDLER) {
  8595. *handler = tmp_rh->handler;
  8596. } else { /* AUTH_HANDLER */
  8597. *auth_handler = tmp_rh->auth_handler;
  8598. }
  8599. *cbdata = tmp_rh->cbdata;
  8600. mg_unlock_context(conn->ctx);
  8601. return 1;
  8602. }
  8603. }
  8604. }
  8605. /* finally try for pattern match */
  8606. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8607. tmp_rh = tmp_rh->next) {
  8608. if (tmp_rh->handler_type == handler_type) {
  8609. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8610. if (handler_type == WEBSOCKET_HANDLER) {
  8611. *connect_handler = tmp_rh->connect_handler;
  8612. *ready_handler = tmp_rh->ready_handler;
  8613. *data_handler = tmp_rh->data_handler;
  8614. *close_handler = tmp_rh->close_handler;
  8615. } else if (handler_type == REQUEST_HANDLER) {
  8616. *handler = tmp_rh->handler;
  8617. } else { /* AUTH_HANDLER */
  8618. *auth_handler = tmp_rh->auth_handler;
  8619. }
  8620. *cbdata = tmp_rh->cbdata;
  8621. mg_unlock_context(conn->ctx);
  8622. return 1;
  8623. }
  8624. }
  8625. }
  8626. mg_unlock_context(conn->ctx);
  8627. }
  8628. return 0; /* none found */
  8629. }
  8630. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8631. static int
  8632. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8633. void *cbdata)
  8634. {
  8635. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8636. if (pcallbacks->websocket_connect) {
  8637. return pcallbacks->websocket_connect(conn);
  8638. }
  8639. /* No handler set - assume "OK" */
  8640. return 0;
  8641. }
  8642. static void
  8643. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8644. {
  8645. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8646. if (pcallbacks->websocket_ready) {
  8647. pcallbacks->websocket_ready(conn);
  8648. }
  8649. }
  8650. static int
  8651. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8652. int bits,
  8653. char *data,
  8654. size_t len,
  8655. void *cbdata)
  8656. {
  8657. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8658. if (pcallbacks->websocket_data) {
  8659. return pcallbacks->websocket_data(conn, bits, data, len);
  8660. }
  8661. /* No handler set - assume "OK" */
  8662. return 1;
  8663. }
  8664. #endif
  8665. /* This is the heart of the Civetweb's logic.
  8666. * This function is called when the request is read, parsed and validated,
  8667. * and Civetweb must decide what action to take: serve a file, or
  8668. * a directory, or call embedded function, etcetera. */
  8669. static void
  8670. handle_request(struct mg_connection *conn)
  8671. {
  8672. if (conn) {
  8673. struct mg_request_info *ri = &conn->request_info;
  8674. char path[PATH_MAX];
  8675. int uri_len, ssl_index;
  8676. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8677. is_put_or_delete_request = 0, is_callback_resource = 0;
  8678. int i;
  8679. struct file file = STRUCT_FILE_INITIALIZER;
  8680. mg_request_handler callback_handler = NULL;
  8681. mg_websocket_connect_handler ws_connect_handler = NULL;
  8682. mg_websocket_ready_handler ws_ready_handler = NULL;
  8683. mg_websocket_data_handler ws_data_handler = NULL;
  8684. mg_websocket_close_handler ws_close_handler = NULL;
  8685. void *callback_data = NULL;
  8686. mg_authorization_handler auth_handler = NULL;
  8687. void *auth_callback_data = NULL;
  8688. #if !defined(NO_FILES)
  8689. time_t curtime = time(NULL);
  8690. char date[64];
  8691. #endif
  8692. path[0] = 0;
  8693. if (!ri) {
  8694. return;
  8695. }
  8696. /* 1. get the request url */
  8697. /* 1.1. split into url and query string */
  8698. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8699. != NULL) {
  8700. *((char *)conn->request_info.query_string++) = '\0';
  8701. }
  8702. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8703. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8704. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8705. if (ssl_index >= 0) {
  8706. redirect_to_https_port(conn, ssl_index);
  8707. } else {
  8708. /* A http to https forward port has been specified,
  8709. * but no https port to forward to. */
  8710. send_http_error(conn,
  8711. 503,
  8712. "%s",
  8713. "Error: SSL forward not configured properly");
  8714. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8715. }
  8716. return;
  8717. }
  8718. uri_len = (int)strlen(ri->local_uri);
  8719. /* 1.3. decode url (if config says so) */
  8720. if (should_decode_url(conn)) {
  8721. mg_url_decode(
  8722. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8723. }
  8724. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8725. * not possible */
  8726. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8727. /* step 1. completed, the url is known now */
  8728. DEBUG_TRACE("URL: %s", ri->local_uri);
  8729. /* 3. if this ip has limited speed, set it for this connection */
  8730. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8731. get_remote_ip(conn),
  8732. ri->local_uri);
  8733. /* 4. call a "handle everything" callback, if registered */
  8734. if (conn->ctx->callbacks.begin_request != NULL) {
  8735. /* Note that since V1.7 the "begin_request" function is called
  8736. * before an authorization check. If an authorization check is
  8737. * required, use a request_handler instead. */
  8738. i = conn->ctx->callbacks.begin_request(conn);
  8739. if (i > 0) {
  8740. /* callback already processed the request. Store the
  8741. return value as a status code for the access log. */
  8742. conn->status_code = i;
  8743. return;
  8744. } else if (i == 0) {
  8745. /* civetweb should process the request */
  8746. } else {
  8747. /* unspecified - may change with the next version */
  8748. return;
  8749. }
  8750. }
  8751. /* request not yet handled by a handler or redirect, so the request
  8752. * is processed here */
  8753. /* 5. interpret the url to find out how the request must be handled
  8754. */
  8755. /* 5.1. first test, if the request targets the regular http(s)://
  8756. * protocol namespace or the websocket ws(s):// protocol namespace.
  8757. */
  8758. is_websocket_request = is_websocket_protocol(conn);
  8759. /* 5.2. check if the request will be handled by a callback */
  8760. if (get_request_handler(conn,
  8761. is_websocket_request ? WEBSOCKET_HANDLER
  8762. : REQUEST_HANDLER,
  8763. &callback_handler,
  8764. &ws_connect_handler,
  8765. &ws_ready_handler,
  8766. &ws_data_handler,
  8767. &ws_close_handler,
  8768. NULL,
  8769. &callback_data)) {
  8770. /* 5.2.1. A callback will handle this request. All requests
  8771. * handled
  8772. * by a callback have to be considered as requests to a script
  8773. * resource. */
  8774. is_callback_resource = 1;
  8775. is_script_resource = 1;
  8776. is_put_or_delete_request = is_put_or_delete_method(conn);
  8777. } else {
  8778. no_callback_resource:
  8779. /* 5.2.2. No callback is responsible for this request. The URI
  8780. * addresses a file based resource (static content or Lua/cgi
  8781. * scripts in the file system). */
  8782. is_callback_resource = 0;
  8783. interpret_uri(conn,
  8784. path,
  8785. sizeof(path),
  8786. &file,
  8787. &is_found,
  8788. &is_script_resource,
  8789. &is_websocket_request,
  8790. &is_put_or_delete_request);
  8791. }
  8792. /* 6. authorization check */
  8793. /* 6.1. a custom authorization handler is installed */
  8794. if (get_request_handler(conn,
  8795. AUTH_HANDLER,
  8796. NULL,
  8797. NULL,
  8798. NULL,
  8799. NULL,
  8800. NULL,
  8801. &auth_handler,
  8802. &auth_callback_data)) {
  8803. if (!auth_handler(conn, auth_callback_data)) {
  8804. return;
  8805. }
  8806. } else if (is_put_or_delete_request && !is_script_resource
  8807. && !is_callback_resource) {
  8808. /* 6.2. this request is a PUT/DELETE to a real file */
  8809. /* 6.2.1. thus, the server must have real files */
  8810. #if defined(NO_FILES)
  8811. if (1) {
  8812. #else
  8813. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8814. #endif
  8815. /* This server does not have any real files, thus the
  8816. * PUT/DELETE methods are not valid. */
  8817. send_http_error(conn,
  8818. 405,
  8819. "%s method not allowed",
  8820. conn->request_info.request_method);
  8821. return;
  8822. }
  8823. #if !defined(NO_FILES)
  8824. /* 6.2.2. Check if put authorization for static files is
  8825. * available.
  8826. */
  8827. if (!is_authorized_for_put(conn)) {
  8828. send_authorization_request(conn);
  8829. return;
  8830. }
  8831. #endif
  8832. } else {
  8833. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8834. * or it is a PUT or DELETE request to a resource that does not
  8835. * correspond to a file. Check authorization. */
  8836. if (!check_authorization(conn, path)) {
  8837. send_authorization_request(conn);
  8838. return;
  8839. }
  8840. }
  8841. /* request is authorized or does not need authorization */
  8842. /* 7. check if there are request handlers for this uri */
  8843. if (is_callback_resource) {
  8844. if (!is_websocket_request) {
  8845. i = callback_handler(conn, callback_data);
  8846. if (i > 0) {
  8847. /* Do nothing, callback has served the request. Store
  8848. * the
  8849. * return value as status code for the log and discard
  8850. * all
  8851. * data from the client not used by the callback. */
  8852. conn->status_code = i;
  8853. discard_unread_request_data(conn);
  8854. } else {
  8855. /* TODO (high): what if the handler did NOT handle the
  8856. * request */
  8857. /* The last version did handle this as a file request,
  8858. * but
  8859. * since a file request is not always a script resource,
  8860. * the authorization check might be different */
  8861. interpret_uri(conn,
  8862. path,
  8863. sizeof(path),
  8864. &file,
  8865. &is_found,
  8866. &is_script_resource,
  8867. &is_websocket_request,
  8868. &is_put_or_delete_request);
  8869. callback_handler = NULL;
  8870. /* TODO (very low): goto is deprecated but for the
  8871. * moment,
  8872. * a goto is simpler than some curious loop. */
  8873. /* The situation "callback does not handle the request"
  8874. * needs to be reconsidered anyway. */
  8875. goto no_callback_resource;
  8876. }
  8877. } else {
  8878. #if defined(USE_WEBSOCKET)
  8879. handle_websocket_request(conn,
  8880. path,
  8881. is_callback_resource,
  8882. ws_connect_handler,
  8883. ws_ready_handler,
  8884. ws_data_handler,
  8885. ws_close_handler,
  8886. callback_data);
  8887. #endif
  8888. }
  8889. return;
  8890. }
  8891. /* 8. handle websocket requests */
  8892. #if defined(USE_WEBSOCKET)
  8893. if (is_websocket_request) {
  8894. if (is_script_resource) {
  8895. /* Websocket Lua script */
  8896. handle_websocket_request(conn,
  8897. path,
  8898. 0 /* Lua Script */,
  8899. NULL,
  8900. NULL,
  8901. NULL,
  8902. NULL,
  8903. &conn->ctx->callbacks);
  8904. } else {
  8905. #if defined(MG_LEGACY_INTERFACE)
  8906. handle_websocket_request(
  8907. conn,
  8908. path,
  8909. !is_script_resource /* could be deprecated global callback */,
  8910. deprecated_websocket_connect_wrapper,
  8911. deprecated_websocket_ready_wrapper,
  8912. deprecated_websocket_data_wrapper,
  8913. NULL,
  8914. &conn->ctx->callbacks);
  8915. #else
  8916. send_http_error(conn, 404, "%s", "Not found");
  8917. #endif
  8918. }
  8919. return;
  8920. } else
  8921. #endif
  8922. #if defined(NO_FILES)
  8923. /* 9a. In case the server uses only callbacks, this uri is
  8924. * unknown.
  8925. * Then, all request handling ends here. */
  8926. send_http_error(conn, 404, "%s", "Not Found");
  8927. #else
  8928. /* 9b. This request is either for a static file or resource handled
  8929. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8930. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8931. send_http_error(conn, 404, "%s", "Not Found");
  8932. return;
  8933. }
  8934. /* 10. File is handled by a script. */
  8935. if (is_script_resource) {
  8936. handle_file_based_request(conn, path, &file);
  8937. return;
  8938. }
  8939. /* 11. Handle put/delete/mkcol requests */
  8940. if (is_put_or_delete_request) {
  8941. /* 11.1. PUT method */
  8942. if (!strcmp(ri->request_method, "PUT")) {
  8943. put_file(conn, path);
  8944. return;
  8945. }
  8946. /* 11.2. DELETE method */
  8947. if (!strcmp(ri->request_method, "DELETE")) {
  8948. delete_file(conn, path);
  8949. return;
  8950. }
  8951. /* 11.3. MKCOL method */
  8952. if (!strcmp(ri->request_method, "MKCOL")) {
  8953. mkcol(conn, path);
  8954. return;
  8955. }
  8956. /* 11.4. PATCH method
  8957. * This method is not supported for static resources,
  8958. * only for scripts (Lua, CGI) and callbacks. */
  8959. send_http_error(conn,
  8960. 405,
  8961. "%s method not allowed",
  8962. conn->request_info.request_method);
  8963. return;
  8964. }
  8965. /* 11. File does not exist, or it was configured that it should be
  8966. * hidden */
  8967. if (!is_found || (must_hide_file(conn, path))) {
  8968. send_http_error(conn, 404, "%s", "Not found");
  8969. return;
  8970. }
  8971. /* 12. Directory uris should end with a slash */
  8972. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8973. gmt_time_string(date, sizeof(date), &curtime);
  8974. mg_printf(conn,
  8975. "HTTP/1.1 301 Moved Permanently\r\n"
  8976. "Location: %s/\r\n"
  8977. "Date: %s\r\n"
  8978. /* "Cache-Control: private\r\n" (= default) */
  8979. "Content-Length: 0\r\n"
  8980. "Connection: %s\r\n\r\n",
  8981. ri->request_uri,
  8982. date,
  8983. suggest_connection_header(conn));
  8984. return;
  8985. }
  8986. /* 13. Handle other methods than GET/HEAD */
  8987. /* 13.1. Handle PROPFIND */
  8988. if (!strcmp(ri->request_method, "PROPFIND")) {
  8989. handle_propfind(conn, path, &file);
  8990. return;
  8991. }
  8992. /* 13.2. Handle OPTIONS for files */
  8993. if (!strcmp(ri->request_method, "OPTIONS")) {
  8994. /* This standard handler is only used for real files.
  8995. * Scripts should support the OPTIONS method themselves, to allow a
  8996. * maximum flexibility.
  8997. * Lua and CGI scripts may fully support CORS this way (including
  8998. * preflights). */
  8999. send_options(conn);
  9000. return;
  9001. }
  9002. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9003. if (0 != strcmp(ri->request_method, "GET")
  9004. && 0 != strcmp(ri->request_method, "HEAD")) {
  9005. send_http_error(conn,
  9006. 405,
  9007. "%s method not allowed",
  9008. conn->request_info.request_method);
  9009. return;
  9010. }
  9011. /* 14. directories */
  9012. if (file.is_directory) {
  9013. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9014. /* 14.1. use a substitute file */
  9015. /* TODO (high): substitute index may be a script resource.
  9016. * define what should be possible in this case. */
  9017. } else {
  9018. /* 14.2. no substitute file */
  9019. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9020. "yes")) {
  9021. handle_directory_request(conn, path);
  9022. } else {
  9023. send_http_error(conn,
  9024. 403,
  9025. "%s",
  9026. "Error: Directory listing denied");
  9027. }
  9028. return;
  9029. }
  9030. }
  9031. handle_file_based_request(conn, path, &file);
  9032. #endif /* !defined(NO_FILES) */
  9033. #if 0
  9034. /* Perform redirect and auth checks before calling begin_request()
  9035. * handler.
  9036. * Otherwise, begin_request() would need to perform auth checks and
  9037. * redirects. */
  9038. #endif
  9039. }
  9040. return;
  9041. }
  9042. static void
  9043. handle_file_based_request(struct mg_connection *conn,
  9044. const char *path,
  9045. struct file *file)
  9046. {
  9047. if (!conn || !conn->ctx) {
  9048. return;
  9049. }
  9050. if (0) {
  9051. #ifdef USE_LUA
  9052. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9053. strlen(
  9054. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9055. path) > 0) {
  9056. /* Lua server page: an SSI like page containing mostly plain html
  9057. * code
  9058. * plus some tags with server generated contents. */
  9059. handle_lsp_request(conn, path, file, NULL);
  9060. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9061. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9062. path) > 0) {
  9063. /* Lua in-server module script: a CGI like script used to generate
  9064. * the
  9065. * entire reply. */
  9066. mg_exec_lua_script(conn, path, NULL);
  9067. #endif
  9068. #if defined(USE_DUKTAPE)
  9069. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9070. strlen(
  9071. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9072. path) > 0) {
  9073. /* Call duktape to generate the page */
  9074. mg_exec_duktape_script(conn, path);
  9075. #endif
  9076. #if !defined(NO_CGI)
  9077. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9078. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9079. path) > 0) {
  9080. /* CGI scripts may support all HTTP methods */
  9081. handle_cgi_request(conn, path);
  9082. #endif /* !NO_CGI */
  9083. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9084. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9085. path) > 0) {
  9086. handle_ssi_file_request(conn, path, file);
  9087. #if !defined(NO_CACHING)
  9088. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9089. /* Send 304 "Not Modified" - this must not send any body data */
  9090. handle_not_modified_static_file_request(conn, file);
  9091. #endif /* !NO_CACHING */
  9092. } else {
  9093. handle_static_file_request(conn, path, file, NULL);
  9094. }
  9095. }
  9096. static void
  9097. close_all_listening_sockets(struct mg_context *ctx)
  9098. {
  9099. unsigned int i;
  9100. if (!ctx) {
  9101. return;
  9102. }
  9103. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9104. closesocket(ctx->listening_sockets[i].sock);
  9105. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9106. }
  9107. mg_free(ctx->listening_sockets);
  9108. ctx->listening_sockets = NULL;
  9109. mg_free(ctx->listening_socket_fds);
  9110. ctx->listening_socket_fds = NULL;
  9111. }
  9112. /* Valid listening port specification is: [ip_address:]port[s]
  9113. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9114. * Examples for IPv6: [::]:80, [::1]:80,
  9115. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9116. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9117. static int
  9118. parse_port_string(const struct vec *vec, struct socket *so)
  9119. {
  9120. unsigned int a, b, c, d, port;
  9121. int ch, len;
  9122. #if defined(USE_IPV6)
  9123. char buf[100] = {0};
  9124. #endif
  9125. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9126. * Also, all-zeroes in the socket address means binding to all addresses
  9127. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9128. memset(so, 0, sizeof(*so));
  9129. so->lsa.sin.sin_family = AF_INET;
  9130. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9131. == 5) {
  9132. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9133. so->lsa.sin.sin_addr.s_addr =
  9134. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9135. so->lsa.sin.sin_port = htons((uint16_t)port);
  9136. #if defined(USE_IPV6)
  9137. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9138. && mg_inet_pton(
  9139. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9140. /* IPv6 address, examples: see above */
  9141. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9142. */
  9143. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9144. #endif
  9145. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9146. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9147. so->lsa.sin.sin_port = htons((uint16_t)port);
  9148. } else {
  9149. /* Parsing failure. Make port invalid. */
  9150. port = 0;
  9151. len = 0;
  9152. }
  9153. /* sscanf and the option splitting code ensure the following condition
  9154. */
  9155. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9156. return 0;
  9157. }
  9158. ch = vec->ptr[len]; /* Next character after the port number */
  9159. so->is_ssl = (ch == 's');
  9160. so->ssl_redir = (ch == 'r');
  9161. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9162. return is_valid_port(port)
  9163. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9164. }
  9165. static int
  9166. set_ports_option(struct mg_context *ctx)
  9167. {
  9168. const char *list;
  9169. int on = 1;
  9170. #if defined(USE_IPV6)
  9171. int off = 0;
  9172. #endif
  9173. struct vec vec;
  9174. struct socket so, *ptr;
  9175. struct pollfd *pfd;
  9176. union usa usa;
  9177. socklen_t len;
  9178. int portsTotal = 0;
  9179. int portsOk = 0;
  9180. if (!ctx) {
  9181. return 0;
  9182. }
  9183. memset(&so, 0, sizeof(so));
  9184. memset(&usa, 0, sizeof(usa));
  9185. len = sizeof(usa);
  9186. list = ctx->config[LISTENING_PORTS];
  9187. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9188. portsTotal++;
  9189. if (!parse_port_string(&vec, &so)) {
  9190. mg_cry(fc(ctx),
  9191. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9192. (int)vec.len,
  9193. vec.ptr,
  9194. portsTotal,
  9195. "[IP_ADDRESS:]PORT[s|r]");
  9196. continue;
  9197. }
  9198. #if !defined(NO_SSL)
  9199. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9200. mg_cry(fc(ctx),
  9201. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9202. "option set?",
  9203. portsTotal);
  9204. continue;
  9205. }
  9206. #endif
  9207. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9208. == INVALID_SOCKET) {
  9209. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9210. continue;
  9211. }
  9212. #ifdef _WIN32
  9213. /* Windows SO_REUSEADDR lets many procs binds to a
  9214. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9215. * if someone already has the socket -- DTL */
  9216. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9217. * Windows might need a few seconds before
  9218. * the same port can be used again in the
  9219. * same process, so a short Sleep may be
  9220. * required between mg_stop and mg_start.
  9221. */
  9222. if (setsockopt(so.sock,
  9223. SOL_SOCKET,
  9224. SO_EXCLUSIVEADDRUSE,
  9225. (SOCK_OPT_TYPE)&on,
  9226. sizeof(on)) != 0) {
  9227. mg_cry(fc(ctx),
  9228. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9229. portsTotal);
  9230. }
  9231. #else
  9232. if (setsockopt(so.sock,
  9233. SOL_SOCKET,
  9234. SO_REUSEADDR,
  9235. (SOCK_OPT_TYPE)&on,
  9236. sizeof(on)) != 0) {
  9237. mg_cry(fc(ctx),
  9238. "cannot set socket option SO_REUSEADDR (entry %i)",
  9239. portsTotal);
  9240. }
  9241. #endif
  9242. #if defined(USE_IPV6)
  9243. if (so.lsa.sa.sa_family == AF_INET6
  9244. && setsockopt(so.sock,
  9245. IPPROTO_IPV6,
  9246. IPV6_V6ONLY,
  9247. (void *)&off,
  9248. sizeof(off)) != 0) {
  9249. mg_cry(fc(ctx),
  9250. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9251. portsTotal);
  9252. }
  9253. #endif
  9254. if (so.lsa.sa.sa_family == AF_INET) {
  9255. len = sizeof(so.lsa.sin);
  9256. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9257. mg_cry(fc(ctx),
  9258. "cannot bind to %.*s: %d (%s)",
  9259. (int)vec.len,
  9260. vec.ptr,
  9261. (int)ERRNO,
  9262. strerror(errno));
  9263. closesocket(so.sock);
  9264. so.sock = INVALID_SOCKET;
  9265. continue;
  9266. }
  9267. }
  9268. #if defined(USE_IPV6)
  9269. else if (so.lsa.sa.sa_family == AF_INET6) {
  9270. len = sizeof(so.lsa.sin6);
  9271. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9272. mg_cry(fc(ctx),
  9273. "cannot bind to IPv6 %.*s: %d (%s)",
  9274. (int)vec.len,
  9275. vec.ptr,
  9276. (int)ERRNO,
  9277. strerror(errno));
  9278. closesocket(so.sock);
  9279. so.sock = INVALID_SOCKET;
  9280. continue;
  9281. }
  9282. }
  9283. #endif
  9284. else {
  9285. mg_cry(fc(ctx),
  9286. "cannot bind: address family not supported (entry %i)",
  9287. portsTotal);
  9288. continue;
  9289. }
  9290. if (listen(so.sock, SOMAXCONN) != 0) {
  9291. mg_cry(fc(ctx),
  9292. "cannot listen to %.*s: %d (%s)",
  9293. (int)vec.len,
  9294. vec.ptr,
  9295. (int)ERRNO,
  9296. strerror(errno));
  9297. closesocket(so.sock);
  9298. so.sock = INVALID_SOCKET;
  9299. continue;
  9300. }
  9301. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9302. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9303. int err = (int)ERRNO;
  9304. mg_cry(fc(ctx),
  9305. "call to getsockname failed %.*s: %d (%s)",
  9306. (int)vec.len,
  9307. vec.ptr,
  9308. err,
  9309. strerror(errno));
  9310. closesocket(so.sock);
  9311. so.sock = INVALID_SOCKET;
  9312. continue;
  9313. }
  9314. /* Update lsa port in case of random free ports */
  9315. #if defined(USE_IPV6)
  9316. if (so.lsa.sa.sa_family == AF_INET6) {
  9317. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9318. } else
  9319. #endif
  9320. {
  9321. so.lsa.sin.sin_port = usa.sin.sin_port;
  9322. }
  9323. if ((ptr = (struct socket *)
  9324. mg_realloc(ctx->listening_sockets,
  9325. (ctx->num_listening_sockets + 1)
  9326. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9327. mg_cry(fc(ctx), "%s", "Out of memory");
  9328. closesocket(so.sock);
  9329. so.sock = INVALID_SOCKET;
  9330. continue;
  9331. }
  9332. if ((pfd = (struct pollfd *)mg_realloc(
  9333. ctx->listening_socket_fds,
  9334. (ctx->num_listening_sockets + 1)
  9335. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9336. mg_cry(fc(ctx), "%s", "Out of memory");
  9337. closesocket(so.sock);
  9338. so.sock = INVALID_SOCKET;
  9339. mg_free(ptr);
  9340. continue;
  9341. }
  9342. set_close_on_exec(so.sock, fc(ctx));
  9343. ctx->listening_sockets = ptr;
  9344. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9345. ctx->listening_socket_fds = pfd;
  9346. ctx->num_listening_sockets++;
  9347. portsOk++;
  9348. }
  9349. if (portsOk != portsTotal) {
  9350. close_all_listening_sockets(ctx);
  9351. portsOk = 0;
  9352. }
  9353. return portsOk;
  9354. }
  9355. static const char *
  9356. header_val(const struct mg_connection *conn, const char *header)
  9357. {
  9358. const char *header_value;
  9359. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9360. return "-";
  9361. } else {
  9362. return header_value;
  9363. }
  9364. }
  9365. static void
  9366. log_access(const struct mg_connection *conn)
  9367. {
  9368. const struct mg_request_info *ri;
  9369. struct file fi;
  9370. char date[64], src_addr[IP_ADDR_STR_LEN];
  9371. struct tm *tm;
  9372. const char *referer;
  9373. const char *user_agent;
  9374. char buf[4096];
  9375. if (!conn || !conn->ctx) {
  9376. return;
  9377. }
  9378. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9379. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9380. == 0) {
  9381. fi.fp = NULL;
  9382. }
  9383. } else {
  9384. fi.fp = NULL;
  9385. }
  9386. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9387. return;
  9388. }
  9389. tm = localtime(&conn->conn_birth_time);
  9390. if (tm != NULL) {
  9391. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9392. } else {
  9393. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9394. date[sizeof(date) - 1] = '\0';
  9395. }
  9396. ri = &conn->request_info;
  9397. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9398. referer = header_val(conn, "Referer");
  9399. user_agent = header_val(conn, "User-Agent");
  9400. mg_snprintf(conn,
  9401. NULL, /* Ignore truncation in access log */
  9402. buf,
  9403. sizeof(buf),
  9404. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9405. src_addr,
  9406. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9407. date,
  9408. ri->request_method ? ri->request_method : "-",
  9409. ri->request_uri ? ri->request_uri : "-",
  9410. ri->query_string ? "?" : "",
  9411. ri->query_string ? ri->query_string : "",
  9412. ri->http_version,
  9413. conn->status_code,
  9414. conn->num_bytes_sent,
  9415. referer,
  9416. user_agent);
  9417. if (conn->ctx->callbacks.log_access) {
  9418. conn->ctx->callbacks.log_access(conn, buf);
  9419. }
  9420. if (fi.fp) {
  9421. flockfile(fi.fp);
  9422. fprintf(fi.fp, "%s\n", buf);
  9423. fflush(fi.fp);
  9424. funlockfile(fi.fp);
  9425. mg_fclose(&fi);
  9426. }
  9427. }
  9428. /* Verify given socket address against the ACL.
  9429. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9430. */
  9431. static int
  9432. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9433. {
  9434. int allowed, flag;
  9435. uint32_t net, mask;
  9436. struct vec vec;
  9437. if (ctx) {
  9438. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9439. /* If any ACL is set, deny by default */
  9440. allowed = (list == NULL) ? '+' : '-';
  9441. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9442. flag = vec.ptr[0];
  9443. if ((flag != '+' && flag != '-')
  9444. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9445. mg_cry(fc(ctx),
  9446. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9447. __func__);
  9448. return -1;
  9449. }
  9450. if (net == (remote_ip & mask)) {
  9451. allowed = flag;
  9452. }
  9453. }
  9454. return allowed == '+';
  9455. }
  9456. return -1;
  9457. }
  9458. #if !defined(_WIN32)
  9459. static int
  9460. set_uid_option(struct mg_context *ctx)
  9461. {
  9462. struct passwd *pw;
  9463. if (ctx) {
  9464. const char *uid = ctx->config[RUN_AS_USER];
  9465. int success = 0;
  9466. if (uid == NULL) {
  9467. success = 1;
  9468. } else {
  9469. if ((pw = getpwnam(uid)) == NULL) {
  9470. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9471. } else if (setgid(pw->pw_gid) == -1) {
  9472. mg_cry(fc(ctx),
  9473. "%s: setgid(%s): %s",
  9474. __func__,
  9475. uid,
  9476. strerror(errno));
  9477. } else if (setgroups(0, NULL)) {
  9478. mg_cry(fc(ctx),
  9479. "%s: setgroups(): %s",
  9480. __func__,
  9481. strerror(errno));
  9482. } else if (setuid(pw->pw_uid) == -1) {
  9483. mg_cry(fc(ctx),
  9484. "%s: setuid(%s): %s",
  9485. __func__,
  9486. uid,
  9487. strerror(errno));
  9488. } else {
  9489. success = 1;
  9490. }
  9491. }
  9492. return success;
  9493. }
  9494. return 0;
  9495. }
  9496. #endif /* !_WIN32 */
  9497. static void
  9498. tls_dtor(void *key)
  9499. {
  9500. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9501. /* key == pthread_getspecific(sTlsKey); */
  9502. if (tls) {
  9503. if (tls->is_master == 2) {
  9504. tls->is_master = -3; /* Mark memory as dead */
  9505. mg_free(tls);
  9506. }
  9507. }
  9508. pthread_setspecific(sTlsKey, NULL);
  9509. }
  9510. #if !defined(NO_SSL)
  9511. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9512. static unsigned long
  9513. ssl_id_callback(void)
  9514. {
  9515. #ifdef _WIN32
  9516. return GetCurrentThreadId();
  9517. #else
  9518. #ifdef __clang__
  9519. #pragma clang diagnostic push
  9520. #pragma clang diagnostic ignored "-Wunreachable-code"
  9521. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9522. * or not, so one of the two conditions will be unreachable by construction.
  9523. * Unfortunately the C standard does not define a way to check this at
  9524. * compile time, since the #if preprocessor conditions can not use the sizeof
  9525. * operator as an argument. */
  9526. #endif
  9527. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9528. /* This is the problematic case for CRYPTO_set_id_callback:
  9529. * The OS pthread_t can not be cast to unsigned long. */
  9530. struct mg_workerTLS *tls =
  9531. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9532. if (tls == NULL) {
  9533. /* SSL called from an unknown thread: Create some thread index.
  9534. */
  9535. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9536. tls->is_master = -2; /* -2 means "3rd party thread" */
  9537. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9538. pthread_setspecific(sTlsKey, tls);
  9539. }
  9540. return tls->thread_idx;
  9541. } else {
  9542. /* pthread_t may be any data type, so a simple cast to unsigned long
  9543. * can rise a warning/error, depending on the platform.
  9544. * Here memcpy is used as an anything-to-anything cast. */
  9545. unsigned long ret = 0;
  9546. pthread_t t = pthread_self();
  9547. memcpy(&ret, &t, sizeof(pthread_t));
  9548. return ret;
  9549. }
  9550. #ifdef __clang__
  9551. #pragma clang diagnostic pop
  9552. #endif
  9553. #endif
  9554. }
  9555. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9556. static const char *ssl_error(void);
  9557. static int
  9558. refresh_trust(struct mg_connection *conn)
  9559. {
  9560. static int reload_lock = 0;
  9561. static long int data_check = 0;
  9562. struct stat cert_buf;
  9563. long int t;
  9564. char *pem;
  9565. int should_verify_peer;
  9566. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9567. && conn->ctx->callbacks.init_ssl == NULL) {
  9568. return 0;
  9569. }
  9570. t = data_check;
  9571. if (stat(pem, &cert_buf) != -1) {
  9572. t = (long int)cert_buf.st_mtime;
  9573. }
  9574. if (data_check != t) {
  9575. data_check = t;
  9576. should_verify_peer =
  9577. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9578. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9579. == 0);
  9580. if (should_verify_peer) {
  9581. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9582. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9583. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9584. ca_file,
  9585. ca_path) != 1) {
  9586. mg_cry(fc(conn->ctx),
  9587. "SSL_CTX_load_verify_locations error: %s "
  9588. "ssl_verify_peer requires setting "
  9589. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9590. "present in "
  9591. "the .conf file?",
  9592. ssl_error());
  9593. return 0;
  9594. }
  9595. }
  9596. if (!reload_lock) {
  9597. reload_lock = 1;
  9598. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9599. return 0;
  9600. }
  9601. reload_lock = 0;
  9602. }
  9603. }
  9604. /* lock while cert is reloading */
  9605. while (reload_lock) {
  9606. sleep(1);
  9607. }
  9608. return 1;
  9609. }
  9610. static pthread_mutex_t *ssl_mutexes;
  9611. static int
  9612. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9613. {
  9614. int ret, err;
  9615. int short_trust;
  9616. unsigned i;
  9617. if (!conn) {
  9618. return 0;
  9619. }
  9620. short_trust =
  9621. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9622. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9623. if (short_trust) {
  9624. int trust_ret = refresh_trust(conn);
  9625. if (!trust_ret) {
  9626. return trust_ret;
  9627. }
  9628. }
  9629. conn->ssl = SSL_new(s);
  9630. if (conn->ssl == NULL) {
  9631. return 0;
  9632. }
  9633. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9634. if (ret != 1) {
  9635. err = SSL_get_error(conn->ssl, ret);
  9636. (void)err; /* TODO: set some error message */
  9637. SSL_free(conn->ssl);
  9638. conn->ssl = NULL;
  9639. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9640. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9641. ERR_remove_state(0);
  9642. return 0;
  9643. }
  9644. /* SSL functions may fail and require to be called again:
  9645. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9646. * Here "func" could be SSL_connect or SSL_accept. */
  9647. for (i = 0; i <= 16; i *= 2) {
  9648. ret = func(conn->ssl);
  9649. if (ret != 1) {
  9650. err = SSL_get_error(conn->ssl, ret);
  9651. if ((err == SSL_ERROR_WANT_CONNECT)
  9652. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9653. /* Retry */
  9654. mg_sleep(i);
  9655. } else {
  9656. /* This is an error */
  9657. /* TODO: set some error message */
  9658. break;
  9659. }
  9660. } else {
  9661. /* success */
  9662. break;
  9663. }
  9664. }
  9665. if (ret != 1) {
  9666. SSL_free(conn->ssl);
  9667. conn->ssl = NULL;
  9668. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9669. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9670. ERR_remove_state(0);
  9671. return 0;
  9672. }
  9673. return 1;
  9674. }
  9675. /* Return OpenSSL error message (from CRYPTO lib) */
  9676. static const char *
  9677. ssl_error(void)
  9678. {
  9679. unsigned long err;
  9680. err = ERR_get_error();
  9681. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9682. }
  9683. static void
  9684. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9685. {
  9686. (void)line;
  9687. (void)file;
  9688. if (mode & 1) {
  9689. /* 1 is CRYPTO_LOCK */
  9690. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9691. } else {
  9692. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9693. }
  9694. }
  9695. #if !defined(NO_SSL_DL)
  9696. static void *
  9697. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9698. {
  9699. union {
  9700. void *p;
  9701. void (*fp)(void);
  9702. } u;
  9703. void *dll_handle;
  9704. struct ssl_func *fp;
  9705. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9706. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9707. return NULL;
  9708. }
  9709. for (fp = sw; fp->name != NULL; fp++) {
  9710. #ifdef _WIN32
  9711. /* GetProcAddress() returns pointer to function */
  9712. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9713. #else
  9714. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9715. * pointers to function pointers. We need to use a union to make a
  9716. * cast. */
  9717. u.p = dlsym(dll_handle, fp->name);
  9718. #endif /* _WIN32 */
  9719. if (u.fp == NULL) {
  9720. mg_cry(fc(ctx),
  9721. "%s: %s: cannot find %s",
  9722. __func__,
  9723. dll_name,
  9724. fp->name);
  9725. dlclose(dll_handle);
  9726. return NULL;
  9727. } else {
  9728. fp->ptr = u.fp;
  9729. }
  9730. }
  9731. return dll_handle;
  9732. }
  9733. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9734. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9735. #endif /* NO_SSL_DL */
  9736. #if defined(SSL_ALREADY_INITIALIZED)
  9737. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9738. #else
  9739. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9740. #endif
  9741. static int
  9742. initialize_ssl(struct mg_context *ctx)
  9743. {
  9744. int i;
  9745. size_t size;
  9746. #if !defined(NO_SSL_DL)
  9747. if (!cryptolib_dll_handle) {
  9748. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9749. if (!cryptolib_dll_handle) {
  9750. return 0;
  9751. }
  9752. }
  9753. #endif /* NO_SSL_DL */
  9754. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9755. return 1;
  9756. }
  9757. /* Initialize locking callbacks, needed for thread safety.
  9758. * http://www.openssl.org/support/faq.html#PROG1
  9759. */
  9760. i = CRYPTO_num_locks();
  9761. if (i < 0) {
  9762. i = 0;
  9763. }
  9764. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9765. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9766. mg_cry(fc(ctx),
  9767. "%s: cannot allocate mutexes: %s",
  9768. __func__,
  9769. ssl_error());
  9770. return 0;
  9771. }
  9772. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9773. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9774. }
  9775. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9776. CRYPTO_set_id_callback(&ssl_id_callback);
  9777. return 1;
  9778. }
  9779. static int
  9780. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9781. {
  9782. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9783. mg_cry(fc(ctx),
  9784. "%s: cannot open certificate file %s: %s",
  9785. __func__,
  9786. pem,
  9787. ssl_error());
  9788. return 0;
  9789. }
  9790. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9791. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9792. mg_cry(fc(ctx),
  9793. "%s: cannot open private key file %s: %s",
  9794. __func__,
  9795. pem,
  9796. ssl_error());
  9797. return 0;
  9798. }
  9799. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9800. mg_cry(fc(ctx),
  9801. "%s: certificate and private key do not match: %s",
  9802. __func__,
  9803. pem);
  9804. return 0;
  9805. }
  9806. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9807. mg_cry(fc(ctx),
  9808. "%s: cannot use certificate chain file %s: %s",
  9809. __func__,
  9810. pem,
  9811. ssl_error());
  9812. return 0;
  9813. }
  9814. return 1;
  9815. }
  9816. static long
  9817. ssl_get_protocol(int version_id)
  9818. {
  9819. long ret = SSL_OP_ALL;
  9820. if (version_id > 0)
  9821. ret |= SSL_OP_NO_SSLv2;
  9822. if (version_id > 1)
  9823. ret |= SSL_OP_NO_SSLv3;
  9824. if (version_id > 2)
  9825. ret |= SSL_OP_NO_TLSv1;
  9826. if (version_id > 3)
  9827. ret |= SSL_OP_NO_TLSv1_1;
  9828. return ret;
  9829. }
  9830. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9831. static int
  9832. set_ssl_option(struct mg_context *ctx)
  9833. {
  9834. const char *pem;
  9835. int callback_ret;
  9836. int should_verify_peer;
  9837. const char *ca_path;
  9838. const char *ca_file;
  9839. int use_default_verify_paths;
  9840. int verify_depth;
  9841. time_t now_rt = time(NULL);
  9842. struct timespec now_mt;
  9843. md5_byte_t ssl_context_id[16];
  9844. md5_state_t md5state;
  9845. int protocol_ver;
  9846. /* If PEM file is not specified and the init_ssl callback
  9847. * is not specified, skip SSL initialization. */
  9848. if (!ctx) {
  9849. return 0;
  9850. }
  9851. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9852. && ctx->callbacks.init_ssl == NULL) {
  9853. return 1;
  9854. }
  9855. if (!initialize_ssl(ctx)) {
  9856. return 0;
  9857. }
  9858. #if !defined(NO_SSL_DL)
  9859. if (!ssllib_dll_handle) {
  9860. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9861. if (!ssllib_dll_handle) {
  9862. return 0;
  9863. }
  9864. }
  9865. #endif /* NO_SSL_DL */
  9866. /* Initialize SSL library */
  9867. SSL_library_init();
  9868. SSL_load_error_strings();
  9869. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9870. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9871. return 0;
  9872. }
  9873. SSL_CTX_clear_options(ctx->ssl_ctx,
  9874. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9875. | SSL_OP_NO_TLSv1_1);
  9876. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9877. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9878. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9879. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9880. /* If a callback has been specified, call it. */
  9881. callback_ret =
  9882. (ctx->callbacks.init_ssl == NULL)
  9883. ? 0
  9884. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9885. /* If callback returns 0, civetweb sets up the SSL certificate.
  9886. * If it returns 1, civetweb assumes the calback already did this.
  9887. * If it returns -1, initializing ssl fails. */
  9888. if (callback_ret < 0) {
  9889. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9890. return 0;
  9891. }
  9892. if (callback_ret > 0) {
  9893. if (pem != NULL) {
  9894. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9895. }
  9896. return 1;
  9897. }
  9898. /* Use some UID as session context ID. */
  9899. md5_init(&md5state);
  9900. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9901. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9902. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9903. md5_append(&md5state,
  9904. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9905. strlen(ctx->config[LISTENING_PORTS]));
  9906. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9907. md5_finish(&md5state, ssl_context_id);
  9908. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9909. (const unsigned char *)&ssl_context_id,
  9910. sizeof(ssl_context_id));
  9911. if (pem != NULL) {
  9912. if (!ssl_use_pem_file(ctx, pem)) {
  9913. return 0;
  9914. }
  9915. }
  9916. should_verify_peer =
  9917. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9918. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9919. use_default_verify_paths =
  9920. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9921. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9922. if (should_verify_peer) {
  9923. ca_path = ctx->config[SSL_CA_PATH];
  9924. ca_file = ctx->config[SSL_CA_FILE];
  9925. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9926. != 1) {
  9927. mg_cry(fc(ctx),
  9928. "SSL_CTX_load_verify_locations error: %s "
  9929. "ssl_verify_peer requires setting "
  9930. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9931. "present in "
  9932. "the .conf file?",
  9933. ssl_error());
  9934. return 0;
  9935. }
  9936. SSL_CTX_set_verify(ctx->ssl_ctx,
  9937. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9938. NULL);
  9939. if (use_default_verify_paths
  9940. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9941. mg_cry(fc(ctx),
  9942. "SSL_CTX_set_default_verify_paths error: %s",
  9943. ssl_error());
  9944. return 0;
  9945. }
  9946. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9947. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9948. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9949. }
  9950. }
  9951. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9952. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9953. != 1) {
  9954. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9955. }
  9956. }
  9957. return 1;
  9958. }
  9959. static void
  9960. uninitialize_ssl(struct mg_context *ctx)
  9961. {
  9962. int i;
  9963. (void)ctx;
  9964. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9965. /* Shutdown according to
  9966. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9967. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9968. */
  9969. CRYPTO_set_locking_callback(NULL);
  9970. CRYPTO_set_id_callback(NULL);
  9971. ENGINE_cleanup();
  9972. CONF_modules_unload(1);
  9973. ERR_free_strings();
  9974. EVP_cleanup();
  9975. CRYPTO_cleanup_all_ex_data();
  9976. ERR_remove_state(0);
  9977. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9978. pthread_mutex_destroy(&ssl_mutexes[i]);
  9979. }
  9980. mg_free(ssl_mutexes);
  9981. ssl_mutexes = NULL;
  9982. }
  9983. }
  9984. #endif /* !NO_SSL */
  9985. static int
  9986. set_gpass_option(struct mg_context *ctx)
  9987. {
  9988. if (ctx) {
  9989. struct file file = STRUCT_FILE_INITIALIZER;
  9990. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9991. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9992. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9993. return 0;
  9994. }
  9995. return 1;
  9996. }
  9997. return 0;
  9998. }
  9999. static int
  10000. set_acl_option(struct mg_context *ctx)
  10001. {
  10002. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10003. }
  10004. static void
  10005. reset_per_request_attributes(struct mg_connection *conn)
  10006. {
  10007. if (!conn) {
  10008. return;
  10009. }
  10010. conn->path_info = NULL;
  10011. conn->num_bytes_sent = conn->consumed_content = 0;
  10012. conn->status_code = -1;
  10013. conn->is_chunked = 0;
  10014. conn->must_close = conn->request_len = conn->throttle = 0;
  10015. conn->request_info.content_length = -1;
  10016. conn->request_info.remote_user = NULL;
  10017. conn->request_info.request_method = NULL;
  10018. conn->request_info.request_uri = NULL;
  10019. conn->request_info.local_uri = NULL;
  10020. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10021. * local_uri and request_uri */
  10022. conn->request_info.http_version = NULL;
  10023. conn->request_info.num_headers = 0;
  10024. conn->data_len = 0;
  10025. conn->chunk_remainder = 0;
  10026. conn->internal_error = 0;
  10027. }
  10028. static int
  10029. set_sock_timeout(SOCKET sock, int milliseconds)
  10030. {
  10031. int r0 = 0, r1, r2;
  10032. #ifdef _WIN32
  10033. /* Windows specific */
  10034. DWORD tv = (DWORD)milliseconds;
  10035. #else
  10036. /* Linux, ... (not Windows) */
  10037. struct timeval tv;
  10038. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10039. * max. time waiting for the acknowledged of TCP data before the connection
  10040. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10041. * If this option is not set, the default timeout of 20-30 minutes is used.
  10042. */
  10043. /* #define TCP_USER_TIMEOUT (18) */
  10044. #if defined(TCP_USER_TIMEOUT)
  10045. unsigned int uto = (unsigned int)milliseconds;
  10046. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10047. #endif
  10048. memset(&tv, 0, sizeof(tv));
  10049. tv.tv_sec = milliseconds / 1000;
  10050. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10051. #endif /* _WIN32 */
  10052. r1 = setsockopt(
  10053. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10054. r2 = setsockopt(
  10055. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10056. return r0 || r1 || r2;
  10057. }
  10058. static int
  10059. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10060. {
  10061. if (setsockopt(sock,
  10062. IPPROTO_TCP,
  10063. TCP_NODELAY,
  10064. (SOCK_OPT_TYPE)&nodelay_on,
  10065. sizeof(nodelay_on)) != 0) {
  10066. /* Error */
  10067. return 1;
  10068. }
  10069. /* OK */
  10070. return 0;
  10071. }
  10072. static void
  10073. close_socket_gracefully(struct mg_connection *conn)
  10074. {
  10075. #if defined(_WIN32)
  10076. char buf[MG_BUF_LEN];
  10077. int n;
  10078. #endif
  10079. struct linger linger;
  10080. if (!conn) {
  10081. return;
  10082. }
  10083. /* Set linger option to avoid socket hanging out after close. This
  10084. * prevent
  10085. * ephemeral port exhaust problem under high QPS. */
  10086. linger.l_onoff = 1;
  10087. linger.l_linger = 1;
  10088. if (setsockopt(conn->client.sock,
  10089. SOL_SOCKET,
  10090. SO_LINGER,
  10091. (char *)&linger,
  10092. sizeof(linger)) != 0) {
  10093. mg_cry(conn,
  10094. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10095. __func__,
  10096. strerror(ERRNO));
  10097. }
  10098. /* Send FIN to the client */
  10099. shutdown(conn->client.sock, SHUT_WR);
  10100. set_non_blocking_mode(conn->client.sock);
  10101. #if defined(_WIN32)
  10102. /* Read and discard pending incoming data. If we do not do that and
  10103. * close
  10104. * the socket, the data in the send buffer may be discarded. This
  10105. * behaviour is seen on Windows, when client keeps sending data
  10106. * when server decides to close the connection; then when client
  10107. * does recv() it gets no data back. */
  10108. do {
  10109. n = pull(
  10110. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10111. } while (n > 0);
  10112. #endif
  10113. /* Now we know that our FIN is ACK-ed, safe to close */
  10114. closesocket(conn->client.sock);
  10115. conn->client.sock = INVALID_SOCKET;
  10116. }
  10117. static void
  10118. close_connection(struct mg_connection *conn)
  10119. {
  10120. if (!conn || !conn->ctx) {
  10121. return;
  10122. }
  10123. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10124. if (conn->lua_websocket_state) {
  10125. lua_websocket_close(conn, conn->lua_websocket_state);
  10126. conn->lua_websocket_state = NULL;
  10127. }
  10128. #endif
  10129. /* call the connection_close callback if assigned */
  10130. if ((conn->ctx->callbacks.connection_close != NULL)
  10131. && (conn->ctx->context_type == 1)) {
  10132. conn->ctx->callbacks.connection_close(conn);
  10133. }
  10134. mg_lock_connection(conn);
  10135. conn->must_close = 1;
  10136. #ifndef NO_SSL
  10137. if (conn->ssl != NULL) {
  10138. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10139. */
  10140. SSL_shutdown(conn->ssl);
  10141. SSL_free(conn->ssl);
  10142. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10143. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10144. ERR_remove_state(0);
  10145. conn->ssl = NULL;
  10146. }
  10147. #endif
  10148. if (conn->client.sock != INVALID_SOCKET) {
  10149. close_socket_gracefully(conn);
  10150. conn->client.sock = INVALID_SOCKET;
  10151. }
  10152. mg_unlock_connection(conn);
  10153. }
  10154. void
  10155. mg_close_connection(struct mg_connection *conn)
  10156. {
  10157. struct mg_context *client_ctx = NULL;
  10158. unsigned int i;
  10159. if (conn == NULL) {
  10160. return;
  10161. }
  10162. if (conn->ctx->context_type == 2) {
  10163. client_ctx = conn->ctx;
  10164. /* client context: loops must end */
  10165. conn->ctx->stop_flag = 1;
  10166. }
  10167. #ifndef NO_SSL
  10168. if (conn->client_ssl_ctx != NULL) {
  10169. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10170. }
  10171. #endif
  10172. close_connection(conn);
  10173. if (client_ctx != NULL) {
  10174. /* join worker thread and free context */
  10175. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10176. if (client_ctx->workerthreadids[i] != 0) {
  10177. mg_join_thread(client_ctx->workerthreadids[i]);
  10178. }
  10179. }
  10180. mg_free(client_ctx->workerthreadids);
  10181. mg_free(client_ctx);
  10182. (void)pthread_mutex_destroy(&conn->mutex);
  10183. mg_free(conn);
  10184. }
  10185. }
  10186. static struct mg_connection *
  10187. mg_connect_client_impl(const struct mg_client_options *client_options,
  10188. int use_ssl,
  10189. char *ebuf,
  10190. size_t ebuf_len)
  10191. {
  10192. static struct mg_context fake_ctx;
  10193. struct mg_connection *conn = NULL;
  10194. SOCKET sock;
  10195. union usa sa;
  10196. if (!connect_socket(&fake_ctx,
  10197. client_options->host,
  10198. client_options->port,
  10199. use_ssl,
  10200. ebuf,
  10201. ebuf_len,
  10202. &sock,
  10203. &sa)) {
  10204. ;
  10205. } else if ((conn = (struct mg_connection *)
  10206. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10207. mg_snprintf(NULL,
  10208. NULL, /* No truncation check for ebuf */
  10209. ebuf,
  10210. ebuf_len,
  10211. "calloc(): %s",
  10212. strerror(ERRNO));
  10213. closesocket(sock);
  10214. #ifndef NO_SSL
  10215. } else if (use_ssl
  10216. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10217. == NULL) {
  10218. mg_snprintf(NULL,
  10219. NULL, /* No truncation check for ebuf */
  10220. ebuf,
  10221. ebuf_len,
  10222. "SSL_CTX_new error");
  10223. closesocket(sock);
  10224. mg_free(conn);
  10225. conn = NULL;
  10226. #endif /* NO_SSL */
  10227. } else {
  10228. #ifdef USE_IPV6
  10229. socklen_t len = (sa.sa.sa_family == AF_INET)
  10230. ? sizeof(conn->client.rsa.sin)
  10231. : sizeof(conn->client.rsa.sin6);
  10232. struct sockaddr *psa =
  10233. (sa.sa.sa_family == AF_INET)
  10234. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10235. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10236. #else
  10237. socklen_t len = sizeof(conn->client.rsa.sin);
  10238. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10239. #endif
  10240. conn->buf_size = MAX_REQUEST_SIZE;
  10241. conn->buf = (char *)(conn + 1);
  10242. conn->ctx = &fake_ctx;
  10243. conn->client.sock = sock;
  10244. conn->client.lsa = sa;
  10245. if (getsockname(sock, psa, &len) != 0) {
  10246. mg_cry(conn,
  10247. "%s: getsockname() failed: %s",
  10248. __func__,
  10249. strerror(ERRNO));
  10250. }
  10251. conn->client.is_ssl = use_ssl ? 1 : 0;
  10252. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10253. #ifndef NO_SSL
  10254. if (use_ssl) {
  10255. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10256. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10257. * SSL_CTX_set_verify call is needed to switch off server
  10258. * certificate checking, which is off by default in OpenSSL and
  10259. * on in yaSSL. */
  10260. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10261. * SSL_VERIFY_PEER, verify_ssl_server); */
  10262. if (client_options->client_cert) {
  10263. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10264. mg_snprintf(NULL,
  10265. NULL, /* No truncation check for ebuf */
  10266. ebuf,
  10267. ebuf_len,
  10268. "Can not use SSL client certificate");
  10269. SSL_CTX_free(conn->client_ssl_ctx);
  10270. closesocket(sock);
  10271. mg_free(conn);
  10272. conn = NULL;
  10273. }
  10274. }
  10275. if (client_options->server_cert) {
  10276. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10277. client_options->server_cert,
  10278. NULL);
  10279. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10280. } else {
  10281. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10282. }
  10283. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10284. mg_snprintf(NULL,
  10285. NULL, /* No truncation check for ebuf */
  10286. ebuf,
  10287. ebuf_len,
  10288. "SSL connection error");
  10289. SSL_CTX_free(conn->client_ssl_ctx);
  10290. closesocket(sock);
  10291. mg_free(conn);
  10292. conn = NULL;
  10293. }
  10294. }
  10295. #endif
  10296. }
  10297. return conn;
  10298. }
  10299. CIVETWEB_API struct mg_connection *
  10300. mg_connect_client_secure(const struct mg_client_options *client_options,
  10301. char *error_buffer,
  10302. size_t error_buffer_size)
  10303. {
  10304. return mg_connect_client_impl(client_options,
  10305. 1,
  10306. error_buffer,
  10307. error_buffer_size);
  10308. }
  10309. struct mg_connection *
  10310. mg_connect_client(const char *host,
  10311. int port,
  10312. int use_ssl,
  10313. char *error_buffer,
  10314. size_t error_buffer_size)
  10315. {
  10316. struct mg_client_options opts;
  10317. memset(&opts, 0, sizeof(opts));
  10318. opts.host = host;
  10319. opts.port = port;
  10320. return mg_connect_client_impl(&opts,
  10321. use_ssl,
  10322. error_buffer,
  10323. error_buffer_size);
  10324. }
  10325. static const struct {
  10326. const char *proto;
  10327. size_t proto_len;
  10328. unsigned default_port;
  10329. } abs_uri_protocols[] = {{"http://", 7, 80},
  10330. {"https://", 8, 443},
  10331. {"ws://", 5, 80},
  10332. {"wss://", 6, 443},
  10333. {NULL, 0, 0}};
  10334. /* Check if the uri is valid.
  10335. * return 0 for invalid uri,
  10336. * return 1 for *,
  10337. * return 2 for relative uri,
  10338. * return 3 for absolute uri without port,
  10339. * return 4 for absolute uri with port */
  10340. static int
  10341. get_uri_type(const char *uri)
  10342. {
  10343. int i;
  10344. char *hostend, *portbegin, *portend;
  10345. unsigned long port;
  10346. /* According to the HTTP standard
  10347. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10348. * URI can be an asterisk (*) or should start with slash (relative uri),
  10349. * or it should start with the protocol (absolute uri). */
  10350. if (uri[0] == '*' && uri[1] == '\0') {
  10351. /* asterisk */
  10352. return 1;
  10353. }
  10354. if (uri[0] == '/') {
  10355. /* relative uri */
  10356. return 2;
  10357. }
  10358. /* It could be an absolute uri: */
  10359. /* This function only checks if the uri is valid, not if it is
  10360. * addressing the current server. So civetweb can also be used
  10361. * as a proxy server. */
  10362. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10363. if (mg_strncasecmp(uri,
  10364. abs_uri_protocols[i].proto,
  10365. abs_uri_protocols[i].proto_len) == 0) {
  10366. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10367. if (!hostend) {
  10368. return 0;
  10369. }
  10370. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10371. if (!portbegin) {
  10372. return 3;
  10373. }
  10374. port = strtoul(portbegin + 1, &portend, 10);
  10375. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10376. return 0;
  10377. }
  10378. return 4;
  10379. }
  10380. }
  10381. return 0;
  10382. }
  10383. /* Return NULL or the relative uri at the current server */
  10384. static const char *
  10385. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10386. {
  10387. const char *server_domain;
  10388. size_t server_domain_len;
  10389. size_t request_domain_len = 0;
  10390. unsigned long port = 0;
  10391. int i;
  10392. const char *hostbegin = NULL;
  10393. const char *hostend = NULL;
  10394. const char *portbegin;
  10395. char *portend;
  10396. /* DNS is case insensitive, so use case insensitive string compare here
  10397. */
  10398. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10399. if (!server_domain) {
  10400. return 0;
  10401. }
  10402. server_domain_len = strlen(server_domain);
  10403. if (!server_domain_len) {
  10404. return 0;
  10405. }
  10406. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10407. if (mg_strncasecmp(uri,
  10408. abs_uri_protocols[i].proto,
  10409. abs_uri_protocols[i].proto_len) == 0) {
  10410. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10411. hostend = strchr(hostbegin, '/');
  10412. if (!hostend) {
  10413. return 0;
  10414. }
  10415. portbegin = strchr(hostbegin, ':');
  10416. if ((!portbegin) || (portbegin > hostend)) {
  10417. port = abs_uri_protocols[i].default_port;
  10418. request_domain_len = (size_t)(hostend - hostbegin);
  10419. } else {
  10420. port = strtoul(portbegin + 1, &portend, 10);
  10421. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10422. return 0;
  10423. }
  10424. request_domain_len = (size_t)(portbegin - hostbegin);
  10425. }
  10426. /* protocol found, port set */
  10427. break;
  10428. }
  10429. }
  10430. if (!port) {
  10431. /* port remains 0 if the protocol is not found */
  10432. return 0;
  10433. }
  10434. #if defined(USE_IPV6)
  10435. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10436. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10437. /* Request is directed to a different port */
  10438. return 0;
  10439. }
  10440. } else
  10441. #endif
  10442. {
  10443. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10444. /* Request is directed to a different port */
  10445. return 0;
  10446. }
  10447. }
  10448. if ((request_domain_len != server_domain_len)
  10449. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10450. /* Request is directed to another server */
  10451. return 0;
  10452. }
  10453. return hostend;
  10454. }
  10455. static int
  10456. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10457. {
  10458. const char *cl;
  10459. if (ebuf_len > 0) {
  10460. ebuf[0] = '\0';
  10461. }
  10462. *err = 0;
  10463. reset_per_request_attributes(conn);
  10464. if (!conn) {
  10465. mg_snprintf(conn,
  10466. NULL, /* No truncation check for ebuf */
  10467. ebuf,
  10468. ebuf_len,
  10469. "%s",
  10470. "Internal error");
  10471. *err = 500;
  10472. return 0;
  10473. }
  10474. /* Set the time the request was received. This value should be used for
  10475. * timeouts. */
  10476. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10477. conn->request_len =
  10478. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10479. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10480. */
  10481. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10482. mg_snprintf(conn,
  10483. NULL, /* No truncation check for ebuf */
  10484. ebuf,
  10485. ebuf_len,
  10486. "%s",
  10487. "Invalid request size");
  10488. *err = 500;
  10489. return 0;
  10490. }
  10491. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10492. mg_snprintf(conn,
  10493. NULL, /* No truncation check for ebuf */
  10494. ebuf,
  10495. ebuf_len,
  10496. "%s",
  10497. "Request Too Large");
  10498. *err = 413;
  10499. return 0;
  10500. } else if (conn->request_len <= 0) {
  10501. if (conn->data_len > 0) {
  10502. mg_snprintf(conn,
  10503. NULL, /* No truncation check for ebuf */
  10504. ebuf,
  10505. ebuf_len,
  10506. "%s",
  10507. "Client sent malformed request");
  10508. *err = 400;
  10509. } else {
  10510. /* Server did not send anything -> just close the connection */
  10511. conn->must_close = 1;
  10512. mg_snprintf(conn,
  10513. NULL, /* No truncation check for ebuf */
  10514. ebuf,
  10515. ebuf_len,
  10516. "%s",
  10517. "Client did not send a request");
  10518. *err = 0;
  10519. }
  10520. return 0;
  10521. } else if (parse_http_message(conn->buf,
  10522. conn->buf_size,
  10523. &conn->request_info) <= 0) {
  10524. mg_snprintf(conn,
  10525. NULL, /* No truncation check for ebuf */
  10526. ebuf,
  10527. ebuf_len,
  10528. "%s",
  10529. "Bad Request");
  10530. *err = 400;
  10531. return 0;
  10532. } else {
  10533. /* Message is a valid request or response */
  10534. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10535. /* Request/response has content length set */
  10536. char *endptr = NULL;
  10537. conn->content_len = strtoll(cl, &endptr, 10);
  10538. if (endptr == cl) {
  10539. mg_snprintf(conn,
  10540. NULL, /* No truncation check for ebuf */
  10541. ebuf,
  10542. ebuf_len,
  10543. "%s",
  10544. "Bad Request");
  10545. *err = 411;
  10546. return 0;
  10547. }
  10548. /* Publish the content length back to the request info. */
  10549. conn->request_info.content_length = conn->content_len;
  10550. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10551. != NULL
  10552. && !mg_strcasecmp(cl, "chunked")) {
  10553. conn->is_chunked = 1;
  10554. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10555. || !mg_strcasecmp(conn->request_info.request_method,
  10556. "PUT")) {
  10557. /* POST or PUT request without content length set */
  10558. conn->content_len = -1;
  10559. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10560. "HTTP/",
  10561. 5)) {
  10562. /* Response without content length set */
  10563. conn->content_len = -1;
  10564. } else {
  10565. /* Other request */
  10566. conn->content_len = 0;
  10567. }
  10568. }
  10569. return 1;
  10570. }
  10571. int
  10572. mg_get_response(struct mg_connection *conn,
  10573. char *ebuf,
  10574. size_t ebuf_len,
  10575. int timeout)
  10576. {
  10577. if (conn) {
  10578. /* Implementation of API function for HTTP clients */
  10579. int err, ret;
  10580. struct mg_context *octx = conn->ctx;
  10581. struct mg_context rctx = *(conn->ctx);
  10582. char txt[32]; /* will not overflow */
  10583. if (timeout >= 0) {
  10584. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10585. rctx.config[REQUEST_TIMEOUT] = txt;
  10586. set_sock_timeout(conn->client.sock, timeout);
  10587. } else {
  10588. rctx.config[REQUEST_TIMEOUT] = NULL;
  10589. }
  10590. conn->ctx = &rctx;
  10591. ret = getreq(conn, ebuf, ebuf_len, &err);
  10592. conn->ctx = octx;
  10593. /* TODO: 1) uri is deprecated;
  10594. * 2) here, ri.uri is the http response code */
  10595. conn->request_info.uri = conn->request_info.request_uri;
  10596. /* TODO (mid): Define proper return values - maybe return length?
  10597. * For the first test use <0 for error and >0 for OK */
  10598. return (ret == 0) ? -1 : +1;
  10599. }
  10600. return -1;
  10601. }
  10602. struct mg_connection *
  10603. mg_download(const char *host,
  10604. int port,
  10605. int use_ssl,
  10606. char *ebuf,
  10607. size_t ebuf_len,
  10608. const char *fmt,
  10609. ...)
  10610. {
  10611. struct mg_connection *conn;
  10612. va_list ap;
  10613. int i;
  10614. int reqerr;
  10615. va_start(ap, fmt);
  10616. ebuf[0] = '\0';
  10617. /* open a connection */
  10618. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10619. if (conn != NULL) {
  10620. i = mg_vprintf(conn, fmt, ap);
  10621. if (i <= 0) {
  10622. mg_snprintf(conn,
  10623. NULL, /* No truncation check for ebuf */
  10624. ebuf,
  10625. ebuf_len,
  10626. "%s",
  10627. "Error sending request");
  10628. } else {
  10629. getreq(conn, ebuf, ebuf_len, &reqerr);
  10630. /* TODO: 1) uri is deprecated;
  10631. * 2) here, ri.uri is the http response code */
  10632. conn->request_info.uri = conn->request_info.request_uri;
  10633. }
  10634. }
  10635. /* if an error occured, close the connection */
  10636. if (ebuf[0] != '\0' && conn != NULL) {
  10637. mg_close_connection(conn);
  10638. conn = NULL;
  10639. }
  10640. va_end(ap);
  10641. return conn;
  10642. }
  10643. struct websocket_client_thread_data {
  10644. struct mg_connection *conn;
  10645. mg_websocket_data_handler data_handler;
  10646. mg_websocket_close_handler close_handler;
  10647. void *callback_data;
  10648. };
  10649. #if defined(USE_WEBSOCKET)
  10650. #ifdef _WIN32
  10651. static unsigned __stdcall websocket_client_thread(void *data)
  10652. #else
  10653. static void *
  10654. websocket_client_thread(void *data)
  10655. #endif
  10656. {
  10657. struct websocket_client_thread_data *cdata =
  10658. (struct websocket_client_thread_data *)data;
  10659. mg_set_thread_name("ws-client");
  10660. if (cdata->conn->ctx) {
  10661. if (cdata->conn->ctx->callbacks.init_thread) {
  10662. /* 3 indicates a websocket client thread */
  10663. /* TODO: check if conn->ctx can be set */
  10664. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10665. }
  10666. }
  10667. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10668. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10669. if (cdata->close_handler != NULL) {
  10670. cdata->close_handler(cdata->conn, cdata->callback_data);
  10671. }
  10672. mg_free((void *)cdata);
  10673. #ifdef _WIN32
  10674. return 0;
  10675. #else
  10676. return NULL;
  10677. #endif
  10678. }
  10679. #endif
  10680. struct mg_connection *
  10681. mg_connect_websocket_client(const char *host,
  10682. int port,
  10683. int use_ssl,
  10684. char *error_buffer,
  10685. size_t error_buffer_size,
  10686. const char *path,
  10687. const char *origin,
  10688. mg_websocket_data_handler data_func,
  10689. mg_websocket_close_handler close_func,
  10690. void *user_data)
  10691. {
  10692. struct mg_connection *conn = NULL;
  10693. #if defined(USE_WEBSOCKET)
  10694. struct mg_context *newctx = NULL;
  10695. struct websocket_client_thread_data *thread_data;
  10696. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10697. static const char *handshake_req;
  10698. if (origin != NULL) {
  10699. handshake_req = "GET %s HTTP/1.1\r\n"
  10700. "Host: %s\r\n"
  10701. "Upgrade: websocket\r\n"
  10702. "Connection: Upgrade\r\n"
  10703. "Sec-WebSocket-Key: %s\r\n"
  10704. "Sec-WebSocket-Version: 13\r\n"
  10705. "Origin: %s\r\n"
  10706. "\r\n";
  10707. } else {
  10708. handshake_req = "GET %s HTTP/1.1\r\n"
  10709. "Host: %s\r\n"
  10710. "Upgrade: websocket\r\n"
  10711. "Connection: Upgrade\r\n"
  10712. "Sec-WebSocket-Key: %s\r\n"
  10713. "Sec-WebSocket-Version: 13\r\n"
  10714. "\r\n";
  10715. }
  10716. /* Establish the client connection and request upgrade */
  10717. conn = mg_download(host,
  10718. port,
  10719. use_ssl,
  10720. error_buffer,
  10721. error_buffer_size,
  10722. handshake_req,
  10723. path,
  10724. host,
  10725. magic,
  10726. origin);
  10727. /* Connection object will be null if something goes wrong */
  10728. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10729. if (!*error_buffer) {
  10730. /* if there is a connection, but it did not return 101,
  10731. * error_buffer is not yet set */
  10732. mg_snprintf(conn,
  10733. NULL, /* No truncation check for ebuf */
  10734. error_buffer,
  10735. error_buffer_size,
  10736. "Unexpected server reply");
  10737. }
  10738. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10739. if (conn != NULL) {
  10740. mg_free(conn);
  10741. conn = NULL;
  10742. }
  10743. return conn;
  10744. }
  10745. /* For client connections, mg_context is fake. Since we need to set a
  10746. * callback function, we need to create a copy and modify it. */
  10747. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10748. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10749. newctx->user_data = user_data;
  10750. newctx->context_type = 2; /* client context type */
  10751. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10752. newctx->workerthreadids =
  10753. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10754. conn->ctx = newctx;
  10755. thread_data = (struct websocket_client_thread_data *)
  10756. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10757. thread_data->conn = conn;
  10758. thread_data->data_handler = data_func;
  10759. thread_data->close_handler = close_func;
  10760. thread_data->callback_data = NULL;
  10761. /* Start a thread to read the websocket client connection
  10762. * This thread will automatically stop when mg_disconnect is
  10763. * called on the client connection */
  10764. if (mg_start_thread_with_id(websocket_client_thread,
  10765. (void *)thread_data,
  10766. newctx->workerthreadids) != 0) {
  10767. mg_free((void *)thread_data);
  10768. mg_free((void *)newctx->workerthreadids);
  10769. mg_free((void *)newctx);
  10770. mg_free((void *)conn);
  10771. conn = NULL;
  10772. DEBUG_TRACE("%s",
  10773. "Websocket client connect thread could not be started\r\n");
  10774. }
  10775. #else
  10776. /* Appease "unused parameter" warnings */
  10777. (void)host;
  10778. (void)port;
  10779. (void)use_ssl;
  10780. (void)error_buffer;
  10781. (void)error_buffer_size;
  10782. (void)path;
  10783. (void)origin;
  10784. (void)user_data;
  10785. (void)data_func;
  10786. (void)close_func;
  10787. #endif
  10788. return conn;
  10789. }
  10790. static void
  10791. process_new_connection(struct mg_connection *conn)
  10792. {
  10793. if (conn && conn->ctx) {
  10794. struct mg_request_info *ri = &conn->request_info;
  10795. int keep_alive_enabled, keep_alive, discard_len;
  10796. char ebuf[100];
  10797. const char *hostend;
  10798. int reqerr, uri_type;
  10799. keep_alive_enabled =
  10800. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10801. /* Important: on new connection, reset the receiving buffer. Credit
  10802. * goes to crule42. */
  10803. conn->data_len = 0;
  10804. do {
  10805. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10806. /* The request sent by the client could not be understood by
  10807. * the server, or it was incomplete or a timeout. Send an
  10808. * error message and close the connection. */
  10809. if (reqerr > 0) {
  10810. /*assert(ebuf[0] != '\0');*/
  10811. send_http_error(conn, reqerr, "%s", ebuf);
  10812. }
  10813. } else if (strcmp(ri->http_version, "1.0")
  10814. && strcmp(ri->http_version, "1.1")) {
  10815. mg_snprintf(conn,
  10816. NULL, /* No truncation check for ebuf */
  10817. ebuf,
  10818. sizeof(ebuf),
  10819. "Bad HTTP version: [%s]",
  10820. ri->http_version);
  10821. send_http_error(conn, 505, "%s", ebuf);
  10822. }
  10823. if (ebuf[0] == '\0') {
  10824. uri_type = get_uri_type(conn->request_info.request_uri);
  10825. switch (uri_type) {
  10826. case 1:
  10827. /* Asterisk */
  10828. conn->request_info.local_uri = NULL;
  10829. break;
  10830. case 2:
  10831. /* relative uri */
  10832. conn->request_info.local_uri =
  10833. conn->request_info.request_uri;
  10834. break;
  10835. case 3:
  10836. case 4:
  10837. /* absolute uri (with/without port) */
  10838. hostend = get_rel_url_at_current_server(
  10839. conn->request_info.request_uri, conn);
  10840. if (hostend) {
  10841. conn->request_info.local_uri = hostend;
  10842. } else {
  10843. conn->request_info.local_uri = NULL;
  10844. }
  10845. break;
  10846. default:
  10847. mg_snprintf(conn,
  10848. NULL, /* No truncation check for ebuf */
  10849. ebuf,
  10850. sizeof(ebuf),
  10851. "Invalid URI: [%s]",
  10852. ri->request_uri);
  10853. send_http_error(conn, 400, "%s", ebuf);
  10854. break;
  10855. }
  10856. /* TODO: cleanup uri, local_uri and request_uri */
  10857. conn->request_info.uri = conn->request_info.local_uri;
  10858. }
  10859. if (ebuf[0] == '\0') {
  10860. if (conn->request_info.local_uri) {
  10861. /* handle request to local server */
  10862. handle_request(conn);
  10863. if (conn->ctx->callbacks.end_request != NULL) {
  10864. conn->ctx->callbacks.end_request(conn,
  10865. conn->status_code);
  10866. }
  10867. log_access(conn);
  10868. } else {
  10869. /* TODO: handle non-local request (PROXY) */
  10870. conn->must_close = 1;
  10871. }
  10872. } else {
  10873. conn->must_close = 1;
  10874. }
  10875. if (ri->remote_user != NULL) {
  10876. mg_free((void *)ri->remote_user);
  10877. /* Important! When having connections with and without auth
  10878. * would cause double free and then crash */
  10879. ri->remote_user = NULL;
  10880. }
  10881. /* NOTE(lsm): order is important here. should_keep_alive() call
  10882. * is
  10883. * using parsed request, which will be invalid after memmove's
  10884. * below.
  10885. * Therefore, memorize should_keep_alive() result now for later
  10886. * use
  10887. * in loop exit condition. */
  10888. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10889. && conn->content_len >= 0 && should_keep_alive(conn);
  10890. /* Discard all buffered data for this request */
  10891. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  10892. && ((conn->request_len + conn->content_len)
  10893. < (int64_t)conn->data_len))
  10894. ? (int)(conn->request_len + conn->content_len)
  10895. : conn->data_len;
  10896. /*assert(discard_len >= 0);*/
  10897. if (discard_len < 0)
  10898. break;
  10899. conn->data_len -= discard_len;
  10900. if (conn->data_len > 0) {
  10901. memmove(conn->buf,
  10902. conn->buf + discard_len,
  10903. (size_t)conn->data_len);
  10904. }
  10905. /* assert(conn->data_len >= 0); */
  10906. /* assert(conn->data_len <= conn->buf_size); */
  10907. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10908. break;
  10909. }
  10910. } while (keep_alive);
  10911. }
  10912. }
  10913. #if defined(ALTERNATIVE_QUEUE)
  10914. static void
  10915. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10916. {
  10917. unsigned int i;
  10918. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10919. /* TODO: find a free worker slot and signal it */
  10920. }
  10921. }
  10922. static int
  10923. consume_socket(struct mg_context *ctx, struct socket *sp)
  10924. {
  10925. /* TODO: every thread must wait for exactly one slot in the list */
  10926. }
  10927. #else /* ALTERNATIVE_QUEUE */
  10928. /* Worker threads take accepted socket from the queue */
  10929. static int
  10930. consume_socket(struct mg_context *ctx, struct socket *sp)
  10931. {
  10932. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10933. if (!ctx) {
  10934. return 0;
  10935. }
  10936. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10937. DEBUG_TRACE("%s", "going idle");
  10938. /* If the queue is empty, wait. We're idle at this point. */
  10939. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10940. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10941. }
  10942. /* If we're stopping, sq_head may be equal to sq_tail. */
  10943. if (ctx->sq_head > ctx->sq_tail) {
  10944. /* Copy socket from the queue and increment tail */
  10945. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10946. ctx->sq_tail++;
  10947. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10948. /* Wrap pointers if needed */
  10949. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10950. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10951. ctx->sq_head -= QUEUE_SIZE(ctx);
  10952. }
  10953. }
  10954. (void)pthread_cond_signal(&ctx->sq_empty);
  10955. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10956. return !ctx->stop_flag;
  10957. #undef QUEUE_SIZE
  10958. }
  10959. /* Master thread adds accepted socket to a queue */
  10960. static void
  10961. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10962. {
  10963. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10964. if (!ctx) {
  10965. return;
  10966. }
  10967. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10968. /* If the queue is full, wait */
  10969. while (ctx->stop_flag == 0
  10970. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10971. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10972. }
  10973. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10974. /* Copy socket to the queue and increment head */
  10975. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10976. ctx->sq_head++;
  10977. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10978. }
  10979. (void)pthread_cond_signal(&ctx->sq_full);
  10980. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10981. #undef QUEUE_SIZE
  10982. }
  10983. #endif /* ALTERNATIVE_QUEUE */
  10984. static void *
  10985. worker_thread_run(void *thread_func_param)
  10986. {
  10987. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10988. struct mg_connection *conn;
  10989. struct mg_workerTLS tls;
  10990. #if defined(MG_LEGACY_INTERFACE)
  10991. uint32_t addr;
  10992. #endif
  10993. mg_set_thread_name("worker");
  10994. tls.is_master = 0;
  10995. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10996. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10997. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10998. #endif
  10999. if (ctx->callbacks.init_thread) {
  11000. /* call init_thread for a worker thread (type 1) */
  11001. ctx->callbacks.init_thread(ctx, 1);
  11002. }
  11003. conn =
  11004. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11005. if (conn == NULL) {
  11006. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11007. } else {
  11008. pthread_setspecific(sTlsKey, &tls);
  11009. conn->buf_size = MAX_REQUEST_SIZE;
  11010. conn->buf = (char *)(conn + 1);
  11011. conn->ctx = ctx;
  11012. conn->request_info.user_data = ctx->user_data;
  11013. /* Allocate a mutex for this connection to allow communication both
  11014. * within the request handler and from elsewhere in the application
  11015. */
  11016. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11017. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11018. * signal sq_empty condvar to wake up the master waiting in
  11019. * produce_socket() */
  11020. while (consume_socket(ctx, &conn->client)) {
  11021. conn->conn_birth_time = time(NULL);
  11022. /* Fill in IP, port info early so even if SSL setup below fails,
  11023. * error handler would have the corresponding info.
  11024. * Thanks to Johannes Winkelmann for the patch.
  11025. */
  11026. #if defined(USE_IPV6)
  11027. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11028. conn->request_info.remote_port =
  11029. ntohs(conn->client.rsa.sin6.sin6_port);
  11030. } else
  11031. #endif
  11032. {
  11033. conn->request_info.remote_port =
  11034. ntohs(conn->client.rsa.sin.sin_port);
  11035. }
  11036. sockaddr_to_string(conn->request_info.remote_addr,
  11037. sizeof(conn->request_info.remote_addr),
  11038. &conn->client.rsa);
  11039. #if defined(MG_LEGACY_INTERFACE)
  11040. /* This legacy interface only works for the IPv4 case */
  11041. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11042. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11043. #endif
  11044. conn->request_info.is_ssl = conn->client.is_ssl;
  11045. if (!conn->client.is_ssl
  11046. #ifndef NO_SSL
  11047. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  11048. #endif
  11049. ) {
  11050. process_new_connection(conn);
  11051. }
  11052. close_connection(conn);
  11053. }
  11054. }
  11055. pthread_setspecific(sTlsKey, NULL);
  11056. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11057. CloseHandle(tls.pthread_cond_helper_mutex);
  11058. #endif
  11059. pthread_mutex_destroy(&conn->mutex);
  11060. mg_free(conn);
  11061. DEBUG_TRACE("%s", "exiting");
  11062. return NULL;
  11063. }
  11064. /* Threads have different return types on Windows and Unix. */
  11065. #ifdef _WIN32
  11066. static unsigned __stdcall worker_thread(void *thread_func_param)
  11067. {
  11068. worker_thread_run(thread_func_param);
  11069. return 0;
  11070. }
  11071. #else
  11072. static void *
  11073. worker_thread(void *thread_func_param)
  11074. {
  11075. worker_thread_run(thread_func_param);
  11076. return NULL;
  11077. }
  11078. #endif /* _WIN32 */
  11079. static void
  11080. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11081. {
  11082. struct socket so;
  11083. char src_addr[IP_ADDR_STR_LEN];
  11084. socklen_t len = sizeof(so.rsa);
  11085. int on = 1;
  11086. int timeout;
  11087. if (!listener) {
  11088. return;
  11089. }
  11090. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11091. == INVALID_SOCKET) {
  11092. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11093. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11094. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11095. closesocket(so.sock);
  11096. so.sock = INVALID_SOCKET;
  11097. } else {
  11098. /* Put so socket structure into the queue */
  11099. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11100. set_close_on_exec(so.sock, fc(ctx));
  11101. so.is_ssl = listener->is_ssl;
  11102. so.ssl_redir = listener->ssl_redir;
  11103. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11104. mg_cry(fc(ctx),
  11105. "%s: getsockname() failed: %s",
  11106. __func__,
  11107. strerror(ERRNO));
  11108. }
  11109. /* Set TCP keep-alive. This is needed because if HTTP-level
  11110. * keep-alive
  11111. * is enabled, and client resets the connection, server won't get
  11112. * TCP FIN or RST and will keep the connection open forever. With
  11113. * TCP keep-alive, next keep-alive handshake will figure out that
  11114. * the client is down and will close the server end.
  11115. * Thanks to Igor Klopov who suggested the patch. */
  11116. if (setsockopt(so.sock,
  11117. SOL_SOCKET,
  11118. SO_KEEPALIVE,
  11119. (SOCK_OPT_TYPE)&on,
  11120. sizeof(on)) != 0) {
  11121. mg_cry(fc(ctx),
  11122. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11123. __func__,
  11124. strerror(ERRNO));
  11125. }
  11126. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11127. * to effectively fill up the underlying IP packet payload and
  11128. * reduce the overhead of sending lots of small buffers. However
  11129. * this hurts the server's throughput (ie. operations per second)
  11130. * when HTTP 1.1 persistent connections are used and the responses
  11131. * are relatively small (eg. less than 1400 bytes).
  11132. */
  11133. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11134. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11135. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11136. mg_cry(fc(ctx),
  11137. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11138. __func__,
  11139. strerror(ERRNO));
  11140. }
  11141. }
  11142. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11143. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11144. } else {
  11145. timeout = -1;
  11146. }
  11147. /* Set socket timeout to the given value, but not more than a
  11148. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  11149. * so the server can exit after that time if requested. */
  11150. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  11151. set_sock_timeout(so.sock, timeout);
  11152. } else {
  11153. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  11154. }
  11155. produce_socket(ctx, &so);
  11156. }
  11157. }
  11158. static void
  11159. master_thread_run(void *thread_func_param)
  11160. {
  11161. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11162. struct mg_workerTLS tls;
  11163. struct pollfd *pfd;
  11164. unsigned int i;
  11165. unsigned int workerthreadcount;
  11166. if (!ctx) {
  11167. return;
  11168. }
  11169. mg_set_thread_name("master");
  11170. /* Increase priority of the master thread */
  11171. #if defined(_WIN32)
  11172. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11173. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11174. int min_prio = sched_get_priority_min(SCHED_RR);
  11175. int max_prio = sched_get_priority_max(SCHED_RR);
  11176. if ((min_prio >= 0) && (max_prio >= 0)
  11177. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11178. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11179. struct sched_param sched_param = {0};
  11180. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11181. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11182. }
  11183. #endif
  11184. /* Initialize thread local storage */
  11185. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11186. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11187. #endif
  11188. tls.is_master = 1;
  11189. pthread_setspecific(sTlsKey, &tls);
  11190. if (ctx->callbacks.init_thread) {
  11191. /* Callback for the master thread (type 0) */
  11192. ctx->callbacks.init_thread(ctx, 0);
  11193. }
  11194. /* Server starts *now* */
  11195. ctx->start_time = time(NULL);
  11196. /* Start the server */
  11197. pfd = ctx->listening_socket_fds;
  11198. while (ctx->stop_flag == 0) {
  11199. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11200. pfd[i].fd = ctx->listening_sockets[i].sock;
  11201. pfd[i].events = POLLIN;
  11202. }
  11203. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11204. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11205. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11206. * successful poll, and POLLIN is defined as
  11207. * (POLLRDNORM | POLLRDBAND)
  11208. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11209. * pfd[i].revents == POLLIN. */
  11210. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11211. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11212. }
  11213. }
  11214. }
  11215. }
  11216. DEBUG_TRACE("%s", "stopping workers");
  11217. /* Stop signal received: somebody called mg_stop. Quit. */
  11218. close_all_listening_sockets(ctx);
  11219. /* Wakeup workers that are waiting for connections to handle. */
  11220. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11221. #if defined(ALTERNATIVE_QUEUE)
  11222. /* TODO: signal all workers */
  11223. /* TODO: close all socket handles (will avoid SOCKET_TIMEOUT_QUANTUM) */
  11224. #else
  11225. pthread_cond_broadcast(&ctx->sq_full);
  11226. #endif
  11227. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11228. /* Join all worker threads to avoid leaking threads. */
  11229. workerthreadcount = ctx->cfg_worker_threads;
  11230. for (i = 0; i < workerthreadcount; i++) {
  11231. if (ctx->workerthreadids[i] != 0) {
  11232. mg_join_thread(ctx->workerthreadids[i]);
  11233. }
  11234. }
  11235. #if !defined(NO_SSL)
  11236. if (ctx->ssl_ctx != NULL) {
  11237. uninitialize_ssl(ctx);
  11238. }
  11239. #endif
  11240. DEBUG_TRACE("%s", "exiting");
  11241. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11242. CloseHandle(tls.pthread_cond_helper_mutex);
  11243. #endif
  11244. pthread_setspecific(sTlsKey, NULL);
  11245. /* Signal mg_stop() that we're done.
  11246. * WARNING: This must be the very last thing this
  11247. * thread does, as ctx becomes invalid after this line. */
  11248. ctx->stop_flag = 2;
  11249. }
  11250. /* Threads have different return types on Windows and Unix. */
  11251. #ifdef _WIN32
  11252. static unsigned __stdcall master_thread(void *thread_func_param)
  11253. {
  11254. master_thread_run(thread_func_param);
  11255. return 0;
  11256. }
  11257. #else
  11258. static void *
  11259. master_thread(void *thread_func_param)
  11260. {
  11261. master_thread_run(thread_func_param);
  11262. return NULL;
  11263. }
  11264. #endif /* _WIN32 */
  11265. static void
  11266. free_context(struct mg_context *ctx)
  11267. {
  11268. int i;
  11269. struct mg_handler_info *tmp_rh;
  11270. if (ctx == NULL) {
  11271. return;
  11272. }
  11273. if (ctx->callbacks.exit_context) {
  11274. ctx->callbacks.exit_context(ctx);
  11275. }
  11276. /* All threads exited, no sync is needed. Destroy thread mutex and
  11277. * condvars
  11278. */
  11279. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11280. #if defined(ALTERNATIVE_QUEUE)
  11281. /* TODO: free allocated memory */
  11282. #else
  11283. (void)pthread_cond_destroy(&ctx->sq_empty);
  11284. (void)pthread_cond_destroy(&ctx->sq_full);
  11285. #endif
  11286. /* Destroy other context global data structures mutex */
  11287. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11288. #if defined(USE_TIMERS)
  11289. timers_exit(ctx);
  11290. #endif
  11291. /* Deallocate config parameters */
  11292. for (i = 0; i < NUM_OPTIONS; i++) {
  11293. if (ctx->config[i] != NULL) {
  11294. #if defined(_MSC_VER)
  11295. #pragma warning(suppress : 6001)
  11296. #endif
  11297. mg_free(ctx->config[i]);
  11298. }
  11299. }
  11300. /* Deallocate request handlers */
  11301. while (ctx->handlers) {
  11302. tmp_rh = ctx->handlers;
  11303. ctx->handlers = tmp_rh->next;
  11304. mg_free(tmp_rh->uri);
  11305. mg_free(tmp_rh);
  11306. }
  11307. #ifndef NO_SSL
  11308. /* Deallocate SSL context */
  11309. if (ctx->ssl_ctx != NULL) {
  11310. SSL_CTX_free(ctx->ssl_ctx);
  11311. }
  11312. #endif /* !NO_SSL */
  11313. /* Deallocate worker thread ID array */
  11314. if (ctx->workerthreadids != NULL) {
  11315. mg_free(ctx->workerthreadids);
  11316. }
  11317. /* Deallocate the tls variable */
  11318. if (mg_atomic_dec(&sTlsInit) == 0) {
  11319. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11320. DeleteCriticalSection(&global_log_file_lock);
  11321. #endif /* _WIN32 && !__SYMBIAN32__ */
  11322. #if !defined(_WIN32)
  11323. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11324. #endif
  11325. pthread_key_delete(sTlsKey);
  11326. }
  11327. /* deallocate system name string */
  11328. mg_free(ctx->systemName);
  11329. /* Deallocate context itself */
  11330. mg_free(ctx);
  11331. }
  11332. void
  11333. mg_stop(struct mg_context *ctx)
  11334. {
  11335. pthread_t mt;
  11336. if (!ctx) {
  11337. return;
  11338. }
  11339. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11340. * two threads is not allowed. */
  11341. mt = ctx->masterthreadid;
  11342. if (mt == 0) {
  11343. return;
  11344. }
  11345. ctx->masterthreadid = 0;
  11346. /* Set stop flag, so all threads know they have to exit. */
  11347. ctx->stop_flag = 1;
  11348. /* Wait until everything has stopped. */
  11349. while (ctx->stop_flag != 2) {
  11350. (void)mg_sleep(10);
  11351. }
  11352. mg_join_thread(mt);
  11353. free_context(ctx);
  11354. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11355. (void)WSACleanup();
  11356. #endif /* _WIN32 && !__SYMBIAN32__ */
  11357. }
  11358. static void
  11359. get_system_name(char **sysName)
  11360. {
  11361. #if defined(_WIN32)
  11362. #if !defined(__SYMBIAN32__)
  11363. #if defined(_WIN32_WCE)
  11364. *sysName = mg_strdup("WinCE");
  11365. #else
  11366. char name[128];
  11367. DWORD dwVersion = 0;
  11368. DWORD dwMajorVersion = 0;
  11369. DWORD dwMinorVersion = 0;
  11370. DWORD dwBuild = 0;
  11371. #ifdef _MSC_VER
  11372. #pragma warning(push)
  11373. // GetVersion was declared deprecated
  11374. #pragma warning(disable : 4996)
  11375. #endif
  11376. dwVersion = GetVersion();
  11377. #ifdef _MSC_VER
  11378. #pragma warning(pop)
  11379. #endif
  11380. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11381. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11382. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11383. (void)dwBuild;
  11384. sprintf(name,
  11385. "Windows %u.%u",
  11386. (unsigned)dwMajorVersion,
  11387. (unsigned)dwMinorVersion);
  11388. *sysName = mg_strdup(name);
  11389. #endif
  11390. #else
  11391. *sysName = mg_strdup("Symbian");
  11392. #endif
  11393. #else
  11394. struct utsname name;
  11395. memset(&name, 0, sizeof(name));
  11396. uname(&name);
  11397. *sysName = mg_strdup(name.sysname);
  11398. #endif
  11399. }
  11400. struct mg_context *
  11401. mg_start(const struct mg_callbacks *callbacks,
  11402. void *user_data,
  11403. const char **options)
  11404. {
  11405. struct mg_context *ctx;
  11406. const char *name, *value, *default_value;
  11407. int idx, ok, workerthreadcount;
  11408. unsigned int i;
  11409. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11410. struct mg_workerTLS tls;
  11411. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11412. WSADATA data;
  11413. WSAStartup(MAKEWORD(2, 2), &data);
  11414. #endif /* _WIN32 && !__SYMBIAN32__ */
  11415. /* Allocate context and initialize reasonable general case defaults. */
  11416. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11417. return NULL;
  11418. }
  11419. /* Random number generator will initialize at the first call */
  11420. ctx->auth_nonce_mask =
  11421. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11422. if (mg_atomic_inc(&sTlsInit) == 1) {
  11423. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11424. InitializeCriticalSection(&global_log_file_lock);
  11425. #endif /* _WIN32 && !__SYMBIAN32__ */
  11426. #if !defined(_WIN32)
  11427. pthread_mutexattr_init(&pthread_mutex_attr);
  11428. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11429. #endif
  11430. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11431. /* Fatal error - abort start. However, this situation should
  11432. * never
  11433. * occur in practice. */
  11434. mg_atomic_dec(&sTlsInit);
  11435. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11436. mg_free(ctx);
  11437. return NULL;
  11438. }
  11439. } else {
  11440. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11441. * initialized. */
  11442. mg_sleep(1);
  11443. }
  11444. tls.is_master = -1;
  11445. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11446. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11447. tls.pthread_cond_helper_mutex = NULL;
  11448. #endif
  11449. pthread_setspecific(sTlsKey, &tls);
  11450. #if defined(USE_LUA)
  11451. lua_init_optional_libraries();
  11452. #endif
  11453. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11454. #if defined(ALTERNATIVE_QUEUE)
  11455. /* TODO: allocate memory */
  11456. #else
  11457. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11458. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11459. #endif
  11460. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11461. if (!ok) {
  11462. /* Fatal error - abort start. However, this situation should never
  11463. * occur in practice. */
  11464. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11465. mg_free(ctx);
  11466. pthread_setspecific(sTlsKey, NULL);
  11467. return NULL;
  11468. }
  11469. if (callbacks) {
  11470. ctx->callbacks = *callbacks;
  11471. exit_callback = callbacks->exit_context;
  11472. ctx->callbacks.exit_context = 0;
  11473. }
  11474. ctx->user_data = user_data;
  11475. ctx->handlers = NULL;
  11476. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11477. ctx->shared_lua_websockets = 0;
  11478. #endif
  11479. while (options && (name = *options++) != NULL) {
  11480. if ((idx = get_option_index(name)) == -1) {
  11481. mg_cry(fc(ctx), "Invalid option: %s", name);
  11482. free_context(ctx);
  11483. pthread_setspecific(sTlsKey, NULL);
  11484. return NULL;
  11485. } else if ((value = *options++) == NULL) {
  11486. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11487. free_context(ctx);
  11488. pthread_setspecific(sTlsKey, NULL);
  11489. return NULL;
  11490. }
  11491. if (ctx->config[idx] != NULL) {
  11492. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11493. mg_free(ctx->config[idx]);
  11494. }
  11495. ctx->config[idx] = mg_strdup(value);
  11496. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11497. }
  11498. /* Set default value if needed */
  11499. for (i = 0; config_options[i].name != NULL; i++) {
  11500. default_value = config_options[i].default_value;
  11501. if (ctx->config[i] == NULL && default_value != NULL) {
  11502. ctx->config[i] = mg_strdup(default_value);
  11503. }
  11504. }
  11505. #if defined(NO_FILES)
  11506. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11507. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11508. free_context(ctx);
  11509. pthread_setspecific(sTlsKey, NULL);
  11510. return NULL;
  11511. }
  11512. #endif
  11513. get_system_name(&ctx->systemName);
  11514. /* NOTE(lsm): order is important here. SSL certificates must
  11515. * be initialized before listening ports. UID must be set last. */
  11516. if (!set_gpass_option(ctx) ||
  11517. #if !defined(NO_SSL)
  11518. !set_ssl_option(ctx) ||
  11519. #endif
  11520. !set_ports_option(ctx) ||
  11521. #if !defined(_WIN32)
  11522. !set_uid_option(ctx) ||
  11523. #endif
  11524. !set_acl_option(ctx)) {
  11525. free_context(ctx);
  11526. pthread_setspecific(sTlsKey, NULL);
  11527. return NULL;
  11528. }
  11529. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11530. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11531. * won't kill the whole process. */
  11532. (void)signal(SIGPIPE, SIG_IGN);
  11533. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11534. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11535. if (workerthreadcount > MAX_WORKER_THREADS) {
  11536. mg_cry(fc(ctx), "Too many worker threads");
  11537. free_context(ctx);
  11538. pthread_setspecific(sTlsKey, NULL);
  11539. return NULL;
  11540. }
  11541. if (workerthreadcount > 0) {
  11542. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11543. ctx->workerthreadids =
  11544. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11545. if (ctx->workerthreadids == NULL) {
  11546. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11547. free_context(ctx);
  11548. pthread_setspecific(sTlsKey, NULL);
  11549. return NULL;
  11550. }
  11551. }
  11552. #if defined(USE_TIMERS)
  11553. if (timers_init(ctx) != 0) {
  11554. mg_cry(fc(ctx), "Error creating timers");
  11555. free_context(ctx);
  11556. pthread_setspecific(sTlsKey, NULL);
  11557. return NULL;
  11558. }
  11559. #endif
  11560. /* Context has been created - init user libraries */
  11561. if (ctx->callbacks.init_context) {
  11562. ctx->callbacks.init_context(ctx);
  11563. }
  11564. ctx->callbacks.exit_context = exit_callback;
  11565. ctx->context_type = 1; /* server context */
  11566. /* Start master (listening) thread */
  11567. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11568. /* Start worker threads */
  11569. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11570. if (mg_start_thread_with_id(worker_thread,
  11571. ctx,
  11572. &ctx->workerthreadids[i]) != 0) {
  11573. if (i > 0) {
  11574. mg_cry(fc(ctx),
  11575. "Cannot start worker thread %i: error %ld",
  11576. i + 1,
  11577. (long)ERRNO);
  11578. } else {
  11579. mg_cry(fc(ctx),
  11580. "Cannot create threads: error %ld",
  11581. (long)ERRNO);
  11582. free_context(ctx);
  11583. pthread_setspecific(sTlsKey, NULL);
  11584. return NULL;
  11585. }
  11586. break;
  11587. }
  11588. }
  11589. pthread_setspecific(sTlsKey, NULL);
  11590. return ctx;
  11591. }
  11592. /* Feature check API function */
  11593. unsigned
  11594. mg_check_feature(unsigned feature)
  11595. {
  11596. static const unsigned feature_set = 0
  11597. /* Set bits for available features according to API documentation.
  11598. * This bit mask is created at compile time, according to the active
  11599. * preprocessor defines. It is a single const value at runtime. */
  11600. #if !defined(NO_FILES)
  11601. | 0x0001u
  11602. #endif
  11603. #if !defined(NO_SSL)
  11604. | 0x0002u
  11605. #endif
  11606. #if !defined(NO_CGI)
  11607. | 0x0004u
  11608. #endif
  11609. #if defined(USE_IPV6)
  11610. | 0x0008u
  11611. #endif
  11612. #if defined(USE_WEBSOCKET)
  11613. | 0x0010u
  11614. #endif
  11615. #if defined(USE_LUA)
  11616. | 0x0020u
  11617. #endif
  11618. #if defined(USE_DUKTAPE)
  11619. | 0x0040u
  11620. #endif
  11621. #if !defined(NO_CACHING)
  11622. | 0x0080u
  11623. #endif
  11624. /* Set some extra bits not defined in the API documentation.
  11625. * These bits may change without further notice. */
  11626. #if defined(MG_LEGACY_INTERFACE)
  11627. | 0x8000u
  11628. #endif
  11629. #if defined(MEMORY_DEBUGGING)
  11630. | 0x0100u
  11631. #endif
  11632. #if defined(USE_TIMERS)
  11633. | 0x0200u
  11634. #endif
  11635. #if !defined(NO_NONCE_CHECK)
  11636. | 0x0400u
  11637. #endif
  11638. #if !defined(NO_POPEN)
  11639. | 0x0800u
  11640. #endif
  11641. ;
  11642. return (feature & feature_set);
  11643. }