civetweb.c 350 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555
  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. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. #define NO_POPEN /* WinCE has no popen */
  201. typedef long off_t;
  202. #define errno ((int)(GetLastError()))
  203. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  204. #endif /* _WIN32_WCE */
  205. #define MAKEUQUAD(lo, hi) \
  206. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  207. #define RATE_DIFF (10000000) /* 100 nsecs */
  208. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  209. #define SYS2UNIX_TIME(lo, hi) \
  210. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  211. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  212. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  213. * Also use _strtoui64 on modern M$ compilers */
  214. #if defined(_MSC_VER)
  215. #if (_MSC_VER < 1300)
  216. #define STRX(x) #x
  217. #define STR(x) STRX(x)
  218. #define __func__ __FILE__ ":" STR(__LINE__)
  219. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  220. #define strtoll(x, y, z) (_atoi64(x))
  221. #else
  222. #define __func__ __FUNCTION__
  223. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  224. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  225. #endif
  226. #endif /* _MSC_VER */
  227. #define ERRNO ((int)(GetLastError()))
  228. #define NO_SOCKLEN_T
  229. #if defined(_WIN64) || defined(__MINGW64__)
  230. #define SSL_LIB "ssleay64.dll"
  231. #define CRYPTO_LIB "libeay64.dll"
  232. #else
  233. #define SSL_LIB "ssleay32.dll"
  234. #define CRYPTO_LIB "libeay32.dll"
  235. #endif
  236. #define O_NONBLOCK (0)
  237. #ifndef W_OK
  238. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  239. #endif
  240. #if !defined(EWOULDBLOCK)
  241. #define EWOULDBLOCK WSAEWOULDBLOCK
  242. #endif /* !EWOULDBLOCK */
  243. #define _POSIX_
  244. #define INT64_FMT "I64d"
  245. #define UINT64_FMT "I64u"
  246. #define WINCDECL __cdecl
  247. #define SHUT_RD (0)
  248. #define SHUT_WR (1)
  249. #define SHUT_BOTH (2)
  250. #define vsnprintf_impl _vsnprintf
  251. #define access _access
  252. #define mg_sleep(x) (Sleep(x))
  253. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  254. #ifndef popen
  255. #define popen(x, y) (_popen(x, y))
  256. #endif
  257. #ifndef pclose
  258. #define pclose(x) (_pclose(x))
  259. #endif
  260. #define close(x) (_close(x))
  261. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  262. #define RTLD_LAZY (0)
  263. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  264. #define fdopen(x, y) (_fdopen((x), (y)))
  265. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  266. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  267. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  268. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  269. #define sleep(x) (Sleep((x)*1000))
  270. #define rmdir(x) (_rmdir(x))
  271. #define timegm(x) (_mkgmtime(x))
  272. #if !defined(fileno)
  273. #define fileno(x) (_fileno(x))
  274. #endif /* !fileno MINGW #defines fileno */
  275. typedef HANDLE pthread_mutex_t;
  276. typedef DWORD pthread_key_t;
  277. typedef HANDLE pthread_t;
  278. typedef struct {
  279. CRITICAL_SECTION threadIdSec;
  280. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  281. } pthread_cond_t;
  282. #ifndef __clockid_t_defined
  283. typedef DWORD clockid_t;
  284. #endif
  285. #ifndef CLOCK_MONOTONIC
  286. #define CLOCK_MONOTONIC (1)
  287. #endif
  288. #ifndef CLOCK_REALTIME
  289. #define CLOCK_REALTIME (2)
  290. #endif
  291. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  292. #define _TIMESPEC_DEFINED
  293. #endif
  294. #ifndef _TIMESPEC_DEFINED
  295. struct timespec {
  296. time_t tv_sec; /* seconds */
  297. long tv_nsec; /* nanoseconds */
  298. };
  299. #endif
  300. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  301. static int pthread_mutex_lock(pthread_mutex_t *);
  302. static int pthread_mutex_unlock(pthread_mutex_t *);
  303. static void path_to_unicode(const struct mg_connection *conn,
  304. const char *path,
  305. wchar_t *wbuf,
  306. size_t wbuf_len);
  307. struct file;
  308. static const char *
  309. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  310. #if defined(HAVE_STDINT)
  311. #include <stdint.h>
  312. #else
  313. typedef unsigned char uint8_t;
  314. typedef unsigned short uint16_t;
  315. typedef unsigned int uint32_t;
  316. typedef unsigned __int64 uint64_t;
  317. typedef __int64 int64_t;
  318. #ifndef INT64_MAX
  319. #define INT64_MAX (9223372036854775807)
  320. #endif
  321. #endif /* HAVE_STDINT */
  322. /* POSIX dirent interface */
  323. struct dirent {
  324. char d_name[PATH_MAX];
  325. };
  326. typedef struct DIR {
  327. HANDLE handle;
  328. WIN32_FIND_DATAW info;
  329. struct dirent result;
  330. } DIR;
  331. #if defined(_WIN32) && !defined(POLLIN)
  332. #ifndef HAVE_POLL
  333. struct pollfd {
  334. SOCKET fd;
  335. short events;
  336. short revents;
  337. };
  338. #define POLLIN (0x0300)
  339. #endif
  340. #endif
  341. /* Mark required libraries */
  342. #if defined(_MSC_VER)
  343. #pragma comment(lib, "Ws2_32.lib")
  344. #endif
  345. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  346. WINDOWS / UNIX include block */
  347. #include <sys/wait.h>
  348. #include <sys/socket.h>
  349. #include <sys/poll.h>
  350. #include <netinet/in.h>
  351. #include <arpa/inet.h>
  352. #include <sys/time.h>
  353. #include <sys/utsname.h>
  354. #include <stdint.h>
  355. #include <inttypes.h>
  356. #include <netdb.h>
  357. #include <netinet/tcp.h>
  358. typedef const void *SOCK_OPT_TYPE;
  359. #if defined(ANDROID)
  360. typedef unsigned short int in_port_t;
  361. #endif
  362. #include <pwd.h>
  363. #include <unistd.h>
  364. #include <grp.h>
  365. #include <dirent.h>
  366. #define vsnprintf_impl vsnprintf
  367. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  368. #include <dlfcn.h>
  369. #endif
  370. #include <pthread.h>
  371. #if defined(__MACH__)
  372. #define SSL_LIB "libssl.dylib"
  373. #define CRYPTO_LIB "libcrypto.dylib"
  374. #else
  375. #if !defined(SSL_LIB)
  376. #define SSL_LIB "libssl.so"
  377. #endif
  378. #if !defined(CRYPTO_LIB)
  379. #define CRYPTO_LIB "libcrypto.so"
  380. #endif
  381. #endif
  382. #ifndef O_BINARY
  383. #define O_BINARY (0)
  384. #endif /* O_BINARY */
  385. #define closesocket(a) (close(a))
  386. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  387. #define mg_remove(conn, x) (remove(x))
  388. #define mg_sleep(x) (usleep((x)*1000))
  389. #define mg_opendir(conn, x) (opendir(x))
  390. #define mg_closedir(x) (closedir(x))
  391. #define mg_readdir(x) (readdir(x))
  392. #define ERRNO (errno)
  393. #define INVALID_SOCKET (-1)
  394. #define INT64_FMT PRId64
  395. #define UINT64_FMT PRIu64
  396. typedef int SOCKET;
  397. #define WINCDECL
  398. #if defined(__hpux)
  399. /* HPUX 11 does not have monotonic, fall back to realtime */
  400. #ifndef CLOCK_MONOTONIC
  401. #define CLOCK_MONOTONIC CLOCK_REALTIME
  402. #endif
  403. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  404. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  405. * the prototypes use int* rather than socklen_t* which matches the
  406. * actual library expectation. When called with the wrong size arg
  407. * accept() returns a zero client inet addr and check_acl() always
  408. * fails. Since socklen_t is widely used below, just force replace
  409. * their typedef with int. - DTL
  410. */
  411. #define socklen_t int
  412. #endif /* hpux */
  413. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  414. WINDOWS / UNIX include block */
  415. /* va_copy should always be a macro, C99 and C++11 - DTL */
  416. #ifndef va_copy
  417. #define va_copy(x, y) ((x) = (y))
  418. #endif
  419. #ifdef _WIN32
  420. /* Create substitutes for POSIX functions in Win32. */
  421. #if defined(__MINGW32__)
  422. /* Show no warning in case system functions are not used. */
  423. #pragma GCC diagnostic push
  424. #pragma GCC diagnostic ignored "-Wunused-function"
  425. #endif
  426. static CRITICAL_SECTION global_log_file_lock;
  427. static DWORD
  428. pthread_self(void)
  429. {
  430. return GetCurrentThreadId();
  431. }
  432. static int
  433. pthread_key_create(
  434. pthread_key_t *key,
  435. void (*_ignored)(void *) /* destructor not supported for Windows */
  436. )
  437. {
  438. (void)_ignored;
  439. if ((key != 0)) {
  440. *key = TlsAlloc();
  441. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  442. }
  443. return -2;
  444. }
  445. static int
  446. pthread_key_delete(pthread_key_t key)
  447. {
  448. return TlsFree(key) ? 0 : 1;
  449. }
  450. static int
  451. pthread_setspecific(pthread_key_t key, void *value)
  452. {
  453. return TlsSetValue(key, value) ? 0 : 1;
  454. }
  455. static void *
  456. pthread_getspecific(pthread_key_t key)
  457. {
  458. return TlsGetValue(key);
  459. }
  460. #if defined(__MINGW32__)
  461. /* Enable unused function warning again */
  462. #pragma GCC diagnostic pop
  463. #endif
  464. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  465. #else
  466. static pthread_mutexattr_t pthread_mutex_attr;
  467. #endif /* _WIN32 */
  468. #define PASSWORDS_FILE_NAME ".htpasswd"
  469. #define CGI_ENVIRONMENT_SIZE (4096)
  470. #define MAX_CGI_ENVIR_VARS (256)
  471. #define MG_BUF_LEN (8192)
  472. #ifndef MAX_REQUEST_SIZE
  473. #define MAX_REQUEST_SIZE (16384)
  474. #endif
  475. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  476. "request size length must be a positive number");
  477. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  478. #if !defined(DEBUG_TRACE)
  479. #if defined(DEBUG)
  480. #if defined(_WIN32_WCE)
  481. /* Create substitutes for POSIX functions in Win32. */
  482. #if defined(__MINGW32__)
  483. /* Show no warning in case system functions are not used. */
  484. #pragma GCC diagnostic push
  485. #pragma GCC diagnostic ignored "-Wunused-function"
  486. #endif
  487. static time_t
  488. time(time_t *ptime)
  489. {
  490. time_t t;
  491. SYSTEMTIME st;
  492. FILETIME ft;
  493. GetSystemTime(&st);
  494. SystemTimeToFileTime(&st, &ft);
  495. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  496. if (ptime != NULL) {
  497. *ptime = t;
  498. }
  499. return t;
  500. }
  501. static struct tm *
  502. localtime_s(const time_t *ptime, struct tm *ptm)
  503. {
  504. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  505. FILETIME ft, lft;
  506. SYSTEMTIME st;
  507. TIME_ZONE_INFORMATION tzinfo;
  508. if (ptm == NULL) {
  509. return NULL;
  510. }
  511. *(int64_t *)&ft = t;
  512. FileTimeToLocalFileTime(&ft, &lft);
  513. FileTimeToSystemTime(&lft, &st);
  514. ptm->tm_year = st.wYear - 1900;
  515. ptm->tm_mon = st.wMonth - 1;
  516. ptm->tm_wday = st.wDayOfWeek;
  517. ptm->tm_mday = st.wDay;
  518. ptm->tm_hour = st.wHour;
  519. ptm->tm_min = st.wMinute;
  520. ptm->tm_sec = st.wSecond;
  521. ptm->tm_yday = 0; /* hope nobody uses this */
  522. ptm->tm_isdst =
  523. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  524. return ptm;
  525. }
  526. static struct tm *
  527. gmtime_s(const time_t *ptime, struct tm *ptm)
  528. {
  529. /* FIXME(lsm): fix this. */
  530. return localtime_s(ptime, ptm);
  531. }
  532. static int mg_atomic_inc(volatile int *addr);
  533. static struct tm tm_array[MAX_WORKER_THREADS];
  534. static int tm_index = 0;
  535. static struct tm *
  536. localtime(const time_t *ptime)
  537. {
  538. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  539. return localtime_s(ptime, tm_array + i);
  540. }
  541. static struct tm *
  542. gmtime(const time_t *ptime)
  543. {
  544. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  545. return gmtime_s(ptime, tm_array + i);
  546. }
  547. static size_t
  548. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  549. {
  550. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  551. // for WinCE");
  552. return 0;
  553. }
  554. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  555. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  556. #define remove(f) mg_remove(NULL, f)
  557. static int
  558. rename(const char *a, const char *b)
  559. {
  560. wchar_t wa[PATH_MAX];
  561. wchar_t wb[PATH_MAX];
  562. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  563. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  564. return MoveFileW(wa, wb) ? 0 : -1;
  565. }
  566. struct stat {
  567. int64_t st_size;
  568. time_t st_mtime;
  569. };
  570. static int
  571. stat(const char *name, struct stat *st)
  572. {
  573. wchar_t wbuf[PATH_MAX];
  574. WIN32_FILE_ATTRIBUTE_DATA attr;
  575. time_t creation_time, write_time;
  576. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  577. memset(&attr, 0, sizeof(attr));
  578. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  579. st->st_size =
  580. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  581. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  582. attr.ftLastWriteTime.dwHighDateTime);
  583. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  584. attr.ftCreationTime.dwHighDateTime);
  585. if (creation_time > write_time) {
  586. st->st_mtime = creation_time;
  587. } else {
  588. st->st_mtime = write_time;
  589. }
  590. return 0;
  591. }
  592. #define access(x, a) 1 /* not required anyway */
  593. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  594. #define EEXIST 1 /* TODO: See Windows error codes */
  595. #define EACCES 2 /* TODO: See Windows error codes */
  596. #define ENOENT 3 /* TODO: See Windows Error codes */
  597. #if defined(__MINGW32__)
  598. /* Enable unused function warning again */
  599. #pragma GCC diagnostic pop
  600. #endif
  601. #endif /* defined(_WIN32_WCE) */
  602. static void DEBUG_TRACE_FUNC(const char *func,
  603. unsigned line,
  604. PRINTF_FORMAT_STRING(const char *fmt),
  605. ...) PRINTF_ARGS(3, 4);
  606. static void
  607. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  608. {
  609. va_list args;
  610. flockfile(stdout);
  611. printf("*** %lu.%p.%s.%u: ",
  612. (unsigned long)time(NULL),
  613. (void *)pthread_self(),
  614. func,
  615. line);
  616. va_start(args, fmt);
  617. vprintf(fmt, args);
  618. va_end(args);
  619. putchar('\n');
  620. fflush(stdout);
  621. funlockfile(stdout);
  622. }
  623. #define DEBUG_TRACE(fmt, ...) \
  624. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  625. #else
  626. #define DEBUG_TRACE(fmt, ...) \
  627. do { \
  628. } while (0)
  629. #endif /* DEBUG */
  630. #endif /* DEBUG_TRACE */
  631. #if defined(MEMORY_DEBUGGING)
  632. unsigned long mg_memory_debug_blockCount = 0;
  633. unsigned long mg_memory_debug_totalMemUsed = 0;
  634. static void *
  635. mg_malloc_ex(size_t size, const char *file, unsigned line)
  636. {
  637. void *data = malloc(size + sizeof(size_t));
  638. void *memory = 0;
  639. char mallocStr[256];
  640. if (data) {
  641. *(size_t *)data = size;
  642. mg_memory_debug_totalMemUsed += size;
  643. mg_memory_debug_blockCount++;
  644. memory = (void *)(((char *)data) + sizeof(size_t));
  645. }
  646. sprintf(mallocStr,
  647. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  648. memory,
  649. (unsigned long)size,
  650. mg_memory_debug_totalMemUsed,
  651. mg_memory_debug_blockCount,
  652. file,
  653. line);
  654. #if defined(_WIN32)
  655. OutputDebugStringA(mallocStr);
  656. #else
  657. DEBUG_TRACE("%s", mallocStr);
  658. #endif
  659. return memory;
  660. }
  661. static void *
  662. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  663. {
  664. void *data = mg_malloc_ex(size * count, file, line);
  665. if (data) {
  666. memset(data, 0, size);
  667. }
  668. return data;
  669. }
  670. static void
  671. mg_free_ex(void *memory, const char *file, unsigned line)
  672. {
  673. char mallocStr[256];
  674. void *data = (void *)(((char *)memory) - sizeof(size_t));
  675. size_t size;
  676. if (memory) {
  677. size = *(size_t *)data;
  678. mg_memory_debug_totalMemUsed -= size;
  679. mg_memory_debug_blockCount--;
  680. sprintf(mallocStr,
  681. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  682. memory,
  683. (unsigned long)size,
  684. mg_memory_debug_totalMemUsed,
  685. mg_memory_debug_blockCount,
  686. file,
  687. line);
  688. #if defined(_WIN32)
  689. OutputDebugStringA(mallocStr);
  690. #else
  691. DEBUG_TRACE("%s", mallocStr);
  692. #endif
  693. free(data);
  694. }
  695. }
  696. static void *
  697. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  698. {
  699. char mallocStr[256];
  700. void *data;
  701. void *_realloc;
  702. size_t oldsize;
  703. if (newsize) {
  704. if (memory) {
  705. data = (void *)(((char *)memory) - sizeof(size_t));
  706. oldsize = *(size_t *)data;
  707. _realloc = realloc(data, newsize + sizeof(size_t));
  708. if (_realloc) {
  709. data = _realloc;
  710. mg_memory_debug_totalMemUsed -= oldsize;
  711. sprintf(mallocStr,
  712. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  713. memory,
  714. (unsigned long)oldsize,
  715. mg_memory_debug_totalMemUsed,
  716. mg_memory_debug_blockCount,
  717. file,
  718. line);
  719. #if defined(_WIN32)
  720. OutputDebugStringA(mallocStr);
  721. #else
  722. DEBUG_TRACE("%s", mallocStr);
  723. #endif
  724. mg_memory_debug_totalMemUsed += newsize;
  725. sprintf(mallocStr,
  726. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  727. memory,
  728. (unsigned long)newsize,
  729. mg_memory_debug_totalMemUsed,
  730. mg_memory_debug_blockCount,
  731. file,
  732. line);
  733. #if defined(_WIN32)
  734. OutputDebugStringA(mallocStr);
  735. #else
  736. DEBUG_TRACE("%s", mallocStr);
  737. #endif
  738. *(size_t *)data = newsize;
  739. data = (void *)(((char *)data) + sizeof(size_t));
  740. } else {
  741. #if defined(_WIN32)
  742. OutputDebugStringA("MEM: realloc failed\n");
  743. #else
  744. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  745. #endif
  746. return _realloc;
  747. }
  748. } else {
  749. data = mg_malloc_ex(newsize, file, line);
  750. }
  751. } else {
  752. data = 0;
  753. mg_free_ex(memory, file, line);
  754. }
  755. return data;
  756. }
  757. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  758. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  759. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  760. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  761. #else
  762. static __inline void *
  763. mg_malloc(size_t a)
  764. {
  765. return malloc(a);
  766. }
  767. static __inline void *
  768. mg_calloc(size_t a, size_t b)
  769. {
  770. return calloc(a, b);
  771. }
  772. static __inline void *
  773. mg_realloc(void *a, size_t b)
  774. {
  775. return realloc(a, b);
  776. }
  777. static __inline void
  778. mg_free(void *a)
  779. {
  780. free(a);
  781. }
  782. #endif
  783. static void mg_vsnprintf(const struct mg_connection *conn,
  784. int *truncated,
  785. char *buf,
  786. size_t buflen,
  787. const char *fmt,
  788. va_list ap);
  789. static void mg_snprintf(const struct mg_connection *conn,
  790. int *truncated,
  791. char *buf,
  792. size_t buflen,
  793. PRINTF_FORMAT_STRING(const char *fmt),
  794. ...) PRINTF_ARGS(5, 6);
  795. /* This following lines are just meant as a reminder to use the mg-functions
  796. * for memory management */
  797. #ifdef malloc
  798. #undef malloc
  799. #endif
  800. #ifdef calloc
  801. #undef calloc
  802. #endif
  803. #ifdef realloc
  804. #undef realloc
  805. #endif
  806. #ifdef free
  807. #undef free
  808. #endif
  809. #ifdef snprintf
  810. #undef snprintf
  811. #endif
  812. #ifdef vsnprintf
  813. #undef vsnprintf
  814. #endif
  815. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  816. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  817. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  818. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  819. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  820. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  821. * but this define only works well for Windows. */
  822. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  823. #endif
  824. #define MD5_STATIC static
  825. #include "md5.inl"
  826. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  827. #ifdef NO_SOCKLEN_T
  828. typedef int socklen_t;
  829. #endif /* NO_SOCKLEN_T */
  830. #define _DARWIN_UNLIMITED_SELECT
  831. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  832. #if !defined(MSG_NOSIGNAL)
  833. #define MSG_NOSIGNAL (0)
  834. #endif
  835. #if !defined(SOMAXCONN)
  836. #define SOMAXCONN (100)
  837. #endif
  838. /* Size of the accepted socket queue */
  839. #if !defined(MGSQLEN)
  840. #define MGSQLEN (20)
  841. #endif
  842. #if defined(NO_SSL)
  843. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  844. typedef struct SSL_CTX SSL_CTX;
  845. #else
  846. #if defined(NO_SSL_DL)
  847. #include <openssl/ssl.h>
  848. #include <openssl/err.h>
  849. #include <openssl/crypto.h>
  850. #include <openssl/x509.h>
  851. #include <openssl/pem.h>
  852. #include <openssl/engine.h>
  853. #include <openssl/conf.h>
  854. #else
  855. /* SSL loaded dynamically from DLL.
  856. * I put the prototypes here to be independent from OpenSSL source
  857. * installation. */
  858. typedef struct ssl_st SSL;
  859. typedef struct ssl_method_st SSL_METHOD;
  860. typedef struct ssl_ctx_st SSL_CTX;
  861. typedef struct x509_store_ctx_st X509_STORE_CTX;
  862. #define SSL_CTRL_OPTIONS (32)
  863. #define SSL_CTRL_CLEAR_OPTIONS (77)
  864. #define SSL_CTRL_SET_ECDH_AUTO (94)
  865. #define SSL_VERIFY_NONE (0)
  866. #define SSL_VERIFY_PEER (1)
  867. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  868. #define SSL_VERIFY_CLIENT_ONCE (4)
  869. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  870. #define SSL_OP_NO_SSLv2 (0x01000000L)
  871. #define SSL_OP_NO_SSLv3 (0x02000000L)
  872. #define SSL_OP_NO_TLSv1 (0x04000000L)
  873. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  874. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  875. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  876. #define SSL_ERROR_NONE (0)
  877. #define SSL_ERROR_SSL (1)
  878. #define SSL_ERROR_WANT_READ (2)
  879. #define SSL_ERROR_WANT_WRITE (3)
  880. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  881. #define SSL_ERROR_SYSCALL (5) /* see errno */
  882. #define SSL_ERROR_ZERO_RETURN (6)
  883. #define SSL_ERROR_WANT_CONNECT (7)
  884. #define SSL_ERROR_WANT_ACCEPT (8)
  885. struct ssl_func {
  886. const char *name; /* SSL function name */
  887. void (*ptr)(void); /* Function pointer */
  888. };
  889. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  890. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  891. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  892. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  893. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  894. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  895. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  896. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  897. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  898. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  899. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  900. #define SSL_CTX_use_PrivateKey_file \
  901. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  902. #define SSL_CTX_use_certificate_file \
  903. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  904. #define SSL_CTX_set_default_passwd_cb \
  905. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  906. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  907. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  908. #define SSL_CTX_use_certificate_chain_file \
  909. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  910. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  911. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  912. #define SSL_CTX_set_verify \
  913. (*(void (*)(SSL_CTX *, \
  914. int, \
  915. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  916. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  917. #define SSL_CTX_load_verify_locations \
  918. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  919. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  920. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  921. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  922. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  923. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  924. #define SSL_CIPHER_get_name \
  925. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  926. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  927. #define SSL_CTX_set_session_id_context \
  928. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  929. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  930. #define SSL_CTX_set_cipher_list \
  931. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  932. #define SSL_CTX_set_options(ctx, op) \
  933. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  934. #define SSL_CTX_clear_options(ctx, op) \
  935. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  936. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  937. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  938. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  939. #define CRYPTO_set_locking_callback \
  940. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  941. #define CRYPTO_set_id_callback \
  942. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  943. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  944. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  945. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  946. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  947. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  948. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  949. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  950. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  951. /* set_ssl_option() function updates this array.
  952. * It loads SSL library dynamically and changes NULLs to the actual addresses
  953. * of respective functions. The macros above (like SSL_connect()) are really
  954. * just calling these functions indirectly via the pointer. */
  955. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  956. {"SSL_accept", NULL},
  957. {"SSL_connect", NULL},
  958. {"SSL_read", NULL},
  959. {"SSL_write", NULL},
  960. {"SSL_get_error", NULL},
  961. {"SSL_set_fd", NULL},
  962. {"SSL_new", NULL},
  963. {"SSL_CTX_new", NULL},
  964. {"SSLv23_server_method", NULL},
  965. {"SSL_library_init", NULL},
  966. {"SSL_CTX_use_PrivateKey_file", NULL},
  967. {"SSL_CTX_use_certificate_file", NULL},
  968. {"SSL_CTX_set_default_passwd_cb", NULL},
  969. {"SSL_CTX_free", NULL},
  970. {"SSL_load_error_strings", NULL},
  971. {"SSL_CTX_use_certificate_chain_file", NULL},
  972. {"SSLv23_client_method", NULL},
  973. {"SSL_pending", NULL},
  974. {"SSL_CTX_set_verify", NULL},
  975. {"SSL_shutdown", NULL},
  976. {"SSL_CTX_load_verify_locations", NULL},
  977. {"SSL_CTX_set_default_verify_paths", NULL},
  978. {"SSL_CTX_set_verify_depth", NULL},
  979. {"SSL_get_peer_certificate", NULL},
  980. {"SSL_get_version", NULL},
  981. {"SSL_get_current_cipher", NULL},
  982. {"SSL_CIPHER_get_name", NULL},
  983. {"SSL_CTX_check_private_key", NULL},
  984. {"SSL_CTX_set_session_id_context", NULL},
  985. {"SSL_CTX_ctrl", NULL},
  986. {"SSL_CTX_set_cipher_list", NULL},
  987. {NULL, NULL}};
  988. /* Similar array as ssl_sw. These functions could be located in different
  989. * lib. */
  990. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  991. {"CRYPTO_set_locking_callback", NULL},
  992. {"CRYPTO_set_id_callback", NULL},
  993. {"ERR_get_error", NULL},
  994. {"ERR_error_string", NULL},
  995. {"ERR_remove_state", NULL},
  996. {"ERR_free_strings", NULL},
  997. {"ENGINE_cleanup", NULL},
  998. {"CONF_modules_unload", NULL},
  999. {"CRYPTO_cleanup_all_ex_data", NULL},
  1000. {"EVP_cleanup", NULL},
  1001. {NULL, NULL}};
  1002. #endif /* NO_SSL_DL */
  1003. #endif /* NO_SSL */
  1004. #if !defined(NO_CACHING)
  1005. static const char *month_names[] = {"Jan",
  1006. "Feb",
  1007. "Mar",
  1008. "Apr",
  1009. "May",
  1010. "Jun",
  1011. "Jul",
  1012. "Aug",
  1013. "Sep",
  1014. "Oct",
  1015. "Nov",
  1016. "Dec"};
  1017. #endif /* !NO_CACHING */
  1018. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1019. * union u. */
  1020. union usa {
  1021. struct sockaddr sa;
  1022. struct sockaddr_in sin;
  1023. #if defined(USE_IPV6)
  1024. struct sockaddr_in6 sin6;
  1025. #endif
  1026. };
  1027. /* Describes a string (chunk of memory). */
  1028. struct vec {
  1029. const char *ptr;
  1030. size_t len;
  1031. };
  1032. struct file {
  1033. uint64_t size;
  1034. time_t last_modified;
  1035. FILE *fp;
  1036. const char *membuf; /* Non-NULL if file data is in memory */
  1037. int is_directory;
  1038. int gzipped; /* set to 1 if the content is gzipped
  1039. * in which case we need a content-encoding: gzip header */
  1040. };
  1041. #define STRUCT_FILE_INITIALIZER \
  1042. { \
  1043. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1044. }
  1045. /* Describes listening socket, or socket which was accept()-ed by the master
  1046. * thread and queued for future handling by the worker thread. */
  1047. struct socket {
  1048. SOCKET sock; /* Listening socket */
  1049. union usa lsa; /* Local socket address */
  1050. union usa rsa; /* Remote socket address */
  1051. unsigned char is_ssl; /* Is port SSL-ed */
  1052. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1053. * port */
  1054. unsigned char in_use; /* Is valid */
  1055. };
  1056. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1057. enum {
  1058. CGI_EXTENSIONS,
  1059. CGI_ENVIRONMENT,
  1060. PUT_DELETE_PASSWORDS_FILE,
  1061. CGI_INTERPRETER,
  1062. PROTECT_URI,
  1063. AUTHENTICATION_DOMAIN,
  1064. SSI_EXTENSIONS,
  1065. THROTTLE,
  1066. ACCESS_LOG_FILE,
  1067. ENABLE_DIRECTORY_LISTING,
  1068. ERROR_LOG_FILE,
  1069. GLOBAL_PASSWORDS_FILE,
  1070. INDEX_FILES,
  1071. ENABLE_KEEP_ALIVE,
  1072. ACCESS_CONTROL_LIST,
  1073. EXTRA_MIME_TYPES,
  1074. LISTENING_PORTS,
  1075. DOCUMENT_ROOT,
  1076. SSL_CERTIFICATE,
  1077. NUM_THREADS,
  1078. RUN_AS_USER,
  1079. REWRITE,
  1080. HIDE_FILES,
  1081. REQUEST_TIMEOUT,
  1082. SSL_DO_VERIFY_PEER,
  1083. SSL_CA_PATH,
  1084. SSL_CA_FILE,
  1085. SSL_VERIFY_DEPTH,
  1086. SSL_DEFAULT_VERIFY_PATHS,
  1087. SSL_CIPHER_LIST,
  1088. SSL_PROTOCOL_VERSION,
  1089. SSL_SHORT_TRUST,
  1090. #if defined(USE_WEBSOCKET)
  1091. WEBSOCKET_TIMEOUT,
  1092. #endif
  1093. DECODE_URL,
  1094. #if defined(USE_LUA)
  1095. LUA_PRELOAD_FILE,
  1096. LUA_SCRIPT_EXTENSIONS,
  1097. LUA_SERVER_PAGE_EXTENSIONS,
  1098. #endif
  1099. #if defined(USE_DUKTAPE)
  1100. DUKTAPE_SCRIPT_EXTENSIONS,
  1101. #endif
  1102. #if defined(USE_WEBSOCKET)
  1103. WEBSOCKET_ROOT,
  1104. #endif
  1105. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1106. LUA_WEBSOCKET_EXTENSIONS,
  1107. #endif
  1108. ACCESS_CONTROL_ALLOW_ORIGIN,
  1109. ERROR_PAGES,
  1110. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1111. * socket option typedef TCP_NODELAY. */
  1112. #if !defined(NO_CACHING)
  1113. STATIC_FILE_MAX_AGE,
  1114. #endif
  1115. NUM_OPTIONS
  1116. };
  1117. /* Config option name, config types, default value */
  1118. static struct mg_option config_options[] = {
  1119. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1120. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1121. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1122. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1123. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1124. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1125. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1126. {"throttle", CONFIG_TYPE_STRING, NULL},
  1127. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1128. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1129. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1130. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1131. {"index_files",
  1132. CONFIG_TYPE_STRING,
  1133. #ifdef USE_LUA
  1134. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1135. "index.shtml,index.php"},
  1136. #else
  1137. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1138. #endif
  1139. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1140. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1141. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1142. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1143. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1144. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1145. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1146. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1147. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1148. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1149. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1150. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1151. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1152. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1153. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1154. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1155. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1156. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1157. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1158. #if defined(USE_WEBSOCKET)
  1159. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1160. #endif
  1161. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1162. #if defined(USE_LUA)
  1163. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1164. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1165. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1166. #endif
  1167. #if defined(USE_DUKTAPE)
  1168. /* The support for duktape is still in alpha version state.
  1169. * The name of this config option might change. */
  1170. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1171. #endif
  1172. #if defined(USE_WEBSOCKET)
  1173. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1174. #endif
  1175. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1176. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1177. #endif
  1178. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1179. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1180. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1181. #if !defined(NO_CACHING)
  1182. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1183. #endif
  1184. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1185. /* Check if the config_options and the corresponding enum have compatible
  1186. * sizes. */
  1187. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1188. == (NUM_OPTIONS + 1),
  1189. "config_options and enum not sync");
  1190. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1191. struct mg_handler_info {
  1192. /* Name/Pattern of the URI. */
  1193. char *uri;
  1194. size_t uri_len;
  1195. /* handler type */
  1196. int handler_type;
  1197. /* Handler for http/https or authorization requests. */
  1198. mg_request_handler handler;
  1199. /* Handler for ws/wss (websocket) requests. */
  1200. mg_websocket_connect_handler connect_handler;
  1201. mg_websocket_ready_handler ready_handler;
  1202. mg_websocket_data_handler data_handler;
  1203. mg_websocket_close_handler close_handler;
  1204. /* Handler for authorization requests */
  1205. mg_authorization_handler auth_handler;
  1206. /* User supplied argument for the handler function. */
  1207. void *cbdata;
  1208. /* next handler in a linked list */
  1209. struct mg_handler_info *next;
  1210. };
  1211. struct mg_context {
  1212. volatile int stop_flag; /* Should we stop event loop */
  1213. SSL_CTX *ssl_ctx; /* SSL context */
  1214. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1215. struct mg_callbacks callbacks; /* User-defined callback function */
  1216. void *user_data; /* User-defined data */
  1217. int context_type; /* 1 = server context, 2 = client context */
  1218. struct socket *listening_sockets;
  1219. struct pollfd *listening_socket_fds;
  1220. unsigned int num_listening_sockets;
  1221. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1222. #ifdef ALTERNATIVE_QUEUE
  1223. struct socket *client_socks;
  1224. int *client_wait_events;
  1225. #else
  1226. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1227. volatile int sq_head; /* Head of the socket queue */
  1228. volatile int sq_tail; /* Tail of the socket queue */
  1229. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1230. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1231. #endif
  1232. pthread_t masterthreadid; /* The master thread ID */
  1233. unsigned int
  1234. cfg_worker_threads; /* The number of configured worker threads. */
  1235. pthread_t *workerthreadids; /* The worker thread IDs */
  1236. time_t start_time; /* Server start time, used for authentication */
  1237. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1238. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1239. unsigned long nonce_count; /* Used nonces, used for authentication */
  1240. char *systemName; /* What operating system is running */
  1241. /* linked list of uri handlers */
  1242. struct mg_handler_info *handlers;
  1243. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1244. /* linked list of shared lua websockets */
  1245. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1246. #endif
  1247. #ifdef USE_TIMERS
  1248. struct ttimers *timers;
  1249. #endif
  1250. };
  1251. struct mg_connection {
  1252. struct mg_request_info request_info;
  1253. struct mg_context *ctx;
  1254. SSL *ssl; /* SSL descriptor */
  1255. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1256. struct socket client; /* Connected client */
  1257. time_t conn_birth_time; /* Time (wall clock) when connection was
  1258. * established */
  1259. struct timespec req_time; /* Time (since system start) when the request
  1260. * was received */
  1261. int64_t num_bytes_sent; /* Total bytes sent to client */
  1262. int64_t content_len; /* Content-Length header value */
  1263. int64_t consumed_content; /* How many bytes of content have been read */
  1264. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1265. * data available, 2: all data read */
  1266. size_t chunk_remainder; /* Unread data from the last chunk */
  1267. char *buf; /* Buffer for received data */
  1268. char *path_info; /* PATH_INFO part of the URL */
  1269. int must_close; /* 1 if connection must be closed */
  1270. int in_error_handler; /* 1 if in handler for user defined error
  1271. * pages */
  1272. int internal_error; /* 1 if an error occured while processing the
  1273. * request */
  1274. int buf_size; /* Buffer size */
  1275. int request_len; /* Size of the request + headers in a buffer */
  1276. int data_len; /* Total size of data in a buffer */
  1277. int status_code; /* HTTP reply status code, e.g. 200 */
  1278. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1279. * throttle */
  1280. time_t last_throttle_time; /* Last time throttled data was sent */
  1281. int64_t last_throttle_bytes; /* Bytes sent this second */
  1282. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1283. * atomic transmissions for websockets */
  1284. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1285. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1286. #endif
  1287. int thread_index; /* Thread index within ctx */
  1288. };
  1289. static pthread_key_t sTlsKey; /* Thread local storage index */
  1290. static int sTlsInit = 0;
  1291. static int thread_idx_max = 0;
  1292. struct mg_workerTLS {
  1293. int is_master;
  1294. unsigned long thread_idx;
  1295. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1296. HANDLE pthread_cond_helper_mutex;
  1297. struct mg_workerTLS *next_waiting_thread;
  1298. #endif
  1299. };
  1300. /* Directory entry */
  1301. struct de {
  1302. struct mg_connection *conn;
  1303. char *file_name;
  1304. struct file file;
  1305. };
  1306. #if defined(USE_WEBSOCKET)
  1307. static int is_websocket_protocol(const struct mg_connection *conn);
  1308. #else
  1309. #define is_websocket_protocol(conn) (0)
  1310. #endif
  1311. static int
  1312. mg_atomic_inc(volatile int *addr)
  1313. {
  1314. int ret;
  1315. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1316. /* Depending on the SDK, this function uses either
  1317. * (volatile unsigned int *) or (volatile LONG *),
  1318. * so whatever you use, the other SDK is likely to raise a warning. */
  1319. ret = InterlockedIncrement((volatile long *)addr);
  1320. #elif defined(__GNUC__) \
  1321. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1322. ret = __sync_add_and_fetch(addr, 1);
  1323. #else
  1324. ret = (++(*addr));
  1325. #endif
  1326. return ret;
  1327. }
  1328. static int
  1329. mg_atomic_dec(volatile int *addr)
  1330. {
  1331. int ret;
  1332. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1333. /* Depending on the SDK, this function uses either
  1334. * (volatile unsigned int *) or (volatile LONG *),
  1335. * so whatever you use, the other SDK is likely to raise a warning. */
  1336. ret = InterlockedDecrement((volatile long *)addr);
  1337. #elif defined(__GNUC__) \
  1338. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1339. ret = __sync_sub_and_fetch(addr, 1);
  1340. #else
  1341. ret = (--(*addr));
  1342. #endif
  1343. return ret;
  1344. }
  1345. #if !defined(NO_THREAD_NAME)
  1346. #if defined(_WIN32) && defined(_MSC_VER)
  1347. /* Set the thread name for debugging purposes in Visual Studio
  1348. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1349. */
  1350. #pragma pack(push, 8)
  1351. typedef struct tagTHREADNAME_INFO {
  1352. DWORD dwType; /* Must be 0x1000. */
  1353. LPCSTR szName; /* Pointer to name (in user addr space). */
  1354. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1355. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1356. } THREADNAME_INFO;
  1357. #pragma pack(pop)
  1358. #elif defined(__linux__)
  1359. #include <sys/prctl.h>
  1360. #include <sys/sendfile.h>
  1361. #include <sys/eventfd.h>
  1362. #ifdef ALTERNATIVE_QUEUE
  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. #endif
  1404. static void
  1405. mg_set_thread_name(const char *name)
  1406. {
  1407. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1408. mg_snprintf(
  1409. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1410. #if defined(_WIN32)
  1411. #if defined(_MSC_VER)
  1412. /* Windows and Visual Studio Compiler */
  1413. __try
  1414. {
  1415. THREADNAME_INFO info;
  1416. info.dwType = 0x1000;
  1417. info.szName = threadName;
  1418. info.dwThreadID = ~0U;
  1419. info.dwFlags = 0;
  1420. RaiseException(0x406D1388,
  1421. 0,
  1422. sizeof(info) / sizeof(ULONG_PTR),
  1423. (ULONG_PTR *)&info);
  1424. }
  1425. __except(EXCEPTION_EXECUTE_HANDLER)
  1426. {
  1427. }
  1428. #elif defined(__MINGW32__)
  1429. /* No option known to set thread name for MinGW */
  1430. #endif
  1431. #elif defined(__GLIBC__) \
  1432. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1433. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1434. (void)pthread_setname_np(pthread_self(), threadName);
  1435. #elif defined(__linux__)
  1436. /* on linux we can use the old prctl function */
  1437. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1438. #endif
  1439. }
  1440. #else /* !defined(NO_THREAD_NAME) */
  1441. void
  1442. mg_set_thread_name(const char *threadName)
  1443. {
  1444. }
  1445. #endif
  1446. #if defined(MG_LEGACY_INTERFACE)
  1447. const char **
  1448. mg_get_valid_option_names(void)
  1449. {
  1450. /* This function is deprecated. Use mg_get_valid_options instead. */
  1451. static const char *
  1452. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1453. int i;
  1454. for (i = 0; config_options[i].name != NULL; i++) {
  1455. data[i * 2] = config_options[i].name;
  1456. data[i * 2 + 1] = config_options[i].default_value;
  1457. }
  1458. return data;
  1459. }
  1460. #endif
  1461. const struct mg_option *
  1462. mg_get_valid_options(void)
  1463. {
  1464. return config_options;
  1465. }
  1466. static int
  1467. is_file_in_memory(const struct mg_connection *conn,
  1468. const char *path,
  1469. struct file *filep)
  1470. {
  1471. size_t size = 0;
  1472. if (!conn || !filep) {
  1473. return 0;
  1474. }
  1475. if (conn->ctx->callbacks.open_file) {
  1476. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1477. if (filep->membuf != NULL) {
  1478. /* NOTE: override filep->size only on success. Otherwise, it might
  1479. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1480. filep->size = size;
  1481. }
  1482. }
  1483. return filep->membuf != NULL;
  1484. }
  1485. static int
  1486. is_file_opened(const struct file *filep)
  1487. {
  1488. if (!filep) {
  1489. return 0;
  1490. }
  1491. return filep->membuf != NULL || filep->fp != NULL;
  1492. }
  1493. /* mg_fopen will open a file either in memory or on the disk.
  1494. * The input parameter path is a string in UTF-8 encoding.
  1495. * The input parameter mode is the same as for fopen.
  1496. * Either fp or membuf will be set in the output struct filep.
  1497. * The function returns 1 on success, 0 on error. */
  1498. static int
  1499. mg_fopen(const struct mg_connection *conn,
  1500. const char *path,
  1501. const char *mode,
  1502. struct file *filep)
  1503. {
  1504. struct stat st;
  1505. if (!filep) {
  1506. return 0;
  1507. }
  1508. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1509. * only get the file status. They should not work on different members of
  1510. * the same structure (bad cohesion). */
  1511. memset(filep, 0, sizeof(*filep));
  1512. if (stat(path, &st) == 0) {
  1513. filep->size = (uint64_t)(st.st_size);
  1514. }
  1515. if (!is_file_in_memory(conn, path, filep)) {
  1516. #ifdef _WIN32
  1517. wchar_t wbuf[PATH_MAX], wmode[20];
  1518. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1519. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1520. filep->fp = _wfopen(wbuf, wmode);
  1521. #else
  1522. /* Linux et al already use unicode. No need to convert. */
  1523. filep->fp = fopen(path, mode);
  1524. #endif
  1525. }
  1526. return is_file_opened(filep);
  1527. }
  1528. static void
  1529. mg_fclose(struct file *filep)
  1530. {
  1531. if (filep != NULL && filep->fp != NULL) {
  1532. fclose(filep->fp);
  1533. }
  1534. }
  1535. static void
  1536. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1537. {
  1538. for (; *src != '\0' && n > 1; n--) {
  1539. *dst++ = *src++;
  1540. }
  1541. *dst = '\0';
  1542. }
  1543. static int
  1544. lowercase(const char *s)
  1545. {
  1546. return tolower(*(const unsigned char *)s);
  1547. }
  1548. int
  1549. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1550. {
  1551. int diff = 0;
  1552. if (len > 0) {
  1553. do {
  1554. diff = lowercase(s1++) - lowercase(s2++);
  1555. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1556. }
  1557. return diff;
  1558. }
  1559. int
  1560. mg_strcasecmp(const char *s1, const char *s2)
  1561. {
  1562. int diff;
  1563. do {
  1564. diff = lowercase(s1++) - lowercase(s2++);
  1565. } while (diff == 0 && s1[-1] != '\0');
  1566. return diff;
  1567. }
  1568. static char *
  1569. mg_strndup(const char *ptr, size_t len)
  1570. {
  1571. char *p;
  1572. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1573. mg_strlcpy(p, ptr, len + 1);
  1574. }
  1575. return p;
  1576. }
  1577. static char *
  1578. mg_strdup(const char *str)
  1579. {
  1580. return mg_strndup(str, strlen(str));
  1581. }
  1582. static const char *
  1583. mg_strcasestr(const char *big_str, const char *small_str)
  1584. {
  1585. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1586. if (big_len >= small_len) {
  1587. for (i = 0; i <= (big_len - small_len); i++) {
  1588. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1589. return big_str + i;
  1590. }
  1591. }
  1592. }
  1593. return NULL;
  1594. }
  1595. /* Return null terminated string of given maximum length.
  1596. * Report errors if length is exceeded. */
  1597. static void
  1598. mg_vsnprintf(const struct mg_connection *conn,
  1599. int *truncated,
  1600. char *buf,
  1601. size_t buflen,
  1602. const char *fmt,
  1603. va_list ap)
  1604. {
  1605. int n, ok;
  1606. if (buflen == 0) {
  1607. return;
  1608. }
  1609. #ifdef __clang__
  1610. #pragma clang diagnostic push
  1611. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1612. /* Using fmt as a non-literal is intended here, since it is mostly called
  1613. * indirectly by mg_snprintf */
  1614. #endif
  1615. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1616. ok = (n >= 0) && ((size_t)n < buflen);
  1617. #ifdef __clang__
  1618. #pragma clang diagnostic pop
  1619. #endif
  1620. if (ok) {
  1621. if (truncated) {
  1622. *truncated = 0;
  1623. }
  1624. } else {
  1625. if (truncated) {
  1626. *truncated = 1;
  1627. }
  1628. mg_cry(conn,
  1629. "truncating vsnprintf buffer: [%.*s]",
  1630. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1631. buf);
  1632. n = (int)buflen - 1;
  1633. }
  1634. buf[n] = '\0';
  1635. }
  1636. static void
  1637. mg_snprintf(const struct mg_connection *conn,
  1638. int *truncated,
  1639. char *buf,
  1640. size_t buflen,
  1641. const char *fmt,
  1642. ...)
  1643. {
  1644. va_list ap;
  1645. va_start(ap, fmt);
  1646. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1647. va_end(ap);
  1648. }
  1649. static int
  1650. get_option_index(const char *name)
  1651. {
  1652. int i;
  1653. for (i = 0; config_options[i].name != NULL; i++) {
  1654. if (strcmp(config_options[i].name, name) == 0) {
  1655. return i;
  1656. }
  1657. }
  1658. return -1;
  1659. }
  1660. const char *
  1661. mg_get_option(const struct mg_context *ctx, const char *name)
  1662. {
  1663. int i;
  1664. if ((i = get_option_index(name)) == -1) {
  1665. return NULL;
  1666. } else if (!ctx || ctx->config[i] == NULL) {
  1667. return "";
  1668. } else {
  1669. return ctx->config[i];
  1670. }
  1671. }
  1672. struct mg_context *
  1673. mg_get_context(const struct mg_connection *conn)
  1674. {
  1675. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1676. }
  1677. void *
  1678. mg_get_user_data(const struct mg_context *ctx)
  1679. {
  1680. return (ctx == NULL) ? NULL : ctx->user_data;
  1681. }
  1682. void
  1683. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1684. {
  1685. if (conn != NULL) {
  1686. conn->request_info.conn_data = data;
  1687. }
  1688. }
  1689. void *
  1690. mg_get_user_connection_data(const struct mg_connection *conn)
  1691. {
  1692. if (conn != NULL) {
  1693. return conn->request_info.conn_data;
  1694. }
  1695. return NULL;
  1696. }
  1697. size_t
  1698. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1699. {
  1700. size_t i;
  1701. if (!ctx) {
  1702. return 0;
  1703. }
  1704. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1705. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1706. ports[i] =
  1707. #if defined(USE_IPV6)
  1708. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1709. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1710. :
  1711. #endif
  1712. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1713. }
  1714. return i;
  1715. }
  1716. int
  1717. mg_get_server_ports(const struct mg_context *ctx,
  1718. int size,
  1719. struct mg_server_ports *ports)
  1720. {
  1721. int i, cnt = 0;
  1722. if (size <= 0) {
  1723. return -1;
  1724. }
  1725. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1726. if (!ctx) {
  1727. return -1;
  1728. }
  1729. if (!ctx->listening_sockets) {
  1730. return -1;
  1731. }
  1732. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1733. ports[cnt].port =
  1734. #if defined(USE_IPV6)
  1735. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1736. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1737. :
  1738. #endif
  1739. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1740. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1741. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1742. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1743. /* IPv4 */
  1744. ports[cnt].protocol = 1;
  1745. cnt++;
  1746. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1747. /* IPv6 */
  1748. ports[cnt].protocol = 3;
  1749. cnt++;
  1750. }
  1751. }
  1752. return cnt;
  1753. }
  1754. static void
  1755. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1756. {
  1757. buf[0] = '\0';
  1758. if (!usa) {
  1759. return;
  1760. }
  1761. if (usa->sa.sa_family == AF_INET) {
  1762. getnameinfo(&usa->sa,
  1763. sizeof(usa->sin),
  1764. buf,
  1765. (unsigned)len,
  1766. NULL,
  1767. 0,
  1768. NI_NUMERICHOST);
  1769. }
  1770. #if defined(USE_IPV6)
  1771. else if (usa->sa.sa_family == AF_INET6) {
  1772. getnameinfo(&usa->sa,
  1773. sizeof(usa->sin6),
  1774. buf,
  1775. (unsigned)len,
  1776. NULL,
  1777. 0,
  1778. NI_NUMERICHOST);
  1779. }
  1780. #endif
  1781. }
  1782. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1783. * included in all responses other than 100, 101, 5xx. */
  1784. static void
  1785. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1786. {
  1787. struct tm *tm;
  1788. tm = ((t != NULL) ? gmtime(t) : NULL);
  1789. if (tm != NULL) {
  1790. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1791. } else {
  1792. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1793. buf[buf_len - 1] = '\0';
  1794. }
  1795. }
  1796. /* difftime for struct timespec. Return value is in seconds. */
  1797. static double
  1798. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1799. {
  1800. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1801. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1802. }
  1803. /* Print error message to the opened error log stream. */
  1804. void
  1805. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1806. {
  1807. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1808. va_list ap;
  1809. struct file fi;
  1810. time_t timestamp;
  1811. va_start(ap, fmt);
  1812. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1813. va_end(ap);
  1814. buf[sizeof(buf) - 1] = 0;
  1815. if (!conn) {
  1816. puts(buf);
  1817. return;
  1818. }
  1819. /* Do not lock when getting the callback value, here and below.
  1820. * I suppose this is fine, since function cannot disappear in the
  1821. * same way string option can. */
  1822. if ((conn->ctx->callbacks.log_message == NULL)
  1823. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1824. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1825. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1826. == 0) {
  1827. fi.fp = NULL;
  1828. }
  1829. } else {
  1830. fi.fp = NULL;
  1831. }
  1832. if (fi.fp != NULL) {
  1833. flockfile(fi.fp);
  1834. timestamp = time(NULL);
  1835. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1836. fprintf(fi.fp,
  1837. "[%010lu] [error] [client %s] ",
  1838. (unsigned long)timestamp,
  1839. src_addr);
  1840. if (conn->request_info.request_method != NULL) {
  1841. fprintf(fi.fp,
  1842. "%s %s: ",
  1843. conn->request_info.request_method,
  1844. conn->request_info.request_uri);
  1845. }
  1846. fprintf(fi.fp, "%s", buf);
  1847. fputc('\n', fi.fp);
  1848. fflush(fi.fp);
  1849. funlockfile(fi.fp);
  1850. mg_fclose(&fi);
  1851. }
  1852. }
  1853. }
  1854. /* Return fake connection structure. Used for logging, if connection
  1855. * is not applicable at the moment of logging. */
  1856. static struct mg_connection *
  1857. fc(struct mg_context *ctx)
  1858. {
  1859. static struct mg_connection fake_connection;
  1860. fake_connection.ctx = ctx;
  1861. return &fake_connection;
  1862. }
  1863. const char *
  1864. mg_version(void)
  1865. {
  1866. return CIVETWEB_VERSION;
  1867. }
  1868. const struct mg_request_info *
  1869. mg_get_request_info(const struct mg_connection *conn)
  1870. {
  1871. if (!conn) {
  1872. return NULL;
  1873. }
  1874. return &conn->request_info;
  1875. }
  1876. /* Skip the characters until one of the delimiters characters found.
  1877. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1878. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1879. * Delimiters can be quoted with quotechar. */
  1880. static char *
  1881. skip_quoted(char **buf,
  1882. const char *delimiters,
  1883. const char *whitespace,
  1884. char quotechar)
  1885. {
  1886. char *p, *begin_word, *end_word, *end_whitespace;
  1887. begin_word = *buf;
  1888. end_word = begin_word + strcspn(begin_word, delimiters);
  1889. /* Check for quotechar */
  1890. if (end_word > begin_word) {
  1891. p = end_word - 1;
  1892. while (*p == quotechar) {
  1893. /* While the delimiter is quoted, look for the next delimiter. */
  1894. /* This happens, e.g., in calls from parse_auth_header,
  1895. * if the user name contains a " character. */
  1896. /* If there is anything beyond end_word, copy it. */
  1897. if (*end_word != '\0') {
  1898. size_t end_off = strcspn(end_word + 1, delimiters);
  1899. memmove(p, end_word, end_off + 1);
  1900. p += end_off; /* p must correspond to end_word - 1 */
  1901. end_word += end_off + 1;
  1902. } else {
  1903. *p = '\0';
  1904. break;
  1905. }
  1906. }
  1907. for (p++; p < end_word; p++) {
  1908. *p = '\0';
  1909. }
  1910. }
  1911. if (*end_word == '\0') {
  1912. *buf = end_word;
  1913. } else {
  1914. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1915. for (p = end_word; p < end_whitespace; p++) {
  1916. *p = '\0';
  1917. }
  1918. *buf = end_whitespace;
  1919. }
  1920. return begin_word;
  1921. }
  1922. /* Simplified version of skip_quoted without quote char
  1923. * and whitespace == delimiters */
  1924. static char *
  1925. skip(char **buf, const char *delimiters)
  1926. {
  1927. return skip_quoted(buf, delimiters, delimiters, 0);
  1928. }
  1929. /* Return HTTP header value, or NULL if not found. */
  1930. static const char *
  1931. get_header(const struct mg_request_info *ri, const char *name)
  1932. {
  1933. int i;
  1934. if (ri) {
  1935. for (i = 0; i < ri->num_headers; i++) {
  1936. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1937. return ri->http_headers[i].value;
  1938. }
  1939. }
  1940. }
  1941. return NULL;
  1942. }
  1943. const char *
  1944. mg_get_header(const struct mg_connection *conn, const char *name)
  1945. {
  1946. if (!conn) {
  1947. return NULL;
  1948. }
  1949. return get_header(&conn->request_info, name);
  1950. }
  1951. /* A helper function for traversing a comma separated list of values.
  1952. * It returns a list pointer shifted to the next value, or NULL if the end
  1953. * of the list found.
  1954. * Value is stored in val vector. If value has form "x=y", then eq_val
  1955. * vector is initialized to point to the "y" part, and val vector length
  1956. * is adjusted to point only to "x". */
  1957. static const char *
  1958. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1959. {
  1960. int end;
  1961. reparse:
  1962. if (val == NULL || list == NULL || *list == '\0') {
  1963. /* End of the list */
  1964. list = NULL;
  1965. } else {
  1966. /* Skip over leading LWS */
  1967. while (*list == ' ' || *list == '\t')
  1968. list++;
  1969. val->ptr = list;
  1970. if ((list = strchr(val->ptr, ',')) != NULL) {
  1971. /* Comma found. Store length and shift the list ptr */
  1972. val->len = ((size_t)(list - val->ptr));
  1973. list++;
  1974. } else {
  1975. /* This value is the last one */
  1976. list = val->ptr + strlen(val->ptr);
  1977. val->len = ((size_t)(list - val->ptr));
  1978. }
  1979. /* Adjust length for trailing LWS */
  1980. end = (int)val->len - 1;
  1981. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1982. end--;
  1983. val->len = (size_t)(end + 1);
  1984. if (val->len == 0) {
  1985. /* Ignore any empty entries. */
  1986. goto reparse;
  1987. }
  1988. if (eq_val != NULL) {
  1989. /* Value has form "x=y", adjust pointers and lengths
  1990. * so that val points to "x", and eq_val points to "y". */
  1991. eq_val->len = 0;
  1992. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1993. if (eq_val->ptr != NULL) {
  1994. eq_val->ptr++; /* Skip over '=' character */
  1995. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1996. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1997. }
  1998. }
  1999. }
  2000. return list;
  2001. }
  2002. /* A helper function for checking if a comma separated list of values contains
  2003. * the given option (case insensitvely).
  2004. * 'header' can be NULL, in which case false is returned. */
  2005. static int
  2006. header_has_option(const char *header, const char *option)
  2007. {
  2008. struct vec opt_vec;
  2009. struct vec eq_vec;
  2010. assert(option != NULL);
  2011. assert(option[0] != '\0');
  2012. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2013. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2014. return 1;
  2015. }
  2016. return 0;
  2017. }
  2018. /* Perform case-insensitive match of string against pattern */
  2019. static int
  2020. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2021. {
  2022. const char *or_str;
  2023. size_t i;
  2024. int j, len, res;
  2025. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2026. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2027. return (res > 0) ? res : match_prefix(or_str + 1,
  2028. (size_t)((pattern + pattern_len)
  2029. - (or_str + 1)),
  2030. str);
  2031. }
  2032. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2033. if (pattern[i] == '?' && str[j] != '\0') {
  2034. continue;
  2035. } else if (pattern[i] == '$') {
  2036. return (str[j] == '\0') ? j : -1;
  2037. } else if (pattern[i] == '*') {
  2038. i++;
  2039. if (pattern[i] == '*') {
  2040. i++;
  2041. len = (int)strlen(str + j);
  2042. } else {
  2043. len = (int)strcspn(str + j, "/");
  2044. }
  2045. if (i == pattern_len) {
  2046. return j + len;
  2047. }
  2048. do {
  2049. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2050. } while (res == -1 && len-- > 0);
  2051. return (res == -1) ? -1 : j + res + len;
  2052. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2053. return -1;
  2054. }
  2055. }
  2056. return j;
  2057. }
  2058. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2059. * This function must tolerate situations when connection info is not
  2060. * set up, for example if request parsing failed. */
  2061. static int
  2062. should_keep_alive(const struct mg_connection *conn)
  2063. {
  2064. if (conn != NULL) {
  2065. const char *http_version = conn->request_info.http_version;
  2066. const char *header = mg_get_header(conn, "Connection");
  2067. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2068. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2069. || (header != NULL && !header_has_option(header, "keep-alive"))
  2070. || (header == NULL && http_version
  2071. && 0 != strcmp(http_version, "1.1"))) {
  2072. return 0;
  2073. }
  2074. return 1;
  2075. }
  2076. return 0;
  2077. }
  2078. static int
  2079. should_decode_url(const struct mg_connection *conn)
  2080. {
  2081. if (!conn || !conn->ctx) {
  2082. return 0;
  2083. }
  2084. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2085. }
  2086. static const char *
  2087. suggest_connection_header(const struct mg_connection *conn)
  2088. {
  2089. return should_keep_alive(conn) ? "keep-alive" : "close";
  2090. }
  2091. static int
  2092. send_no_cache_header(struct mg_connection *conn)
  2093. {
  2094. /* Send all current and obsolete cache opt-out directives. */
  2095. return mg_printf(conn,
  2096. "Cache-Control: no-cache, no-store, "
  2097. "must-revalidate, private, max-age=0\r\n"
  2098. "Pragma: no-cache\r\n"
  2099. "Expires: 0\r\n");
  2100. }
  2101. static int
  2102. send_static_cache_header(struct mg_connection *conn)
  2103. {
  2104. #if !defined(NO_CACHING)
  2105. /* Read the server config to check how long a file may be cached.
  2106. * The configuration is in seconds. */
  2107. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2108. if (max_age <= 0) {
  2109. /* 0 means "do not cache". All values <0 are reserved
  2110. * and may be used differently in the future. */
  2111. /* If a file should not be cached, do not only send
  2112. * max-age=0, but also pragmas and Expires headers. */
  2113. return send_no_cache_header(conn);
  2114. }
  2115. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2116. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2117. /* See also https://www.mnot.net/cache_docs/ */
  2118. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2119. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2120. * year to 31622400 seconds. For the moment, we just send whatever has
  2121. * been configured, still the behavior for >1 year should be considered
  2122. * as undefined. */
  2123. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2124. #else /* NO_CACHING */
  2125. return send_no_cache_header(conn);
  2126. #endif /* !NO_CACHING */
  2127. }
  2128. static void handle_file_based_request(struct mg_connection *conn,
  2129. const char *path,
  2130. struct file *filep);
  2131. static int
  2132. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2133. const char *
  2134. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2135. {
  2136. /* See IANA HTTP status code assignment:
  2137. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2138. */
  2139. switch (response_code) {
  2140. /* RFC2616 Section 10.1 - Informational 1xx */
  2141. case 100:
  2142. return "Continue"; /* RFC2616 Section 10.1.1 */
  2143. case 101:
  2144. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2145. case 102:
  2146. return "Processing"; /* RFC2518 Section 10.1 */
  2147. /* RFC2616 Section 10.2 - Successful 2xx */
  2148. case 200:
  2149. return "OK"; /* RFC2616 Section 10.2.1 */
  2150. case 201:
  2151. return "Created"; /* RFC2616 Section 10.2.2 */
  2152. case 202:
  2153. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2154. case 203:
  2155. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2156. case 204:
  2157. return "No Content"; /* RFC2616 Section 10.2.5 */
  2158. case 205:
  2159. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2160. case 206:
  2161. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2162. case 207:
  2163. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2164. case 208:
  2165. return "Already Reported"; /* RFC5842 Section 7.1 */
  2166. case 226:
  2167. return "IM used"; /* RFC3229 Section 10.4.1 */
  2168. /* RFC2616 Section 10.3 - Redirection 3xx */
  2169. case 300:
  2170. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2171. case 301:
  2172. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2173. case 302:
  2174. return "Found"; /* RFC2616 Section 10.3.3 */
  2175. case 303:
  2176. return "See Other"; /* RFC2616 Section 10.3.4 */
  2177. case 304:
  2178. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2179. case 305:
  2180. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2181. case 307:
  2182. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2183. case 308:
  2184. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2185. /* RFC2616 Section 10.4 - Client Error 4xx */
  2186. case 400:
  2187. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2188. case 401:
  2189. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2190. case 402:
  2191. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2192. case 403:
  2193. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2194. case 404:
  2195. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2196. case 405:
  2197. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2198. case 406:
  2199. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2200. case 407:
  2201. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2202. case 408:
  2203. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2204. case 409:
  2205. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2206. case 410:
  2207. return "Gone"; /* RFC2616 Section 10.4.11 */
  2208. case 411:
  2209. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2210. case 412:
  2211. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2212. case 413:
  2213. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2214. case 414:
  2215. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2216. case 415:
  2217. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2218. case 416:
  2219. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2220. case 417:
  2221. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2222. case 421:
  2223. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2224. case 422:
  2225. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2226. * Section 11.2 */
  2227. case 423:
  2228. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2229. case 424:
  2230. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2231. * Section 11.4 */
  2232. case 426:
  2233. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2234. case 428:
  2235. return "Precondition Required"; /* RFC 6585, Section 3 */
  2236. case 429:
  2237. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2238. case 431:
  2239. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2240. case 451:
  2241. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2242. * Section 3 */
  2243. /* RFC2616 Section 10.5 - Server Error 5xx */
  2244. case 500:
  2245. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2246. case 501:
  2247. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2248. case 502:
  2249. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2250. case 503:
  2251. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2252. case 504:
  2253. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2254. case 505:
  2255. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2256. case 506:
  2257. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2258. case 507:
  2259. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2260. * Section 11.5 */
  2261. case 508:
  2262. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2263. case 510:
  2264. return "Not Extended"; /* RFC 2774, Section 7 */
  2265. case 511:
  2266. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2267. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2268. * E.g., "de facto" standards due to common use, ... */
  2269. case 418:
  2270. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2271. case 419:
  2272. return "Authentication Timeout"; /* common use */
  2273. case 420:
  2274. return "Enhance Your Calm"; /* common use */
  2275. case 440:
  2276. return "Login Timeout"; /* common use */
  2277. case 509:
  2278. return "Bandwidth Limit Exceeded"; /* common use */
  2279. default:
  2280. /* This error code is unknown. This should not happen. */
  2281. if (conn) {
  2282. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2283. }
  2284. /* Return at least a category according to RFC 2616 Section 10. */
  2285. if (response_code >= 100 && response_code < 200) {
  2286. /* Unknown informational status code */
  2287. return "Information";
  2288. }
  2289. if (response_code >= 200 && response_code < 300) {
  2290. /* Unknown success code */
  2291. return "Success";
  2292. }
  2293. if (response_code >= 300 && response_code < 400) {
  2294. /* Unknown redirection code */
  2295. return "Redirection";
  2296. }
  2297. if (response_code >= 400 && response_code < 500) {
  2298. /* Unknown request error code */
  2299. return "Client Error";
  2300. }
  2301. if (response_code >= 500 && response_code < 600) {
  2302. /* Unknown server error code */
  2303. return "Server Error";
  2304. }
  2305. /* Response code not even within reasonable range */
  2306. return "";
  2307. }
  2308. }
  2309. static void send_http_error(struct mg_connection *,
  2310. int,
  2311. PRINTF_FORMAT_STRING(const char *fmt),
  2312. ...) PRINTF_ARGS(3, 4);
  2313. static void
  2314. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2315. {
  2316. char buf[MG_BUF_LEN];
  2317. va_list ap;
  2318. int len, i, page_handler_found, scope, truncated;
  2319. char date[64];
  2320. time_t curtime = time(NULL);
  2321. const char *error_handler = NULL;
  2322. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2323. const char *error_page_file_ext, *tstr;
  2324. const char *status_text = mg_get_response_code_text(conn, status);
  2325. if (conn == NULL) {
  2326. return;
  2327. }
  2328. conn->status_code = status;
  2329. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2330. || conn->ctx->callbacks.http_error(conn, status)) {
  2331. if (!conn->in_error_handler) {
  2332. /* Send user defined error pages, if defined */
  2333. error_handler = conn->ctx->config[ERROR_PAGES];
  2334. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2335. page_handler_found = 0;
  2336. if (error_handler != NULL) {
  2337. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2338. switch (scope) {
  2339. case 1: /* Handler for specific error, e.g. 404 error */
  2340. mg_snprintf(conn,
  2341. &truncated,
  2342. buf,
  2343. sizeof(buf) - 32,
  2344. "%serror%03u.",
  2345. error_handler,
  2346. status);
  2347. break;
  2348. case 2: /* Handler for error group, e.g., 5xx error handler
  2349. * for all server errors (500-599) */
  2350. mg_snprintf(conn,
  2351. &truncated,
  2352. buf,
  2353. sizeof(buf) - 32,
  2354. "%serror%01uxx.",
  2355. error_handler,
  2356. status / 100);
  2357. break;
  2358. default: /* Handler for all errors */
  2359. mg_snprintf(conn,
  2360. &truncated,
  2361. buf,
  2362. sizeof(buf) - 32,
  2363. "%serror.",
  2364. error_handler);
  2365. break;
  2366. }
  2367. /* String truncation in buf may only occur if error_handler
  2368. * is too long. This string is from the config, not from a
  2369. * client. */
  2370. (void)truncated;
  2371. len = (int)strlen(buf);
  2372. tstr = strchr(error_page_file_ext, '.');
  2373. while (tstr) {
  2374. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2375. i++)
  2376. buf[len + i - 1] = tstr[i];
  2377. buf[len + i - 1] = 0;
  2378. if (mg_stat(conn, buf, &error_page_file)) {
  2379. page_handler_found = 1;
  2380. break;
  2381. }
  2382. tstr = strchr(tstr + i, '.');
  2383. }
  2384. }
  2385. }
  2386. if (page_handler_found) {
  2387. conn->in_error_handler = 1;
  2388. handle_file_based_request(conn, buf, &error_page_file);
  2389. conn->in_error_handler = 0;
  2390. return;
  2391. }
  2392. }
  2393. /* No custom error page. Send default error page. */
  2394. gmt_time_string(date, sizeof(date), &curtime);
  2395. conn->must_close = 1;
  2396. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2397. send_no_cache_header(conn);
  2398. mg_printf(conn,
  2399. "Date: %s\r\n"
  2400. "Connection: close\r\n\r\n",
  2401. date);
  2402. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2403. if (status > 199 && status != 204 && status != 304) {
  2404. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2405. if (fmt != NULL) {
  2406. va_start(ap, fmt);
  2407. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2408. va_end(ap);
  2409. mg_write(conn, buf, strlen(buf));
  2410. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2411. }
  2412. } else {
  2413. /* No body allowed. Close the connection. */
  2414. DEBUG_TRACE("Error %i", status);
  2415. }
  2416. }
  2417. }
  2418. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2419. /* Create substitutes for POSIX functions in Win32. */
  2420. #if defined(__MINGW32__)
  2421. /* Show no warning in case system functions are not used. */
  2422. #pragma GCC diagnostic push
  2423. #pragma GCC diagnostic ignored "-Wunused-function"
  2424. #endif
  2425. static int
  2426. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2427. {
  2428. (void)unused;
  2429. *mutex = CreateMutex(NULL, FALSE, NULL);
  2430. return (*mutex == NULL) ? -1 : 0;
  2431. }
  2432. static int
  2433. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2434. {
  2435. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2436. }
  2437. static int
  2438. pthread_mutex_lock(pthread_mutex_t *mutex)
  2439. {
  2440. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2441. }
  2442. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2443. static int
  2444. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2445. {
  2446. switch (WaitForSingleObject(*mutex, 0)) {
  2447. case WAIT_OBJECT_0:
  2448. return 0;
  2449. case WAIT_TIMEOUT:
  2450. return -2; /* EBUSY */
  2451. }
  2452. return -1;
  2453. }
  2454. #endif
  2455. static int
  2456. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2457. {
  2458. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2459. }
  2460. #ifndef WIN_PTHREADS_TIME_H
  2461. static int
  2462. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2463. {
  2464. FILETIME ft;
  2465. ULARGE_INTEGER li;
  2466. BOOL ok = FALSE;
  2467. double d;
  2468. static double perfcnt_per_sec = 0.0;
  2469. if (tp) {
  2470. memset(tp, 0, sizeof(*tp));
  2471. if (clk_id == CLOCK_REALTIME) {
  2472. GetSystemTimeAsFileTime(&ft);
  2473. li.LowPart = ft.dwLowDateTime;
  2474. li.HighPart = ft.dwHighDateTime;
  2475. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2476. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2477. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2478. ok = TRUE;
  2479. } else if (clk_id == CLOCK_MONOTONIC) {
  2480. if (perfcnt_per_sec == 0.0) {
  2481. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2482. perfcnt_per_sec = 1.0 / li.QuadPart;
  2483. }
  2484. if (perfcnt_per_sec != 0.0) {
  2485. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2486. d = li.QuadPart * perfcnt_per_sec;
  2487. tp->tv_sec = (time_t)d;
  2488. d -= tp->tv_sec;
  2489. tp->tv_nsec = (long)(d * 1.0E9);
  2490. ok = TRUE;
  2491. }
  2492. }
  2493. }
  2494. return ok ? 0 : -1;
  2495. }
  2496. #endif
  2497. static int
  2498. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2499. {
  2500. (void)unused;
  2501. InitializeCriticalSection(&cv->threadIdSec);
  2502. cv->waiting_thread = NULL;
  2503. return 0;
  2504. }
  2505. static int
  2506. pthread_cond_timedwait(pthread_cond_t *cv,
  2507. pthread_mutex_t *mutex,
  2508. const struct timespec *abstime)
  2509. {
  2510. struct mg_workerTLS **ptls,
  2511. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2512. int ok;
  2513. struct timespec tsnow;
  2514. int64_t nsnow, nswaitabs, nswaitrel;
  2515. DWORD mswaitrel;
  2516. EnterCriticalSection(&cv->threadIdSec);
  2517. /* Add this thread to cv's waiting list */
  2518. ptls = &cv->waiting_thread;
  2519. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2520. ;
  2521. tls->next_waiting_thread = NULL;
  2522. *ptls = tls;
  2523. LeaveCriticalSection(&cv->threadIdSec);
  2524. if (abstime) {
  2525. clock_gettime(CLOCK_REALTIME, &tsnow);
  2526. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2527. nswaitabs =
  2528. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2529. nswaitrel = nswaitabs - nsnow;
  2530. if (nswaitrel < 0) {
  2531. nswaitrel = 0;
  2532. }
  2533. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2534. } else {
  2535. mswaitrel = INFINITE;
  2536. }
  2537. pthread_mutex_unlock(mutex);
  2538. ok = (WAIT_OBJECT_0
  2539. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2540. if (!ok) {
  2541. ok = 1;
  2542. EnterCriticalSection(&cv->threadIdSec);
  2543. ptls = &cv->waiting_thread;
  2544. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2545. if (*ptls == tls) {
  2546. *ptls = tls->next_waiting_thread;
  2547. ok = 0;
  2548. break;
  2549. }
  2550. }
  2551. LeaveCriticalSection(&cv->threadIdSec);
  2552. if (ok) {
  2553. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2554. }
  2555. }
  2556. /* This thread has been removed from cv's waiting list */
  2557. pthread_mutex_lock(mutex);
  2558. return ok ? 0 : -1;
  2559. }
  2560. static int
  2561. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2562. {
  2563. return pthread_cond_timedwait(cv, mutex, NULL);
  2564. }
  2565. static int
  2566. pthread_cond_signal(pthread_cond_t *cv)
  2567. {
  2568. HANDLE wkup = NULL;
  2569. BOOL ok = FALSE;
  2570. EnterCriticalSection(&cv->threadIdSec);
  2571. if (cv->waiting_thread) {
  2572. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2573. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2574. ok = SetEvent(wkup);
  2575. assert(ok);
  2576. }
  2577. LeaveCriticalSection(&cv->threadIdSec);
  2578. return ok ? 0 : 1;
  2579. }
  2580. static int
  2581. pthread_cond_broadcast(pthread_cond_t *cv)
  2582. {
  2583. EnterCriticalSection(&cv->threadIdSec);
  2584. while (cv->waiting_thread) {
  2585. pthread_cond_signal(cv);
  2586. }
  2587. LeaveCriticalSection(&cv->threadIdSec);
  2588. return 0;
  2589. }
  2590. static int
  2591. pthread_cond_destroy(pthread_cond_t *cv)
  2592. {
  2593. EnterCriticalSection(&cv->threadIdSec);
  2594. assert(cv->waiting_thread == NULL);
  2595. LeaveCriticalSection(&cv->threadIdSec);
  2596. DeleteCriticalSection(&cv->threadIdSec);
  2597. return 0;
  2598. }
  2599. #ifdef ALTERNATIVE_QUEUE
  2600. static int
  2601. event_create(void)
  2602. {
  2603. return (int)CreateEvent(NULL, FALSE, FALSE, NULL);
  2604. }
  2605. static int
  2606. event_wait(int eventhdl)
  2607. {
  2608. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2609. return (res == WAIT_OBJECT_0);
  2610. }
  2611. static int
  2612. event_signal(int eventhdl)
  2613. {
  2614. return (int)SetEvent((HANDLE)eventhdl);
  2615. }
  2616. static void
  2617. event_destroy(int eventhdl)
  2618. {
  2619. CloseHandle((HANDLE)eventhdl);
  2620. }
  2621. #endif
  2622. #if defined(__MINGW32__)
  2623. /* Enable unused function warning again */
  2624. #pragma GCC diagnostic pop
  2625. #endif
  2626. /* For Windows, change all slashes to backslashes in path names. */
  2627. static void
  2628. change_slashes_to_backslashes(char *path)
  2629. {
  2630. int i;
  2631. for (i = 0; path[i] != '\0'; i++) {
  2632. if (path[i] == '/') {
  2633. path[i] = '\\';
  2634. }
  2635. /* remove double backslash (check i > 0 to preserve UNC paths,
  2636. * like \\server\file.txt) */
  2637. if ((path[i] == '\\') && (i > 0)) {
  2638. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2639. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2640. }
  2641. }
  2642. }
  2643. }
  2644. static int
  2645. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2646. {
  2647. int diff;
  2648. do {
  2649. diff = tolower(*s1) - tolower(*s2);
  2650. s1++;
  2651. s2++;
  2652. } while (diff == 0 && s1[-1] != '\0');
  2653. return diff;
  2654. }
  2655. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2656. * wbuf and wbuf_len is a target buffer and its length. */
  2657. static void
  2658. path_to_unicode(const struct mg_connection *conn,
  2659. const char *path,
  2660. wchar_t *wbuf,
  2661. size_t wbuf_len)
  2662. {
  2663. char buf[PATH_MAX], buf2[PATH_MAX];
  2664. wchar_t wbuf2[MAX_PATH + 1];
  2665. DWORD long_len, err;
  2666. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2667. mg_strlcpy(buf, path, sizeof(buf));
  2668. change_slashes_to_backslashes(buf);
  2669. /* Convert to Unicode and back. If doubly-converted string does not
  2670. * match the original, something is fishy, reject. */
  2671. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2672. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2673. WideCharToMultiByte(
  2674. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2675. if (strcmp(buf, buf2) != 0) {
  2676. wbuf[0] = L'\0';
  2677. }
  2678. /* TODO: Add a configuration to switch between case sensitive and
  2679. * case insensitive URIs for Windows server. */
  2680. /*
  2681. if (conn) {
  2682. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2683. fcompare = wcscmp;
  2684. }
  2685. }
  2686. */
  2687. (void)conn; /* conn is currently unused */
  2688. #if !defined(_WIN32_WCE)
  2689. /* Only accept a full file path, not a Windows short (8.3) path. */
  2690. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2691. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2692. if (long_len == 0) {
  2693. err = GetLastError();
  2694. if (err == ERROR_FILE_NOT_FOUND) {
  2695. /* File does not exist. This is not always a problem here. */
  2696. return;
  2697. }
  2698. }
  2699. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2700. /* Short name is used. */
  2701. wbuf[0] = L'\0';
  2702. }
  2703. #else
  2704. (void)long_len;
  2705. (void)wbuf2;
  2706. (void)err;
  2707. if (strchr(path, '~')) {
  2708. wbuf[0] = L'\0';
  2709. }
  2710. #endif
  2711. }
  2712. /* Windows happily opens files with some garbage at the end of file name.
  2713. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2714. * "a.cgi", despite one would expect an error back.
  2715. * This function returns non-0 if path ends with some garbage. */
  2716. static int
  2717. path_cannot_disclose_cgi(const char *path)
  2718. {
  2719. static const char *allowed_last_characters = "_-";
  2720. int last = path[strlen(path) - 1];
  2721. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2722. }
  2723. static int
  2724. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2725. {
  2726. wchar_t wbuf[PATH_MAX];
  2727. WIN32_FILE_ATTRIBUTE_DATA info;
  2728. time_t creation_time;
  2729. if (!filep) {
  2730. return 0;
  2731. }
  2732. memset(filep, 0, sizeof(*filep));
  2733. if (conn && is_file_in_memory(conn, path, filep)) {
  2734. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2735. * memset */
  2736. filep->last_modified = time(NULL);
  2737. /* last_modified = now ... assumes the file may change during runtime,
  2738. * so every mg_fopen call may return different data */
  2739. /* last_modified = conn->ctx.start_time;
  2740. * May be used it the data does not change during runtime. This allows
  2741. * browser caching. Since we do not know, we have to assume the file
  2742. * in memory may change. */
  2743. return 1;
  2744. }
  2745. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2746. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2747. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2748. filep->last_modified =
  2749. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2750. info.ftLastWriteTime.dwHighDateTime);
  2751. /* On Windows, the file creation time can be higher than the
  2752. * modification time, e.g. when a file is copied.
  2753. * Since the Last-Modified timestamp is used for caching
  2754. * it should be based on the most recent timestamp. */
  2755. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2756. info.ftCreationTime.dwHighDateTime);
  2757. if (creation_time > filep->last_modified) {
  2758. filep->last_modified = creation_time;
  2759. }
  2760. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2761. /* If file name is fishy, reset the file structure and return
  2762. * error.
  2763. * Note it is important to reset, not just return the error, cause
  2764. * functions like is_file_opened() check the struct. */
  2765. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2766. memset(filep, 0, sizeof(*filep));
  2767. return 0;
  2768. }
  2769. return 1;
  2770. }
  2771. return 0;
  2772. }
  2773. static int
  2774. mg_remove(const struct mg_connection *conn, const char *path)
  2775. {
  2776. wchar_t wbuf[PATH_MAX];
  2777. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2778. return DeleteFileW(wbuf) ? 0 : -1;
  2779. }
  2780. static int
  2781. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2782. {
  2783. wchar_t wbuf[PATH_MAX];
  2784. (void)mode;
  2785. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2786. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2787. }
  2788. /* Create substitutes for POSIX functions in Win32. */
  2789. #if defined(__MINGW32__)
  2790. /* Show no warning in case system functions are not used. */
  2791. #pragma GCC diagnostic push
  2792. #pragma GCC diagnostic ignored "-Wunused-function"
  2793. #endif
  2794. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2795. static DIR *
  2796. mg_opendir(const struct mg_connection *conn, const char *name)
  2797. {
  2798. DIR *dir = NULL;
  2799. wchar_t wpath[PATH_MAX];
  2800. DWORD attrs;
  2801. if (name == NULL) {
  2802. SetLastError(ERROR_BAD_ARGUMENTS);
  2803. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2804. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2805. } else {
  2806. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2807. attrs = GetFileAttributesW(wpath);
  2808. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2809. == FILE_ATTRIBUTE_DIRECTORY)) {
  2810. (void)wcscat(wpath, L"\\*");
  2811. dir->handle = FindFirstFileW(wpath, &dir->info);
  2812. dir->result.d_name[0] = '\0';
  2813. } else {
  2814. mg_free(dir);
  2815. dir = NULL;
  2816. }
  2817. }
  2818. return dir;
  2819. }
  2820. static int
  2821. mg_closedir(DIR *dir)
  2822. {
  2823. int result = 0;
  2824. if (dir != NULL) {
  2825. if (dir->handle != INVALID_HANDLE_VALUE)
  2826. result = FindClose(dir->handle) ? 0 : -1;
  2827. mg_free(dir);
  2828. } else {
  2829. result = -1;
  2830. SetLastError(ERROR_BAD_ARGUMENTS);
  2831. }
  2832. return result;
  2833. }
  2834. static struct dirent *
  2835. mg_readdir(DIR *dir)
  2836. {
  2837. struct dirent *result = 0;
  2838. if (dir) {
  2839. if (dir->handle != INVALID_HANDLE_VALUE) {
  2840. result = &dir->result;
  2841. (void)WideCharToMultiByte(CP_UTF8,
  2842. 0,
  2843. dir->info.cFileName,
  2844. -1,
  2845. result->d_name,
  2846. sizeof(result->d_name),
  2847. NULL,
  2848. NULL);
  2849. if (!FindNextFileW(dir->handle, &dir->info)) {
  2850. (void)FindClose(dir->handle);
  2851. dir->handle = INVALID_HANDLE_VALUE;
  2852. }
  2853. } else {
  2854. SetLastError(ERROR_FILE_NOT_FOUND);
  2855. }
  2856. } else {
  2857. SetLastError(ERROR_BAD_ARGUMENTS);
  2858. }
  2859. return result;
  2860. }
  2861. #ifndef HAVE_POLL
  2862. static int
  2863. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2864. {
  2865. struct timeval tv;
  2866. fd_set set;
  2867. unsigned int i;
  2868. int result;
  2869. SOCKET maxfd = 0;
  2870. memset(&tv, 0, sizeof(tv));
  2871. tv.tv_sec = milliseconds / 1000;
  2872. tv.tv_usec = (milliseconds % 1000) * 1000;
  2873. FD_ZERO(&set);
  2874. for (i = 0; i < n; i++) {
  2875. FD_SET((SOCKET)pfd[i].fd, &set);
  2876. pfd[i].revents = 0;
  2877. if (pfd[i].fd > maxfd) {
  2878. maxfd = pfd[i].fd;
  2879. }
  2880. }
  2881. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2882. for (i = 0; i < n; i++) {
  2883. if (FD_ISSET(pfd[i].fd, &set)) {
  2884. pfd[i].revents = POLLIN;
  2885. }
  2886. }
  2887. }
  2888. return result;
  2889. }
  2890. #endif /* HAVE_POLL */
  2891. #if defined(__MINGW32__)
  2892. /* Enable unused function warning again */
  2893. #pragma GCC diagnostic pop
  2894. #endif
  2895. static void
  2896. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2897. {
  2898. (void)conn; /* Unused. */
  2899. #if defined(_WIN32_WCE)
  2900. (void)sock;
  2901. #else
  2902. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2903. #endif
  2904. }
  2905. int
  2906. mg_start_thread(mg_thread_func_t f, void *p)
  2907. {
  2908. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2909. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2910. */
  2911. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2912. == ((uintptr_t)(-1L)))
  2913. ? -1
  2914. : 0);
  2915. #else
  2916. return (
  2917. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2918. ? -1
  2919. : 0);
  2920. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2921. }
  2922. /* Start a thread storing the thread context. */
  2923. static int
  2924. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2925. void *p,
  2926. pthread_t *threadidptr)
  2927. {
  2928. uintptr_t uip;
  2929. HANDLE threadhandle;
  2930. int result = -1;
  2931. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2932. threadhandle = (HANDLE)uip;
  2933. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2934. *threadidptr = threadhandle;
  2935. result = 0;
  2936. }
  2937. return result;
  2938. }
  2939. /* Wait for a thread to finish. */
  2940. static int
  2941. mg_join_thread(pthread_t threadid)
  2942. {
  2943. int result;
  2944. DWORD dwevent;
  2945. result = -1;
  2946. dwevent = WaitForSingleObject(threadid, INFINITE);
  2947. if (dwevent == WAIT_FAILED) {
  2948. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2949. } else {
  2950. if (dwevent == WAIT_OBJECT_0) {
  2951. CloseHandle(threadid);
  2952. result = 0;
  2953. }
  2954. }
  2955. return result;
  2956. }
  2957. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  2958. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  2959. /* Create substitutes for POSIX functions in Win32. */
  2960. #if defined(__MINGW32__)
  2961. /* Show no warning in case system functions are not used. */
  2962. #pragma GCC diagnostic push
  2963. #pragma GCC diagnostic ignored "-Wunused-function"
  2964. #endif
  2965. static HANDLE
  2966. dlopen(const char *dll_name, int flags)
  2967. {
  2968. wchar_t wbuf[PATH_MAX];
  2969. (void)flags;
  2970. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  2971. return LoadLibraryW(wbuf);
  2972. }
  2973. static int
  2974. dlclose(void *handle)
  2975. {
  2976. int result;
  2977. if (FreeLibrary((HMODULE)handle) != 0) {
  2978. result = 0;
  2979. } else {
  2980. result = -1;
  2981. }
  2982. return result;
  2983. }
  2984. #if defined(__MINGW32__)
  2985. /* Enable unused function warning again */
  2986. #pragma GCC diagnostic pop
  2987. #endif
  2988. #endif
  2989. #if !defined(NO_CGI)
  2990. #define SIGKILL (0)
  2991. static int
  2992. kill(pid_t pid, int sig_num)
  2993. {
  2994. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2995. (void)CloseHandle((HANDLE)pid);
  2996. return 0;
  2997. }
  2998. static void
  2999. trim_trailing_whitespaces(char *s)
  3000. {
  3001. char *e = s + strlen(s) - 1;
  3002. while (e > s && isspace(*(unsigned char *)e)) {
  3003. *e-- = '\0';
  3004. }
  3005. }
  3006. static pid_t
  3007. spawn_process(struct mg_connection *conn,
  3008. const char *prog,
  3009. char *envblk,
  3010. char *envp[],
  3011. int fdin[2],
  3012. int fdout[2],
  3013. int fderr[2],
  3014. const char *dir)
  3015. {
  3016. HANDLE me;
  3017. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3018. cmdline[PATH_MAX], buf[PATH_MAX];
  3019. int truncated;
  3020. struct file file = STRUCT_FILE_INITIALIZER;
  3021. STARTUPINFOA si;
  3022. PROCESS_INFORMATION pi = {0};
  3023. (void)envp;
  3024. memset(&si, 0, sizeof(si));
  3025. si.cb = sizeof(si);
  3026. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3027. si.wShowWindow = SW_HIDE;
  3028. me = GetCurrentProcess();
  3029. DuplicateHandle(me,
  3030. (HANDLE)_get_osfhandle(fdin[0]),
  3031. me,
  3032. &si.hStdInput,
  3033. 0,
  3034. TRUE,
  3035. DUPLICATE_SAME_ACCESS);
  3036. DuplicateHandle(me,
  3037. (HANDLE)_get_osfhandle(fdout[1]),
  3038. me,
  3039. &si.hStdOutput,
  3040. 0,
  3041. TRUE,
  3042. DUPLICATE_SAME_ACCESS);
  3043. DuplicateHandle(me,
  3044. (HANDLE)_get_osfhandle(fderr[1]),
  3045. me,
  3046. &si.hStdError,
  3047. 0,
  3048. TRUE,
  3049. DUPLICATE_SAME_ACCESS);
  3050. /* Mark handles that should not be inherited. See
  3051. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3052. */
  3053. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3054. HANDLE_FLAG_INHERIT,
  3055. 0);
  3056. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3057. HANDLE_FLAG_INHERIT,
  3058. 0);
  3059. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3060. HANDLE_FLAG_INHERIT,
  3061. 0);
  3062. /* If CGI file is a script, try to read the interpreter line */
  3063. interp = conn->ctx->config[CGI_INTERPRETER];
  3064. if (interp == NULL) {
  3065. buf[0] = buf[1] = '\0';
  3066. /* Read the first line of the script into the buffer */
  3067. mg_snprintf(
  3068. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3069. if (truncated) {
  3070. pi.hProcess = (pid_t)-1;
  3071. goto spawn_cleanup;
  3072. }
  3073. if (mg_fopen(conn, cmdline, "r", &file)) {
  3074. p = (char *)file.membuf;
  3075. mg_fgets(buf, sizeof(buf), &file, &p);
  3076. mg_fclose(&file);
  3077. buf[sizeof(buf) - 1] = '\0';
  3078. }
  3079. if (buf[0] == '#' && buf[1] == '!') {
  3080. trim_trailing_whitespaces(buf + 2);
  3081. } else {
  3082. buf[2] = '\0';
  3083. }
  3084. interp = buf + 2;
  3085. }
  3086. if (interp[0] != '\0') {
  3087. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3088. interp = full_interp;
  3089. }
  3090. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3091. if (interp[0] != '\0') {
  3092. mg_snprintf(conn,
  3093. &truncated,
  3094. cmdline,
  3095. sizeof(cmdline),
  3096. "\"%s\" \"%s\\%s\"",
  3097. interp,
  3098. full_dir,
  3099. prog);
  3100. } else {
  3101. mg_snprintf(conn,
  3102. &truncated,
  3103. cmdline,
  3104. sizeof(cmdline),
  3105. "\"%s\\%s\"",
  3106. full_dir,
  3107. prog);
  3108. }
  3109. if (truncated) {
  3110. pi.hProcess = (pid_t)-1;
  3111. goto spawn_cleanup;
  3112. }
  3113. DEBUG_TRACE("Running [%s]", cmdline);
  3114. if (CreateProcessA(NULL,
  3115. cmdline,
  3116. NULL,
  3117. NULL,
  3118. TRUE,
  3119. CREATE_NEW_PROCESS_GROUP,
  3120. envblk,
  3121. NULL,
  3122. &si,
  3123. &pi) == 0) {
  3124. mg_cry(
  3125. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3126. pi.hProcess = (pid_t)-1;
  3127. /* goto spawn_cleanup; */
  3128. }
  3129. spawn_cleanup:
  3130. (void)CloseHandle(si.hStdOutput);
  3131. (void)CloseHandle(si.hStdError);
  3132. (void)CloseHandle(si.hStdInput);
  3133. if (pi.hThread != NULL) {
  3134. (void)CloseHandle(pi.hThread);
  3135. }
  3136. return (pid_t)pi.hProcess;
  3137. }
  3138. #endif /* !NO_CGI */
  3139. static int
  3140. set_non_blocking_mode(SOCKET sock)
  3141. {
  3142. unsigned long on = 1;
  3143. return ioctlsocket(sock, (long)FIONBIO, &on);
  3144. }
  3145. #else
  3146. static int
  3147. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3148. {
  3149. struct stat st;
  3150. if (!filep) {
  3151. return 0;
  3152. }
  3153. memset(filep, 0, sizeof(*filep));
  3154. if (conn && is_file_in_memory(conn, path, filep)) {
  3155. return 1;
  3156. }
  3157. if (0 == stat(path, &st)) {
  3158. filep->size = (uint64_t)(st.st_size);
  3159. filep->last_modified = st.st_mtime;
  3160. filep->is_directory = S_ISDIR(st.st_mode);
  3161. return 1;
  3162. }
  3163. return 0;
  3164. }
  3165. static void
  3166. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3167. {
  3168. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3169. if (conn) {
  3170. mg_cry(conn,
  3171. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3172. __func__,
  3173. strerror(ERRNO));
  3174. }
  3175. }
  3176. }
  3177. int
  3178. mg_start_thread(mg_thread_func_t func, void *param)
  3179. {
  3180. pthread_t thread_id;
  3181. pthread_attr_t attr;
  3182. int result;
  3183. (void)pthread_attr_init(&attr);
  3184. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3185. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3186. /* Compile-time option to control stack size,
  3187. * e.g. -DUSE_STACK_SIZE=16384 */
  3188. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3189. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3190. result = pthread_create(&thread_id, &attr, func, param);
  3191. pthread_attr_destroy(&attr);
  3192. return result;
  3193. }
  3194. /* Start a thread storing the thread context. */
  3195. static int
  3196. mg_start_thread_with_id(mg_thread_func_t func,
  3197. void *param,
  3198. pthread_t *threadidptr)
  3199. {
  3200. pthread_t thread_id;
  3201. pthread_attr_t attr;
  3202. int result;
  3203. (void)pthread_attr_init(&attr);
  3204. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3205. /* Compile-time option to control stack size,
  3206. * e.g. -DUSE_STACK_SIZE=16384 */
  3207. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3208. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3209. result = pthread_create(&thread_id, &attr, func, param);
  3210. pthread_attr_destroy(&attr);
  3211. if ((result == 0) && (threadidptr != NULL)) {
  3212. *threadidptr = thread_id;
  3213. }
  3214. return result;
  3215. }
  3216. /* Wait for a thread to finish. */
  3217. static int
  3218. mg_join_thread(pthread_t threadid)
  3219. {
  3220. int result;
  3221. result = pthread_join(threadid, NULL);
  3222. return result;
  3223. }
  3224. #ifndef NO_CGI
  3225. static pid_t
  3226. spawn_process(struct mg_connection *conn,
  3227. const char *prog,
  3228. char *envblk,
  3229. char *envp[],
  3230. int fdin[2],
  3231. int fdout[2],
  3232. int fderr[2],
  3233. const char *dir)
  3234. {
  3235. pid_t pid;
  3236. const char *interp;
  3237. (void)envblk;
  3238. if (conn == NULL) {
  3239. return 0;
  3240. }
  3241. if ((pid = fork()) == -1) {
  3242. /* Parent */
  3243. send_http_error(conn,
  3244. 500,
  3245. "Error: Creating CGI process\nfork(): %s",
  3246. strerror(ERRNO));
  3247. } else if (pid == 0) {
  3248. /* Child */
  3249. if (chdir(dir) != 0) {
  3250. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3251. } else if (dup2(fdin[0], 0) == -1) {
  3252. mg_cry(conn,
  3253. "%s: dup2(%d, 0): %s",
  3254. __func__,
  3255. fdin[0],
  3256. strerror(ERRNO));
  3257. } else if (dup2(fdout[1], 1) == -1) {
  3258. mg_cry(conn,
  3259. "%s: dup2(%d, 1): %s",
  3260. __func__,
  3261. fdout[1],
  3262. strerror(ERRNO));
  3263. } else if (dup2(fderr[1], 2) == -1) {
  3264. mg_cry(conn,
  3265. "%s: dup2(%d, 2): %s",
  3266. __func__,
  3267. fderr[1],
  3268. strerror(ERRNO));
  3269. } else {
  3270. /* Keep stderr and stdout in two different pipes.
  3271. * Stdout will be sent back to the client,
  3272. * stderr should go into a server error log. */
  3273. (void)close(fdin[0]);
  3274. (void)close(fdout[1]);
  3275. (void)close(fderr[1]);
  3276. /* Close write end fdin and read end fdout and fderr */
  3277. (void)close(fdin[1]);
  3278. (void)close(fdout[0]);
  3279. (void)close(fderr[0]);
  3280. /* After exec, all signal handlers are restored to their default
  3281. * values, with one exception of SIGCHLD. According to
  3282. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3283. * leave unchanged after exec if it was set to be ignored. Restore
  3284. * it to default action. */
  3285. signal(SIGCHLD, SIG_DFL);
  3286. interp = conn->ctx->config[CGI_INTERPRETER];
  3287. if (interp == NULL) {
  3288. (void)execle(prog, prog, NULL, envp);
  3289. mg_cry(conn,
  3290. "%s: execle(%s): %s",
  3291. __func__,
  3292. prog,
  3293. strerror(ERRNO));
  3294. } else {
  3295. (void)execle(interp, interp, prog, NULL, envp);
  3296. mg_cry(conn,
  3297. "%s: execle(%s %s): %s",
  3298. __func__,
  3299. interp,
  3300. prog,
  3301. strerror(ERRNO));
  3302. }
  3303. }
  3304. exit(EXIT_FAILURE);
  3305. }
  3306. return pid;
  3307. }
  3308. #endif /* !NO_CGI */
  3309. static int
  3310. set_non_blocking_mode(SOCKET sock)
  3311. {
  3312. int flags;
  3313. flags = fcntl(sock, F_GETFL, 0);
  3314. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3315. return 0;
  3316. }
  3317. #endif /* _WIN32 */
  3318. /* End of initial operating system specific define block. */
  3319. /* Get a random number (independent of C rand function) */
  3320. static uint64_t
  3321. get_random(void)
  3322. {
  3323. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3324. static uint64_t lcg = 0; /* Linear congruential generator */
  3325. struct timespec now;
  3326. memset(&now, 0, sizeof(now));
  3327. clock_gettime(CLOCK_MONOTONIC, &now);
  3328. if (lfsr == 0) {
  3329. /* lfsr will be only 0 if has not been initialized,
  3330. * so this code is called only once. */
  3331. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3332. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3333. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3334. + (uint64_t)(ptrdiff_t)&now;
  3335. } else {
  3336. /* Get the next step of both random number generators. */
  3337. lfsr = (lfsr >> 1)
  3338. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3339. << 63);
  3340. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3341. }
  3342. /* Combining two pseudo-random number generators and a high resolution part
  3343. * of the current server time will make it hard (impossible?) to guess the
  3344. * next number. */
  3345. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3346. }
  3347. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3348. * descriptor. Return number of bytes written. */
  3349. static int
  3350. push(struct mg_context *ctx,
  3351. FILE *fp,
  3352. SOCKET sock,
  3353. SSL *ssl,
  3354. const char *buf,
  3355. int len,
  3356. double timeout)
  3357. {
  3358. struct timespec start, now;
  3359. int n, err;
  3360. #ifdef _WIN32
  3361. typedef int len_t;
  3362. #else
  3363. typedef size_t len_t;
  3364. #endif
  3365. if (timeout > 0) {
  3366. memset(&start, 0, sizeof(start));
  3367. memset(&now, 0, sizeof(now));
  3368. clock_gettime(CLOCK_MONOTONIC, &start);
  3369. }
  3370. if (ctx == NULL) {
  3371. return -1;
  3372. }
  3373. #ifdef NO_SSL
  3374. if (ssl) {
  3375. return -1;
  3376. }
  3377. #endif
  3378. do {
  3379. #ifndef NO_SSL
  3380. if (ssl != NULL) {
  3381. n = SSL_write(ssl, buf, len);
  3382. if (n <= 0) {
  3383. err = SSL_get_error(ssl, n);
  3384. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3385. err = ERRNO;
  3386. } else if ((err == SSL_ERROR_WANT_READ)
  3387. || (err == SSL_ERROR_WANT_WRITE)) {
  3388. n = 0;
  3389. } else {
  3390. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3391. return -1;
  3392. }
  3393. } else {
  3394. err = 0;
  3395. }
  3396. } else
  3397. #endif
  3398. if (fp != NULL) {
  3399. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3400. if (ferror(fp)) {
  3401. n = -1;
  3402. err = ERRNO;
  3403. } else {
  3404. err = 0;
  3405. }
  3406. } else {
  3407. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3408. err = (n < 0) ? ERRNO : 0;
  3409. if (n == 0) {
  3410. /* shutdown of the socket at client side */
  3411. return -1;
  3412. }
  3413. }
  3414. if (ctx->stop_flag) {
  3415. return -1;
  3416. }
  3417. if ((n > 0) || (n == 0 && len == 0)) {
  3418. /* some data has been read, or no data was requested */
  3419. return n;
  3420. }
  3421. if (n < 0) {
  3422. /* socket error - check errno */
  3423. DEBUG_TRACE("send() failed, error %d", err);
  3424. /* TODO: error handling depending on the error code.
  3425. * These codes are different between Windows and Linux.
  3426. */
  3427. return -1;
  3428. }
  3429. /* This code is not reached in the moment.
  3430. * ==> Fix the TODOs above first. */
  3431. if (timeout > 0) {
  3432. clock_gettime(CLOCK_MONOTONIC, &now);
  3433. }
  3434. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3435. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3436. used */
  3437. return -1;
  3438. }
  3439. static int64_t
  3440. push_all(struct mg_context *ctx,
  3441. FILE *fp,
  3442. SOCKET sock,
  3443. SSL *ssl,
  3444. const char *buf,
  3445. int64_t len)
  3446. {
  3447. double timeout = -1.0;
  3448. int64_t n, nwritten = 0;
  3449. if (ctx == NULL) {
  3450. return -1;
  3451. }
  3452. if (ctx->config[REQUEST_TIMEOUT]) {
  3453. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3454. }
  3455. while (len > 0 && ctx->stop_flag == 0) {
  3456. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3457. if (n < 0) {
  3458. if (nwritten == 0) {
  3459. nwritten = n; /* Propagate the error */
  3460. }
  3461. break;
  3462. } else if (n == 0) {
  3463. break; /* No more data to write */
  3464. } else {
  3465. nwritten += n;
  3466. len -= n;
  3467. }
  3468. }
  3469. return nwritten;
  3470. }
  3471. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3472. * Return negative value on error, or number of bytes read on success. */
  3473. static int
  3474. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3475. {
  3476. int nread, err;
  3477. struct timespec start, now;
  3478. #ifdef _WIN32
  3479. typedef int len_t;
  3480. #else
  3481. typedef size_t len_t;
  3482. #endif
  3483. if (timeout > 0) {
  3484. memset(&start, 0, sizeof(start));
  3485. memset(&now, 0, sizeof(now));
  3486. clock_gettime(CLOCK_MONOTONIC, &start);
  3487. }
  3488. do {
  3489. if (fp != NULL) {
  3490. #if !defined(_WIN32_WCE)
  3491. /* Use read() instead of fread(), because if we're reading from the
  3492. * CGI pipe, fread() may block until IO buffer is filled up. We
  3493. * cannot afford to block and must pass all read bytes immediately
  3494. * to the client. */
  3495. nread = (int)read(fileno(fp), buf, (size_t)len);
  3496. #else
  3497. /* WinCE does not support CGI pipes */
  3498. nread = (int)fread(buf, 1, (size_t)len, fp);
  3499. #endif
  3500. err = (nread < 0) ? ERRNO : 0;
  3501. #ifndef NO_SSL
  3502. } else if (conn->ssl != NULL) {
  3503. nread = SSL_read(conn->ssl, buf, len);
  3504. if (nread <= 0) {
  3505. err = SSL_get_error(conn->ssl, nread);
  3506. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3507. err = ERRNO;
  3508. } else if ((err == SSL_ERROR_WANT_READ)
  3509. || (err == SSL_ERROR_WANT_WRITE)) {
  3510. nread = 0;
  3511. } else {
  3512. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3513. return -1;
  3514. }
  3515. } else {
  3516. err = 0;
  3517. }
  3518. #endif
  3519. } else {
  3520. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3521. err = (nread < 0) ? ERRNO : 0;
  3522. if (nread == 0) {
  3523. /* shutdown of the socket at client side */
  3524. return -1;
  3525. }
  3526. }
  3527. if (conn->ctx->stop_flag) {
  3528. return -1;
  3529. }
  3530. if ((nread > 0) || (nread == 0 && len == 0)) {
  3531. /* some data has been read, or no data was requested */
  3532. return nread;
  3533. }
  3534. if (nread < 0) {
  3535. /* socket error - check errno */
  3536. #ifdef _WIN32
  3537. if (err == WSAEWOULDBLOCK) {
  3538. /* standard case if called from close_socket_gracefully */
  3539. return -1;
  3540. } else if (err == WSAETIMEDOUT) {
  3541. /* timeout is handled by the while loop */
  3542. } else {
  3543. DEBUG_TRACE("recv() failed, error %d", err);
  3544. return -1;
  3545. }
  3546. #else
  3547. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3548. * if the timeout is reached and if the socket was set to non-
  3549. * blocking in close_socket_gracefully, so we can not distinguish
  3550. * here. We have to wait for the timeout in both cases for now.
  3551. */
  3552. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3553. /* EAGAIN/EWOULDBLOCK:
  3554. * standard case if called from close_socket_gracefully
  3555. * => should return -1 */
  3556. /* or timeout occured
  3557. * => the code must stay in the while loop */
  3558. /* EINTR can be generated on a socket with a timeout set even
  3559. * when SA_RESTART is effective for all relevant signals
  3560. * (see signal(7)).
  3561. * => stay in the while loop */
  3562. } else {
  3563. DEBUG_TRACE("recv() failed, error %d", err);
  3564. return -1;
  3565. }
  3566. #endif
  3567. }
  3568. if (timeout > 0) {
  3569. clock_gettime(CLOCK_MONOTONIC, &now);
  3570. }
  3571. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3572. /* Timeout occured, but no data available. */
  3573. return -1;
  3574. }
  3575. static int
  3576. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3577. {
  3578. int n, nread = 0;
  3579. double timeout = -1.0;
  3580. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3581. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3582. }
  3583. while (len > 0 && conn->ctx->stop_flag == 0) {
  3584. n = pull(fp, conn, buf + nread, len, timeout);
  3585. if (n < 0) {
  3586. if (nread == 0) {
  3587. nread = n; /* Propagate the error */
  3588. }
  3589. break;
  3590. } else if (n == 0) {
  3591. break; /* No more data to read */
  3592. } else {
  3593. conn->consumed_content += n;
  3594. nread += n;
  3595. len -= n;
  3596. }
  3597. }
  3598. return nread;
  3599. }
  3600. static void
  3601. discard_unread_request_data(struct mg_connection *conn)
  3602. {
  3603. char buf[MG_BUF_LEN];
  3604. size_t to_read;
  3605. int nread;
  3606. if (conn == NULL) {
  3607. return;
  3608. }
  3609. to_read = sizeof(buf);
  3610. if (conn->is_chunked) {
  3611. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3612. * completely */
  3613. while (conn->is_chunked == 1) {
  3614. nread = mg_read(conn, buf, to_read);
  3615. if (nread <= 0) {
  3616. break;
  3617. }
  3618. }
  3619. } else {
  3620. /* Not chunked: content length is known */
  3621. while (conn->consumed_content < conn->content_len) {
  3622. if (to_read
  3623. > (size_t)(conn->content_len - conn->consumed_content)) {
  3624. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3625. }
  3626. nread = mg_read(conn, buf, to_read);
  3627. if (nread <= 0) {
  3628. break;
  3629. }
  3630. }
  3631. }
  3632. }
  3633. static int
  3634. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3635. {
  3636. int64_t n, buffered_len, nread;
  3637. int64_t len64 =
  3638. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3639. * int, we may not read more
  3640. * bytes */
  3641. const char *body;
  3642. if (conn == NULL) {
  3643. return 0;
  3644. }
  3645. /* If Content-Length is not set for a PUT or POST request, read until
  3646. * socket is closed */
  3647. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3648. conn->content_len = INT64_MAX;
  3649. conn->must_close = 1;
  3650. }
  3651. nread = 0;
  3652. if (conn->consumed_content < conn->content_len) {
  3653. /* Adjust number of bytes to read. */
  3654. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3655. if (left_to_read < len64) {
  3656. /* Do not read more than the total content length of the request.
  3657. */
  3658. len64 = left_to_read;
  3659. }
  3660. /* Return buffered data */
  3661. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3662. - conn->consumed_content;
  3663. if (buffered_len > 0) {
  3664. if (len64 < buffered_len) {
  3665. buffered_len = len64;
  3666. }
  3667. body = conn->buf + conn->request_len + conn->consumed_content;
  3668. memcpy(buf, body, (size_t)buffered_len);
  3669. len64 -= buffered_len;
  3670. conn->consumed_content += buffered_len;
  3671. nread += buffered_len;
  3672. buf = (char *)buf + buffered_len;
  3673. }
  3674. /* We have returned all buffered data. Read new data from the remote
  3675. * socket.
  3676. */
  3677. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3678. nread += n;
  3679. } else {
  3680. nread = ((nread > 0) ? nread : n);
  3681. }
  3682. }
  3683. return (int)nread;
  3684. }
  3685. static char
  3686. mg_getc(struct mg_connection *conn)
  3687. {
  3688. char c;
  3689. if (conn == NULL) {
  3690. return 0;
  3691. }
  3692. conn->content_len++;
  3693. if (mg_read_inner(conn, &c, 1) <= 0) {
  3694. return (char)0;
  3695. }
  3696. return c;
  3697. }
  3698. int
  3699. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3700. {
  3701. if (len > INT_MAX) {
  3702. len = INT_MAX;
  3703. }
  3704. if (conn == NULL) {
  3705. return 0;
  3706. }
  3707. if (conn->is_chunked) {
  3708. size_t all_read = 0;
  3709. while (len > 0) {
  3710. if (conn->is_chunked == 2) {
  3711. /* No more data left to read */
  3712. return 0;
  3713. }
  3714. if (conn->chunk_remainder) {
  3715. /* copy from the remainder of the last received chunk */
  3716. long read_ret;
  3717. size_t read_now =
  3718. ((conn->chunk_remainder > len) ? (len)
  3719. : (conn->chunk_remainder));
  3720. conn->content_len += (int)read_now;
  3721. read_ret =
  3722. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3723. all_read += (size_t)read_ret;
  3724. conn->chunk_remainder -= read_now;
  3725. len -= read_now;
  3726. if (conn->chunk_remainder == 0) {
  3727. /* the rest of the data in the current chunk has been read
  3728. */
  3729. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3730. /* Protocol violation */
  3731. return -1;
  3732. }
  3733. }
  3734. } else {
  3735. /* fetch a new chunk */
  3736. int i = 0;
  3737. char lenbuf[64];
  3738. char *end = 0;
  3739. unsigned long chunkSize = 0;
  3740. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3741. lenbuf[i] = mg_getc(conn);
  3742. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3743. continue;
  3744. }
  3745. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3746. lenbuf[i + 1] = 0;
  3747. chunkSize = strtoul(lenbuf, &end, 16);
  3748. if (chunkSize == 0) {
  3749. /* regular end of content */
  3750. conn->is_chunked = 2;
  3751. }
  3752. break;
  3753. }
  3754. if (!isalnum(lenbuf[i])) {
  3755. /* illegal character for chunk length */
  3756. return -1;
  3757. }
  3758. }
  3759. if ((end == NULL) || (*end != '\r')) {
  3760. /* chunksize not set correctly */
  3761. return -1;
  3762. }
  3763. if (chunkSize == 0) {
  3764. break;
  3765. }
  3766. conn->chunk_remainder = chunkSize;
  3767. }
  3768. }
  3769. return (int)all_read;
  3770. }
  3771. return mg_read_inner(conn, buf, len);
  3772. }
  3773. int
  3774. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3775. {
  3776. time_t now;
  3777. int64_t n, total, allowed;
  3778. if (conn == NULL) {
  3779. return 0;
  3780. }
  3781. if (conn->throttle > 0) {
  3782. if ((now = time(NULL)) != conn->last_throttle_time) {
  3783. conn->last_throttle_time = now;
  3784. conn->last_throttle_bytes = 0;
  3785. }
  3786. allowed = conn->throttle - conn->last_throttle_bytes;
  3787. if (allowed > (int64_t)len) {
  3788. allowed = (int64_t)len;
  3789. }
  3790. if ((total = push_all(conn->ctx,
  3791. NULL,
  3792. conn->client.sock,
  3793. conn->ssl,
  3794. (const char *)buf,
  3795. (int64_t)allowed)) == allowed) {
  3796. buf = (const char *)buf + total;
  3797. conn->last_throttle_bytes += total;
  3798. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3799. allowed = (conn->throttle > ((int64_t)len - total))
  3800. ? (int64_t)len - total
  3801. : conn->throttle;
  3802. if ((n = push_all(conn->ctx,
  3803. NULL,
  3804. conn->client.sock,
  3805. conn->ssl,
  3806. (const char *)buf,
  3807. (int64_t)allowed)) != allowed) {
  3808. break;
  3809. }
  3810. sleep(1);
  3811. conn->last_throttle_bytes = allowed;
  3812. conn->last_throttle_time = time(NULL);
  3813. buf = (const char *)buf + n;
  3814. total += n;
  3815. }
  3816. }
  3817. } else {
  3818. total = push_all(conn->ctx,
  3819. NULL,
  3820. conn->client.sock,
  3821. conn->ssl,
  3822. (const char *)buf,
  3823. (int64_t)len);
  3824. }
  3825. return (int)total;
  3826. }
  3827. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3828. static int
  3829. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3830. {
  3831. va_list ap_copy;
  3832. size_t size = MG_BUF_LEN / 4;
  3833. int len = -1;
  3834. *buf = NULL;
  3835. while (len < 0) {
  3836. if (*buf) {
  3837. mg_free(*buf);
  3838. }
  3839. size *= 4;
  3840. *buf = (char *)mg_malloc(size);
  3841. if (!*buf) {
  3842. break;
  3843. }
  3844. va_copy(ap_copy, ap);
  3845. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3846. va_end(ap_copy);
  3847. (*buf)[size - 1] = 0;
  3848. }
  3849. return len;
  3850. }
  3851. /* Print message to buffer. If buffer is large enough to hold the message,
  3852. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3853. * and return allocated buffer. */
  3854. static int
  3855. alloc_vprintf(char **out_buf,
  3856. char *prealloc_buf,
  3857. size_t prealloc_size,
  3858. const char *fmt,
  3859. va_list ap)
  3860. {
  3861. va_list ap_copy;
  3862. int len;
  3863. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3864. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3865. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3866. * Therefore, we make two passes: on first pass, get required message
  3867. * length.
  3868. * On second pass, actually print the message. */
  3869. va_copy(ap_copy, ap);
  3870. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3871. va_end(ap_copy);
  3872. if (len < 0) {
  3873. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3874. * Switch to alternative code path that uses incremental allocations.
  3875. */
  3876. va_copy(ap_copy, ap);
  3877. len = alloc_vprintf2(out_buf, fmt, ap);
  3878. va_end(ap_copy);
  3879. } else if ((size_t)(len) >= prealloc_size) {
  3880. /* The pre-allocated buffer not large enough. */
  3881. /* Allocate a new buffer. */
  3882. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3883. if (!*out_buf) {
  3884. /* Allocation failed. Return -1 as "out of memory" error. */
  3885. return -1;
  3886. }
  3887. /* Buffer allocation successful. Store the string there. */
  3888. va_copy(ap_copy, ap);
  3889. IGNORE_UNUSED_RESULT(
  3890. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3891. va_end(ap_copy);
  3892. } else {
  3893. /* The pre-allocated buffer is large enough.
  3894. * Use it to store the string and return the address. */
  3895. va_copy(ap_copy, ap);
  3896. IGNORE_UNUSED_RESULT(
  3897. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3898. va_end(ap_copy);
  3899. *out_buf = prealloc_buf;
  3900. }
  3901. return len;
  3902. }
  3903. static int
  3904. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3905. {
  3906. char mem[MG_BUF_LEN];
  3907. char *buf = NULL;
  3908. int len;
  3909. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3910. len = mg_write(conn, buf, (size_t)len);
  3911. }
  3912. if (buf != mem && buf != NULL) {
  3913. mg_free(buf);
  3914. }
  3915. return len;
  3916. }
  3917. int
  3918. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3919. {
  3920. va_list ap;
  3921. int result;
  3922. va_start(ap, fmt);
  3923. result = mg_vprintf(conn, fmt, ap);
  3924. va_end(ap);
  3925. return result;
  3926. }
  3927. int
  3928. mg_url_decode(const char *src,
  3929. int src_len,
  3930. char *dst,
  3931. int dst_len,
  3932. int is_form_url_encoded)
  3933. {
  3934. int i, j, a, b;
  3935. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  3936. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  3937. if (i < src_len - 2 && src[i] == '%'
  3938. && isxdigit(*(const unsigned char *)(src + i + 1))
  3939. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3940. a = tolower(*(const unsigned char *)(src + i + 1));
  3941. b = tolower(*(const unsigned char *)(src + i + 2));
  3942. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3943. i += 2;
  3944. } else if (is_form_url_encoded && src[i] == '+') {
  3945. dst[j] = ' ';
  3946. } else {
  3947. dst[j] = src[i];
  3948. }
  3949. }
  3950. dst[j] = '\0'; /* Null-terminate the destination */
  3951. return (i >= src_len) ? j : -1;
  3952. }
  3953. int
  3954. mg_get_var(const char *data,
  3955. size_t data_len,
  3956. const char *name,
  3957. char *dst,
  3958. size_t dst_len)
  3959. {
  3960. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3961. }
  3962. int
  3963. mg_get_var2(const char *data,
  3964. size_t data_len,
  3965. const char *name,
  3966. char *dst,
  3967. size_t dst_len,
  3968. size_t occurrence)
  3969. {
  3970. const char *p, *e, *s;
  3971. size_t name_len;
  3972. int len;
  3973. if (dst == NULL || dst_len == 0) {
  3974. len = -2;
  3975. } else if (data == NULL || name == NULL || data_len == 0) {
  3976. len = -1;
  3977. dst[0] = '\0';
  3978. } else {
  3979. name_len = strlen(name);
  3980. e = data + data_len;
  3981. len = -1;
  3982. dst[0] = '\0';
  3983. /* data is "var1=val1&var2=val2...". Find variable first */
  3984. for (p = data; p + name_len < e; p++) {
  3985. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3986. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3987. /* Point p to variable value */
  3988. p += name_len + 1;
  3989. /* Point s to the end of the value */
  3990. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3991. if (s == NULL) {
  3992. s = e;
  3993. }
  3994. /* assert(s >= p); */
  3995. if (s < p) {
  3996. return -3;
  3997. }
  3998. /* Decode variable into destination buffer */
  3999. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4000. /* Redirect error code from -1 to -2 (destination buffer too
  4001. * small). */
  4002. if (len == -1) {
  4003. len = -2;
  4004. }
  4005. break;
  4006. }
  4007. }
  4008. }
  4009. return len;
  4010. }
  4011. int
  4012. mg_get_cookie(const char *cookie_header,
  4013. const char *var_name,
  4014. char *dst,
  4015. size_t dst_size)
  4016. {
  4017. const char *s, *p, *end;
  4018. int name_len, len = -1;
  4019. if (dst == NULL || dst_size == 0) {
  4020. len = -2;
  4021. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4022. len = -1;
  4023. dst[0] = '\0';
  4024. } else {
  4025. name_len = (int)strlen(var_name);
  4026. end = s + strlen(s);
  4027. dst[0] = '\0';
  4028. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4029. if (s[name_len] == '=') {
  4030. s += name_len + 1;
  4031. if ((p = strchr(s, ' ')) == NULL) {
  4032. p = end;
  4033. }
  4034. if (p[-1] == ';') {
  4035. p--;
  4036. }
  4037. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4038. s++;
  4039. p--;
  4040. }
  4041. if ((size_t)(p - s) < dst_size) {
  4042. len = (int)(p - s);
  4043. mg_strlcpy(dst, s, (size_t)len + 1);
  4044. } else {
  4045. len = -3;
  4046. }
  4047. break;
  4048. }
  4049. }
  4050. }
  4051. return len;
  4052. }
  4053. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4054. static void
  4055. base64_encode(const unsigned char *src, int src_len, char *dst)
  4056. {
  4057. static const char *b64 =
  4058. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4059. int i, j, a, b, c;
  4060. for (i = j = 0; i < src_len; i += 3) {
  4061. a = src[i];
  4062. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4063. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4064. dst[j++] = b64[a >> 2];
  4065. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4066. if (i + 1 < src_len) {
  4067. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4068. }
  4069. if (i + 2 < src_len) {
  4070. dst[j++] = b64[c & 63];
  4071. }
  4072. }
  4073. while (j % 4 != 0) {
  4074. dst[j++] = '=';
  4075. }
  4076. dst[j++] = '\0';
  4077. }
  4078. #endif
  4079. #if defined(USE_LUA)
  4080. static unsigned char
  4081. b64reverse(char letter)
  4082. {
  4083. if (letter >= 'A' && letter <= 'Z') {
  4084. return letter - 'A';
  4085. }
  4086. if (letter >= 'a' && letter <= 'z') {
  4087. return letter - 'a' + 26;
  4088. }
  4089. if (letter >= '0' && letter <= '9') {
  4090. return letter - '0' + 52;
  4091. }
  4092. if (letter == '+') {
  4093. return 62;
  4094. }
  4095. if (letter == '/') {
  4096. return 63;
  4097. }
  4098. if (letter == '=') {
  4099. return 255; /* normal end */
  4100. }
  4101. return 254; /* error */
  4102. }
  4103. static int
  4104. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4105. {
  4106. int i;
  4107. unsigned char a, b, c, d;
  4108. *dst_len = 0;
  4109. for (i = 0; i < src_len; i += 4) {
  4110. a = b64reverse(src[i]);
  4111. if (a >= 254) {
  4112. return i;
  4113. }
  4114. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4115. if (b >= 254) {
  4116. return i + 1;
  4117. }
  4118. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4119. if (c == 254) {
  4120. return i + 2;
  4121. }
  4122. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4123. if (d == 254) {
  4124. return i + 3;
  4125. }
  4126. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4127. if (c != 255) {
  4128. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4129. if (d != 255) {
  4130. dst[(*dst_len)++] = (c << 6) + d;
  4131. }
  4132. }
  4133. }
  4134. return -1;
  4135. }
  4136. #endif
  4137. static int
  4138. is_put_or_delete_method(const struct mg_connection *conn)
  4139. {
  4140. if (conn) {
  4141. const char *s = conn->request_info.request_method;
  4142. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4143. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4144. }
  4145. return 0;
  4146. }
  4147. static void
  4148. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4149. char *filename, /* out: filename */
  4150. size_t filename_buf_len, /* in: size of filename buffer */
  4151. struct file *filep, /* out: file structure */
  4152. int *is_found, /* out: file is found (directly) */
  4153. int *is_script_resource, /* out: handled by a script? */
  4154. int *is_websocket_request, /* out: websocket connetion? */
  4155. int *is_put_or_delete_request /* out: put/delete a file? */
  4156. )
  4157. {
  4158. /* TODO (high): Restructure this function */
  4159. #if !defined(NO_FILES)
  4160. const char *uri = conn->request_info.local_uri;
  4161. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4162. const char *rewrite;
  4163. struct vec a, b;
  4164. int match_len;
  4165. char gz_path[PATH_MAX];
  4166. char const *accept_encoding;
  4167. int truncated;
  4168. #if !defined(NO_CGI) || defined(USE_LUA)
  4169. char *p;
  4170. #endif
  4171. #else
  4172. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4173. #endif
  4174. memset(filep, 0, sizeof(*filep));
  4175. *filename = 0;
  4176. *is_found = 0;
  4177. *is_script_resource = 0;
  4178. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4179. #if defined(USE_WEBSOCKET)
  4180. *is_websocket_request = is_websocket_protocol(conn);
  4181. #if !defined(NO_FILES)
  4182. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4183. root = conn->ctx->config[WEBSOCKET_ROOT];
  4184. }
  4185. #endif /* !NO_FILES */
  4186. #else /* USE_WEBSOCKET */
  4187. *is_websocket_request = 0;
  4188. #endif /* USE_WEBSOCKET */
  4189. #if !defined(NO_FILES)
  4190. /* Note that root == NULL is a regular use case here. This occurs,
  4191. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4192. * config is not required. */
  4193. if (root == NULL) {
  4194. /* all file related outputs have already been set to 0, just return
  4195. */
  4196. return;
  4197. }
  4198. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4199. * of the path one byte on the right.
  4200. * If document_root is NULL, leave the file empty. */
  4201. mg_snprintf(
  4202. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4203. if (truncated) {
  4204. goto interpret_cleanup;
  4205. }
  4206. rewrite = conn->ctx->config[REWRITE];
  4207. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4208. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4209. mg_snprintf(conn,
  4210. &truncated,
  4211. filename,
  4212. filename_buf_len - 1,
  4213. "%.*s%s",
  4214. (int)b.len,
  4215. b.ptr,
  4216. uri + match_len);
  4217. break;
  4218. }
  4219. }
  4220. if (truncated) {
  4221. goto interpret_cleanup;
  4222. }
  4223. /* Local file path and name, corresponding to requested URI
  4224. * is now stored in "filename" variable. */
  4225. if (mg_stat(conn, filename, filep)) {
  4226. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4227. /* File exists. Check if it is a script type. */
  4228. if (0
  4229. #if !defined(NO_CGI)
  4230. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4231. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4232. filename) > 0
  4233. #endif
  4234. #if defined(USE_LUA)
  4235. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4236. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4237. filename) > 0
  4238. #endif
  4239. #if defined(USE_DUKTAPE)
  4240. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4241. strlen(
  4242. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4243. filename) > 0
  4244. #endif
  4245. ) {
  4246. /* The request addresses a CGI script or a Lua script. The URI
  4247. * corresponds to the script itself (like /path/script.cgi),
  4248. * and there is no additional resource path
  4249. * (like /path/script.cgi/something).
  4250. * Requests that modify (replace or delete) a resource, like
  4251. * PUT and DELETE requests, should replace/delete the script
  4252. * file.
  4253. * Requests that read or write from/to a resource, like GET and
  4254. * POST requests, should call the script and return the
  4255. * generated response. */
  4256. *is_script_resource = !*is_put_or_delete_request;
  4257. }
  4258. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4259. *is_found = 1;
  4260. return;
  4261. }
  4262. /* If we can't find the actual file, look for the file
  4263. * with the same name but a .gz extension. If we find it,
  4264. * use that and set the gzipped flag in the file struct
  4265. * to indicate that the response need to have the content-
  4266. * encoding: gzip header.
  4267. * We can only do this if the browser declares support. */
  4268. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4269. if (strstr(accept_encoding, "gzip") != NULL) {
  4270. mg_snprintf(
  4271. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4272. if (truncated) {
  4273. goto interpret_cleanup;
  4274. }
  4275. if (mg_stat(conn, gz_path, filep)) {
  4276. if (filep) {
  4277. filep->gzipped = 1;
  4278. *is_found = 1;
  4279. }
  4280. /* Currently gz files can not be scripts. */
  4281. return;
  4282. }
  4283. }
  4284. }
  4285. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4286. /* Support PATH_INFO for CGI scripts. */
  4287. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4288. if (*p == '/') {
  4289. *p = '\0';
  4290. if ((0
  4291. #if !defined(NO_CGI)
  4292. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4293. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4294. filename) > 0
  4295. #endif
  4296. #if defined(USE_LUA)
  4297. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4298. strlen(
  4299. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4300. filename) > 0
  4301. #endif
  4302. #if defined(USE_DUKTAPE)
  4303. || match_prefix(
  4304. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4305. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4306. filename) > 0
  4307. #endif
  4308. ) && mg_stat(conn, filename, filep)) {
  4309. /* Shift PATH_INFO block one character right, e.g.
  4310. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4311. * conn->path_info is pointing to the local variable "path"
  4312. * declared in handle_request(), so PATH_INFO is not valid
  4313. * after handle_request returns. */
  4314. conn->path_info = p + 1;
  4315. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4316. * trailing \0 */
  4317. p[1] = '/';
  4318. *is_script_resource = 1;
  4319. break;
  4320. } else {
  4321. *p = '/';
  4322. }
  4323. }
  4324. }
  4325. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4326. #endif /* !defined(NO_FILES) */
  4327. return;
  4328. #if !defined(NO_FILES)
  4329. /* Reset all outputs */
  4330. interpret_cleanup:
  4331. memset(filep, 0, sizeof(*filep));
  4332. *filename = 0;
  4333. *is_found = 0;
  4334. *is_script_resource = 0;
  4335. *is_websocket_request = 0;
  4336. *is_put_or_delete_request = 0;
  4337. #endif /* !defined(NO_FILES) */
  4338. }
  4339. /* Check whether full request is buffered. Return:
  4340. * -1 if request is malformed
  4341. * 0 if request is not yet fully buffered
  4342. * >0 actual request length, including last \r\n\r\n */
  4343. static int
  4344. get_request_len(const char *buf, int buflen)
  4345. {
  4346. const char *s, *e;
  4347. int len = 0;
  4348. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4349. /* Control characters are not allowed but >=128 is. */
  4350. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4351. && *(const unsigned char *)s < 128) {
  4352. len = -1;
  4353. break; /* [i_a] abort scan as soon as one malformed character is
  4354. * found; */
  4355. /* don't let subsequent \r\n\r\n win us over anyhow */
  4356. } else if (s[0] == '\n' && s[1] == '\n') {
  4357. len = (int)(s - buf) + 2;
  4358. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4359. len = (int)(s - buf) + 3;
  4360. }
  4361. return len;
  4362. }
  4363. #if !defined(NO_CACHING)
  4364. /* Convert month to the month number. Return -1 on error, or month number */
  4365. static int
  4366. get_month_index(const char *s)
  4367. {
  4368. size_t i;
  4369. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4370. if (!strcmp(s, month_names[i])) {
  4371. return (int)i;
  4372. }
  4373. }
  4374. return -1;
  4375. }
  4376. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4377. static time_t
  4378. parse_date_string(const char *datetime)
  4379. {
  4380. char month_str[32] = {0};
  4381. int second, minute, hour, day, month, year;
  4382. time_t result = (time_t)0;
  4383. struct tm tm;
  4384. if ((sscanf(datetime,
  4385. "%d/%3s/%d %d:%d:%d",
  4386. &day,
  4387. month_str,
  4388. &year,
  4389. &hour,
  4390. &minute,
  4391. &second) == 6) || (sscanf(datetime,
  4392. "%d %3s %d %d:%d:%d",
  4393. &day,
  4394. month_str,
  4395. &year,
  4396. &hour,
  4397. &minute,
  4398. &second) == 6)
  4399. || (sscanf(datetime,
  4400. "%*3s, %d %3s %d %d:%d:%d",
  4401. &day,
  4402. month_str,
  4403. &year,
  4404. &hour,
  4405. &minute,
  4406. &second) == 6) || (sscanf(datetime,
  4407. "%d-%3s-%d %d:%d:%d",
  4408. &day,
  4409. month_str,
  4410. &year,
  4411. &hour,
  4412. &minute,
  4413. &second) == 6)) {
  4414. month = get_month_index(month_str);
  4415. if ((month >= 0) && (year >= 1970)) {
  4416. memset(&tm, 0, sizeof(tm));
  4417. tm.tm_year = year - 1900;
  4418. tm.tm_mon = month;
  4419. tm.tm_mday = day;
  4420. tm.tm_hour = hour;
  4421. tm.tm_min = minute;
  4422. tm.tm_sec = second;
  4423. result = timegm(&tm);
  4424. }
  4425. }
  4426. return result;
  4427. }
  4428. #endif /* !NO_CACHING */
  4429. /* Protect against directory disclosure attack by removing '..',
  4430. * excessive '/' and '\' characters */
  4431. static void
  4432. remove_double_dots_and_double_slashes(char *s)
  4433. {
  4434. char *p = s;
  4435. while (*s != '\0') {
  4436. *p++ = *s++;
  4437. if (s[-1] == '/' || s[-1] == '\\') {
  4438. /* Skip all following slashes, backslashes and double-dots */
  4439. while (s[0] != '\0') {
  4440. if (s[0] == '/' || s[0] == '\\') {
  4441. s++;
  4442. } else if (s[0] == '.' && s[1] == '.') {
  4443. s += 2;
  4444. } else {
  4445. break;
  4446. }
  4447. }
  4448. }
  4449. }
  4450. *p = '\0';
  4451. }
  4452. static const struct {
  4453. const char *extension;
  4454. size_t ext_len;
  4455. const char *mime_type;
  4456. } builtin_mime_types[] = {
  4457. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4458. * application types */
  4459. {".doc", 4, "application/msword"},
  4460. {".eps", 4, "application/postscript"},
  4461. {".exe", 4, "application/octet-stream"},
  4462. {".js", 3, "application/javascript"},
  4463. {".json", 5, "application/json"},
  4464. {".pdf", 4, "application/pdf"},
  4465. {".ps", 3, "application/postscript"},
  4466. {".rtf", 4, "application/rtf"},
  4467. {".xhtml", 6, "application/xhtml+xml"},
  4468. {".xsl", 4, "application/xml"},
  4469. {".xslt", 5, "application/xml"},
  4470. /* fonts */
  4471. {".ttf", 4, "application/font-sfnt"},
  4472. {".cff", 4, "application/font-sfnt"},
  4473. {".otf", 4, "application/font-sfnt"},
  4474. {".aat", 4, "application/font-sfnt"},
  4475. {".sil", 4, "application/font-sfnt"},
  4476. {".pfr", 4, "application/font-tdpfr"},
  4477. {".woff", 5, "application/font-woff"},
  4478. /* audio */
  4479. {".mp3", 4, "audio/mpeg"},
  4480. {".oga", 4, "audio/ogg"},
  4481. {".ogg", 4, "audio/ogg"},
  4482. /* image */
  4483. {".gif", 4, "image/gif"},
  4484. {".ief", 4, "image/ief"},
  4485. {".jpeg", 5, "image/jpeg"},
  4486. {".jpg", 4, "image/jpeg"},
  4487. {".jpm", 4, "image/jpm"},
  4488. {".jpx", 4, "image/jpx"},
  4489. {".png", 4, "image/png"},
  4490. {".svg", 4, "image/svg+xml"},
  4491. {".tif", 4, "image/tiff"},
  4492. {".tiff", 5, "image/tiff"},
  4493. /* model */
  4494. {".wrl", 4, "model/vrml"},
  4495. /* text */
  4496. {".css", 4, "text/css"},
  4497. {".csv", 4, "text/csv"},
  4498. {".htm", 4, "text/html"},
  4499. {".html", 5, "text/html"},
  4500. {".sgm", 4, "text/sgml"},
  4501. {".shtm", 5, "text/html"},
  4502. {".shtml", 6, "text/html"},
  4503. {".txt", 4, "text/plain"},
  4504. {".xml", 4, "text/xml"},
  4505. /* video */
  4506. {".mov", 4, "video/quicktime"},
  4507. {".mp4", 4, "video/mp4"},
  4508. {".mpeg", 5, "video/mpeg"},
  4509. {".mpg", 4, "video/mpeg"},
  4510. {".ogv", 4, "video/ogg"},
  4511. {".qt", 3, "video/quicktime"},
  4512. /* not registered types
  4513. * (http://reference.sitepoint.com/html/mime-types-full,
  4514. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4515. {".arj", 4, "application/x-arj-compressed"},
  4516. {".gz", 3, "application/x-gunzip"},
  4517. {".rar", 4, "application/x-arj-compressed"},
  4518. {".swf", 4, "application/x-shockwave-flash"},
  4519. {".tar", 4, "application/x-tar"},
  4520. {".tgz", 4, "application/x-tar-gz"},
  4521. {".torrent", 8, "application/x-bittorrent"},
  4522. {".ppt", 4, "application/x-mspowerpoint"},
  4523. {".xls", 4, "application/x-msexcel"},
  4524. {".zip", 4, "application/x-zip-compressed"},
  4525. {".aac",
  4526. 4,
  4527. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4528. {".aif", 4, "audio/x-aif"},
  4529. {".m3u", 4, "audio/x-mpegurl"},
  4530. {".mid", 4, "audio/x-midi"},
  4531. {".ra", 3, "audio/x-pn-realaudio"},
  4532. {".ram", 4, "audio/x-pn-realaudio"},
  4533. {".wav", 4, "audio/x-wav"},
  4534. {".bmp", 4, "image/bmp"},
  4535. {".ico", 4, "image/x-icon"},
  4536. {".pct", 4, "image/x-pct"},
  4537. {".pict", 5, "image/pict"},
  4538. {".rgb", 4, "image/x-rgb"},
  4539. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4540. {".asf", 4, "video/x-ms-asf"},
  4541. {".avi", 4, "video/x-msvideo"},
  4542. {".m4v", 4, "video/x-m4v"},
  4543. {NULL, 0, NULL}};
  4544. const char *
  4545. mg_get_builtin_mime_type(const char *path)
  4546. {
  4547. const char *ext;
  4548. size_t i, path_len;
  4549. path_len = strlen(path);
  4550. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4551. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4552. if (path_len > builtin_mime_types[i].ext_len
  4553. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4554. return builtin_mime_types[i].mime_type;
  4555. }
  4556. }
  4557. return "text/plain";
  4558. }
  4559. /* Look at the "path" extension and figure what mime type it has.
  4560. * Store mime type in the vector. */
  4561. static void
  4562. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4563. {
  4564. struct vec ext_vec, mime_vec;
  4565. const char *list, *ext;
  4566. size_t path_len;
  4567. path_len = strlen(path);
  4568. if (ctx == NULL || vec == NULL) {
  4569. return;
  4570. }
  4571. /* Scan user-defined mime types first, in case user wants to
  4572. * override default mime types. */
  4573. list = ctx->config[EXTRA_MIME_TYPES];
  4574. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4575. /* ext now points to the path suffix */
  4576. ext = path + path_len - ext_vec.len;
  4577. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4578. *vec = mime_vec;
  4579. return;
  4580. }
  4581. }
  4582. vec->ptr = mg_get_builtin_mime_type(path);
  4583. vec->len = strlen(vec->ptr);
  4584. }
  4585. /* Stringify binary data. Output buffer must be twice as big as input,
  4586. * because each byte takes 2 bytes in string representation */
  4587. static void
  4588. bin2str(char *to, const unsigned char *p, size_t len)
  4589. {
  4590. static const char *hex = "0123456789abcdef";
  4591. for (; len--; p++) {
  4592. *to++ = hex[p[0] >> 4];
  4593. *to++ = hex[p[0] & 0x0f];
  4594. }
  4595. *to = '\0';
  4596. }
  4597. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4598. char *
  4599. mg_md5(char buf[33], ...)
  4600. {
  4601. md5_byte_t hash[16];
  4602. const char *p;
  4603. va_list ap;
  4604. md5_state_t ctx;
  4605. md5_init(&ctx);
  4606. va_start(ap, buf);
  4607. while ((p = va_arg(ap, const char *)) != NULL) {
  4608. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4609. }
  4610. va_end(ap);
  4611. md5_finish(&ctx, hash);
  4612. bin2str(buf, hash, sizeof(hash));
  4613. return buf;
  4614. }
  4615. /* Check the user's password, return 1 if OK */
  4616. static int
  4617. check_password(const char *method,
  4618. const char *ha1,
  4619. const char *uri,
  4620. const char *nonce,
  4621. const char *nc,
  4622. const char *cnonce,
  4623. const char *qop,
  4624. const char *response)
  4625. {
  4626. char ha2[32 + 1], expected_response[32 + 1];
  4627. /* Some of the parameters may be NULL */
  4628. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4629. || qop == NULL
  4630. || response == NULL) {
  4631. return 0;
  4632. }
  4633. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4634. if (strlen(response) != 32) {
  4635. return 0;
  4636. }
  4637. mg_md5(ha2, method, ":", uri, NULL);
  4638. mg_md5(expected_response,
  4639. ha1,
  4640. ":",
  4641. nonce,
  4642. ":",
  4643. nc,
  4644. ":",
  4645. cnonce,
  4646. ":",
  4647. qop,
  4648. ":",
  4649. ha2,
  4650. NULL);
  4651. return mg_strcasecmp(response, expected_response) == 0;
  4652. }
  4653. /* Use the global passwords file, if specified by auth_gpass option,
  4654. * or search for .htpasswd in the requested directory. */
  4655. static void
  4656. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4657. {
  4658. if (conn != NULL && conn->ctx != NULL) {
  4659. char name[PATH_MAX];
  4660. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4661. struct file file = STRUCT_FILE_INITIALIZER;
  4662. int truncated;
  4663. if (gpass != NULL) {
  4664. /* Use global passwords file */
  4665. if (!mg_fopen(conn, gpass, "r", filep)) {
  4666. #ifdef DEBUG
  4667. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4668. #endif
  4669. }
  4670. /* Important: using local struct file to test path for is_directory
  4671. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4672. * was opened. */
  4673. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4674. mg_snprintf(conn,
  4675. &truncated,
  4676. name,
  4677. sizeof(name),
  4678. "%s/%s",
  4679. path,
  4680. PASSWORDS_FILE_NAME);
  4681. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4682. #ifdef DEBUG
  4683. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4684. #endif
  4685. }
  4686. } else {
  4687. /* Try to find .htpasswd in requested directory. */
  4688. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4689. if (e[0] == '/') {
  4690. break;
  4691. }
  4692. }
  4693. mg_snprintf(conn,
  4694. &truncated,
  4695. name,
  4696. sizeof(name),
  4697. "%.*s/%s",
  4698. (int)(e - p),
  4699. p,
  4700. PASSWORDS_FILE_NAME);
  4701. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4702. #ifdef DEBUG
  4703. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4704. #endif
  4705. }
  4706. }
  4707. }
  4708. }
  4709. /* Parsed Authorization header */
  4710. struct ah {
  4711. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4712. };
  4713. /* Return 1 on success. Always initializes the ah structure. */
  4714. static int
  4715. parse_auth_header(struct mg_connection *conn,
  4716. char *buf,
  4717. size_t buf_size,
  4718. struct ah *ah)
  4719. {
  4720. char *name, *value, *s;
  4721. const char *auth_header;
  4722. uint64_t nonce;
  4723. if (!ah || !conn) {
  4724. return 0;
  4725. }
  4726. (void)memset(ah, 0, sizeof(*ah));
  4727. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4728. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4729. return 0;
  4730. }
  4731. /* Make modifiable copy of the auth header */
  4732. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4733. s = buf;
  4734. /* Parse authorization header */
  4735. for (;;) {
  4736. /* Gobble initial spaces */
  4737. while (isspace(*(unsigned char *)s)) {
  4738. s++;
  4739. }
  4740. name = skip_quoted(&s, "=", " ", 0);
  4741. /* Value is either quote-delimited, or ends at first comma or space. */
  4742. if (s[0] == '\"') {
  4743. s++;
  4744. value = skip_quoted(&s, "\"", " ", '\\');
  4745. if (s[0] == ',') {
  4746. s++;
  4747. }
  4748. } else {
  4749. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4750. * spaces */
  4751. }
  4752. if (*name == '\0') {
  4753. break;
  4754. }
  4755. if (!strcmp(name, "username")) {
  4756. ah->user = value;
  4757. } else if (!strcmp(name, "cnonce")) {
  4758. ah->cnonce = value;
  4759. } else if (!strcmp(name, "response")) {
  4760. ah->response = value;
  4761. } else if (!strcmp(name, "uri")) {
  4762. ah->uri = value;
  4763. } else if (!strcmp(name, "qop")) {
  4764. ah->qop = value;
  4765. } else if (!strcmp(name, "nc")) {
  4766. ah->nc = value;
  4767. } else if (!strcmp(name, "nonce")) {
  4768. ah->nonce = value;
  4769. }
  4770. }
  4771. #ifndef NO_NONCE_CHECK
  4772. /* Read the nonce from the response. */
  4773. if (ah->nonce == NULL) {
  4774. return 0;
  4775. }
  4776. s = NULL;
  4777. nonce = strtoull(ah->nonce, &s, 10);
  4778. if ((s == NULL) || (*s != 0)) {
  4779. return 0;
  4780. }
  4781. /* Convert the nonce from the client to a number. */
  4782. nonce ^= conn->ctx->auth_nonce_mask;
  4783. /* The converted number corresponds to the time the nounce has been
  4784. * created. This should not be earlier than the server start. */
  4785. /* Server side nonce check is valuable in all situations but one:
  4786. * if the server restarts frequently, but the client should not see
  4787. * that, so the server should accept nonces from previous starts. */
  4788. /* However, the reasonable default is to not accept a nonce from a
  4789. * previous start, so if anyone changed the access rights between
  4790. * two restarts, a new login is required. */
  4791. if (nonce < (uint64_t)conn->ctx->start_time) {
  4792. /* nonce is from a previous start of the server and no longer valid
  4793. * (replay attack?) */
  4794. return 0;
  4795. }
  4796. /* Check if the nonce is too high, so it has not (yet) been used by the
  4797. * server. */
  4798. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4799. return 0;
  4800. }
  4801. #else
  4802. (void)nonce;
  4803. #endif
  4804. /* CGI needs it as REMOTE_USER */
  4805. if (ah->user != NULL) {
  4806. conn->request_info.remote_user = mg_strdup(ah->user);
  4807. } else {
  4808. return 0;
  4809. }
  4810. return 1;
  4811. }
  4812. static const char *
  4813. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4814. {
  4815. const char *eof;
  4816. size_t len;
  4817. const char *memend;
  4818. if (!filep) {
  4819. return NULL;
  4820. }
  4821. if (filep->membuf != NULL && *p != NULL) {
  4822. memend = (const char *)&filep->membuf[filep->size];
  4823. /* Search for \n from p till the end of stream */
  4824. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4825. if (eof != NULL) {
  4826. eof += 1; /* Include \n */
  4827. } else {
  4828. eof = memend; /* Copy remaining data */
  4829. }
  4830. len =
  4831. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4832. memcpy(buf, *p, len);
  4833. buf[len] = '\0';
  4834. *p += len;
  4835. return len ? eof : NULL;
  4836. } else if (filep->fp != NULL) {
  4837. return fgets(buf, (int)size, filep->fp);
  4838. } else {
  4839. return NULL;
  4840. }
  4841. }
  4842. struct read_auth_file_struct {
  4843. struct mg_connection *conn;
  4844. struct ah ah;
  4845. char *domain;
  4846. char buf[256 + 256 + 40];
  4847. char *f_user;
  4848. char *f_domain;
  4849. char *f_ha1;
  4850. };
  4851. static int
  4852. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4853. {
  4854. char *p;
  4855. int is_authorized = 0;
  4856. struct file fp;
  4857. size_t l;
  4858. if (!filep || !workdata) {
  4859. return 0;
  4860. }
  4861. /* Loop over passwords file */
  4862. p = (char *)filep->membuf;
  4863. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4864. l = strlen(workdata->buf);
  4865. while (l > 0) {
  4866. if (isspace(workdata->buf[l - 1])
  4867. || iscntrl(workdata->buf[l - 1])) {
  4868. l--;
  4869. workdata->buf[l] = 0;
  4870. } else
  4871. break;
  4872. }
  4873. if (l < 1) {
  4874. continue;
  4875. }
  4876. workdata->f_user = workdata->buf;
  4877. if (workdata->f_user[0] == ':') {
  4878. /* user names may not contain a ':' and may not be empty,
  4879. * so lines starting with ':' may be used for a special purpose */
  4880. if (workdata->f_user[1] == '#') {
  4881. /* :# is a comment */
  4882. continue;
  4883. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4884. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4885. is_authorized = read_auth_file(&fp, workdata);
  4886. mg_fclose(&fp);
  4887. } else {
  4888. mg_cry(workdata->conn,
  4889. "%s: cannot open authorization file: %s",
  4890. __func__,
  4891. workdata->buf);
  4892. }
  4893. continue;
  4894. }
  4895. /* everything is invalid for the moment (might change in the
  4896. * future) */
  4897. mg_cry(workdata->conn,
  4898. "%s: syntax error in authorization file: %s",
  4899. __func__,
  4900. workdata->buf);
  4901. continue;
  4902. }
  4903. workdata->f_domain = strchr(workdata->f_user, ':');
  4904. if (workdata->f_domain == NULL) {
  4905. mg_cry(workdata->conn,
  4906. "%s: syntax error in authorization file: %s",
  4907. __func__,
  4908. workdata->buf);
  4909. continue;
  4910. }
  4911. *(workdata->f_domain) = 0;
  4912. (workdata->f_domain)++;
  4913. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4914. if (workdata->f_ha1 == NULL) {
  4915. mg_cry(workdata->conn,
  4916. "%s: syntax error in authorization file: %s",
  4917. __func__,
  4918. workdata->buf);
  4919. continue;
  4920. }
  4921. *(workdata->f_ha1) = 0;
  4922. (workdata->f_ha1)++;
  4923. if (!strcmp(workdata->ah.user, workdata->f_user)
  4924. && !strcmp(workdata->domain, workdata->f_domain)) {
  4925. return check_password(workdata->conn->request_info.request_method,
  4926. workdata->f_ha1,
  4927. workdata->ah.uri,
  4928. workdata->ah.nonce,
  4929. workdata->ah.nc,
  4930. workdata->ah.cnonce,
  4931. workdata->ah.qop,
  4932. workdata->ah.response);
  4933. }
  4934. }
  4935. return is_authorized;
  4936. }
  4937. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4938. static int
  4939. authorize(struct mg_connection *conn, struct file *filep)
  4940. {
  4941. struct read_auth_file_struct workdata;
  4942. char buf[MG_BUF_LEN];
  4943. if (!conn || !conn->ctx) {
  4944. return 0;
  4945. }
  4946. memset(&workdata, 0, sizeof(workdata));
  4947. workdata.conn = conn;
  4948. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4949. return 0;
  4950. }
  4951. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4952. return read_auth_file(filep, &workdata);
  4953. }
  4954. /* Return 1 if request is authorised, 0 otherwise. */
  4955. static int
  4956. check_authorization(struct mg_connection *conn, const char *path)
  4957. {
  4958. char fname[PATH_MAX];
  4959. struct vec uri_vec, filename_vec;
  4960. const char *list;
  4961. struct file file = STRUCT_FILE_INITIALIZER;
  4962. int authorized = 1, truncated;
  4963. if (!conn || !conn->ctx) {
  4964. return 0;
  4965. }
  4966. list = conn->ctx->config[PROTECT_URI];
  4967. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4968. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4969. mg_snprintf(conn,
  4970. &truncated,
  4971. fname,
  4972. sizeof(fname),
  4973. "%.*s",
  4974. (int)filename_vec.len,
  4975. filename_vec.ptr);
  4976. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4977. mg_cry(conn,
  4978. "%s: cannot open %s: %s",
  4979. __func__,
  4980. fname,
  4981. strerror(errno));
  4982. }
  4983. break;
  4984. }
  4985. }
  4986. if (!is_file_opened(&file)) {
  4987. open_auth_file(conn, path, &file);
  4988. }
  4989. if (is_file_opened(&file)) {
  4990. authorized = authorize(conn, &file);
  4991. mg_fclose(&file);
  4992. }
  4993. return authorized;
  4994. }
  4995. static void
  4996. send_authorization_request(struct mg_connection *conn)
  4997. {
  4998. char date[64];
  4999. time_t curtime = time(NULL);
  5000. if (conn && conn->ctx) {
  5001. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5002. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5003. nonce += conn->ctx->nonce_count;
  5004. ++conn->ctx->nonce_count;
  5005. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5006. nonce ^= conn->ctx->auth_nonce_mask;
  5007. conn->status_code = 401;
  5008. conn->must_close = 1;
  5009. gmt_time_string(date, sizeof(date), &curtime);
  5010. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5011. send_no_cache_header(conn);
  5012. mg_printf(conn,
  5013. "Date: %s\r\n"
  5014. "Connection: %s\r\n"
  5015. "Content-Length: 0\r\n"
  5016. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5017. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5018. date,
  5019. suggest_connection_header(conn),
  5020. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5021. nonce);
  5022. }
  5023. }
  5024. #if !defined(NO_FILES)
  5025. static int
  5026. is_authorized_for_put(struct mg_connection *conn)
  5027. {
  5028. if (conn) {
  5029. struct file file = STRUCT_FILE_INITIALIZER;
  5030. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5031. int ret = 0;
  5032. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5033. ret = authorize(conn, &file);
  5034. mg_fclose(&file);
  5035. }
  5036. return ret;
  5037. }
  5038. return 0;
  5039. }
  5040. #endif
  5041. int
  5042. mg_modify_passwords_file(const char *fname,
  5043. const char *domain,
  5044. const char *user,
  5045. const char *pass)
  5046. {
  5047. int found, i;
  5048. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5049. FILE *fp, *fp2;
  5050. found = 0;
  5051. fp = fp2 = NULL;
  5052. /* Regard empty password as no password - remove user record. */
  5053. if (pass != NULL && pass[0] == '\0') {
  5054. pass = NULL;
  5055. }
  5056. /* Other arguments must not be empty */
  5057. if (fname == NULL || domain == NULL || user == NULL) {
  5058. return 0;
  5059. }
  5060. /* Using the given file format, user name and domain must not contain ':'
  5061. */
  5062. if (strchr(user, ':') != NULL) {
  5063. return 0;
  5064. }
  5065. if (strchr(domain, ':') != NULL) {
  5066. return 0;
  5067. }
  5068. /* Do not allow control characters like newline in user name and domain.
  5069. * Do not allow excessively long names either. */
  5070. for (i = 0; i < 255 && user[i] != 0; i++) {
  5071. if (iscntrl(user[i])) {
  5072. return 0;
  5073. }
  5074. }
  5075. if (user[i]) {
  5076. return 0;
  5077. }
  5078. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5079. if (iscntrl(domain[i])) {
  5080. return 0;
  5081. }
  5082. }
  5083. if (domain[i]) {
  5084. return 0;
  5085. }
  5086. /* The maximum length of the path to the password file is limited */
  5087. if ((strlen(fname) + 4) >= PATH_MAX) {
  5088. return 0;
  5089. }
  5090. /* Create a temporary file name. Length has been checked before. */
  5091. strcpy(tmp, fname);
  5092. strcat(tmp, ".tmp");
  5093. /* Create the file if does not exist */
  5094. /* Use of fopen here is OK, since fname is only ASCII */
  5095. if ((fp = fopen(fname, "a+")) != NULL) {
  5096. (void)fclose(fp);
  5097. }
  5098. /* Open the given file and temporary file */
  5099. if ((fp = fopen(fname, "r")) == NULL) {
  5100. return 0;
  5101. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5102. fclose(fp);
  5103. return 0;
  5104. }
  5105. /* Copy the stuff to temporary file */
  5106. while (fgets(line, sizeof(line), fp) != NULL) {
  5107. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5108. continue;
  5109. }
  5110. u[255] = 0;
  5111. d[255] = 0;
  5112. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5113. found++;
  5114. if (pass != NULL) {
  5115. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5116. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5117. }
  5118. } else {
  5119. fprintf(fp2, "%s", line);
  5120. }
  5121. }
  5122. /* If new user, just add it */
  5123. if (!found && pass != NULL) {
  5124. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5125. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5126. }
  5127. /* Close files */
  5128. fclose(fp);
  5129. fclose(fp2);
  5130. /* Put the temp file in place of real file */
  5131. IGNORE_UNUSED_RESULT(remove(fname));
  5132. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5133. return 1;
  5134. }
  5135. static int
  5136. is_valid_port(unsigned long port)
  5137. {
  5138. return port < 0xffff;
  5139. }
  5140. static int
  5141. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5142. {
  5143. struct addrinfo hints, *res, *ressave;
  5144. int func_ret = 0;
  5145. int gai_ret;
  5146. memset(&hints, 0, sizeof(struct addrinfo));
  5147. hints.ai_family = af;
  5148. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5149. if (gai_ret != 0) {
  5150. /* gai_strerror could be used to convert gai_ret to a string */
  5151. /* POSIX return values: see
  5152. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5153. */
  5154. /* Windows return values: see
  5155. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5156. */
  5157. return 0;
  5158. }
  5159. ressave = res;
  5160. while (res) {
  5161. if (dstlen >= res->ai_addrlen) {
  5162. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5163. func_ret = 1;
  5164. }
  5165. res = res->ai_next;
  5166. }
  5167. freeaddrinfo(ressave);
  5168. return func_ret;
  5169. }
  5170. static int
  5171. connect_socket(struct mg_context *ctx /* may be NULL */,
  5172. const char *host,
  5173. int port,
  5174. int use_ssl,
  5175. char *ebuf,
  5176. size_t ebuf_len,
  5177. SOCKET *sock /* output: socket, must not be NULL */,
  5178. union usa *sa /* output: socket address, must not be NULL */
  5179. )
  5180. {
  5181. int ip_ver = 0;
  5182. *sock = INVALID_SOCKET;
  5183. memset(sa, 0, sizeof(*sa));
  5184. if (ebuf_len > 0) {
  5185. *ebuf = 0;
  5186. }
  5187. if (host == NULL) {
  5188. mg_snprintf(NULL,
  5189. NULL, /* No truncation check for ebuf */
  5190. ebuf,
  5191. ebuf_len,
  5192. "%s",
  5193. "NULL host");
  5194. return 0;
  5195. }
  5196. if (port < 0 || !is_valid_port((unsigned)port)) {
  5197. mg_snprintf(NULL,
  5198. NULL, /* No truncation check for ebuf */
  5199. ebuf,
  5200. ebuf_len,
  5201. "%s",
  5202. "invalid port");
  5203. return 0;
  5204. }
  5205. #if !defined(NO_SSL)
  5206. if (use_ssl && (SSLv23_client_method == NULL)) {
  5207. mg_snprintf(NULL,
  5208. NULL, /* No truncation check for ebuf */
  5209. ebuf,
  5210. ebuf_len,
  5211. "%s",
  5212. "SSL is not initialized");
  5213. return 0;
  5214. }
  5215. #else
  5216. (void)use_ssl;
  5217. #endif
  5218. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5219. sa->sin.sin_port = htons((uint16_t)port);
  5220. ip_ver = 4;
  5221. #ifdef USE_IPV6
  5222. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5223. sa->sin6.sin6_port = htons((uint16_t)port);
  5224. ip_ver = 6;
  5225. } else if (host[0] == '[') {
  5226. /* While getaddrinfo on Windows will work with [::1],
  5227. * getaddrinfo on Linux only works with ::1 (without []). */
  5228. size_t l = strlen(host + 1);
  5229. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5230. if (h) {
  5231. h[l - 1] = 0;
  5232. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5233. sa->sin6.sin6_port = htons((uint16_t)port);
  5234. ip_ver = 6;
  5235. }
  5236. mg_free(h);
  5237. }
  5238. #endif
  5239. }
  5240. if (ip_ver == 0) {
  5241. mg_snprintf(NULL,
  5242. NULL, /* No truncation check for ebuf */
  5243. ebuf,
  5244. ebuf_len,
  5245. "%s",
  5246. "host not found");
  5247. return 0;
  5248. }
  5249. if (ip_ver == 4) {
  5250. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5251. }
  5252. #ifdef USE_IPV6
  5253. else if (ip_ver == 6) {
  5254. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5255. }
  5256. #endif
  5257. if (*sock == INVALID_SOCKET) {
  5258. mg_snprintf(NULL,
  5259. NULL, /* No truncation check for ebuf */
  5260. ebuf,
  5261. ebuf_len,
  5262. "socket(): %s",
  5263. strerror(ERRNO));
  5264. return 0;
  5265. }
  5266. set_close_on_exec(*sock, fc(ctx));
  5267. if ((ip_ver == 4)
  5268. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5269. == 0)) {
  5270. /* connected with IPv4 */
  5271. return 1;
  5272. }
  5273. #ifdef USE_IPV6
  5274. if ((ip_ver == 6)
  5275. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5276. == 0)) {
  5277. /* connected with IPv6 */
  5278. return 1;
  5279. }
  5280. #endif
  5281. /* Not connected */
  5282. mg_snprintf(NULL,
  5283. NULL, /* No truncation check for ebuf */
  5284. ebuf,
  5285. ebuf_len,
  5286. "connect(%s:%d): %s",
  5287. host,
  5288. port,
  5289. strerror(ERRNO));
  5290. closesocket(*sock);
  5291. *sock = INVALID_SOCKET;
  5292. return 0;
  5293. }
  5294. int
  5295. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5296. {
  5297. static const char *dont_escape = "._-$,;~()";
  5298. static const char *hex = "0123456789abcdef";
  5299. char *pos = dst;
  5300. const char *end = dst + dst_len - 1;
  5301. for (; *src != '\0' && pos < end; src++, pos++) {
  5302. if (isalnum(*(const unsigned char *)src)
  5303. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5304. *pos = *src;
  5305. } else if (pos + 2 < end) {
  5306. pos[0] = '%';
  5307. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5308. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5309. pos += 2;
  5310. } else {
  5311. break;
  5312. }
  5313. }
  5314. *pos = '\0';
  5315. return (*src == '\0') ? (int)(pos - dst) : -1;
  5316. }
  5317. static void
  5318. print_dir_entry(struct de *de)
  5319. {
  5320. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5321. struct tm *tm;
  5322. if (de->file.is_directory) {
  5323. mg_snprintf(de->conn,
  5324. NULL, /* Buffer is big enough */
  5325. size,
  5326. sizeof(size),
  5327. "%s",
  5328. "[DIRECTORY]");
  5329. } else {
  5330. /* We use (signed) cast below because MSVC 6 compiler cannot
  5331. * convert unsigned __int64 to double. Sigh. */
  5332. if (de->file.size < 1024) {
  5333. mg_snprintf(de->conn,
  5334. NULL, /* Buffer is big enough */
  5335. size,
  5336. sizeof(size),
  5337. "%d",
  5338. (int)de->file.size);
  5339. } else if (de->file.size < 0x100000) {
  5340. mg_snprintf(de->conn,
  5341. NULL, /* Buffer is big enough */
  5342. size,
  5343. sizeof(size),
  5344. "%.1fk",
  5345. (double)de->file.size / 1024.0);
  5346. } else if (de->file.size < 0x40000000) {
  5347. mg_snprintf(de->conn,
  5348. NULL, /* Buffer is big enough */
  5349. size,
  5350. sizeof(size),
  5351. "%.1fM",
  5352. (double)de->file.size / 1048576);
  5353. } else {
  5354. mg_snprintf(de->conn,
  5355. NULL, /* Buffer is big enough */
  5356. size,
  5357. sizeof(size),
  5358. "%.1fG",
  5359. (double)de->file.size / 1073741824);
  5360. }
  5361. }
  5362. /* Note: mg_snprintf will not cause a buffer overflow above.
  5363. * So, string truncation checks are not required here. */
  5364. tm = localtime(&de->file.last_modified);
  5365. if (tm != NULL) {
  5366. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5367. } else {
  5368. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5369. mod[sizeof(mod) - 1] = '\0';
  5370. }
  5371. mg_url_encode(de->file_name, href, sizeof(href));
  5372. de->conn->num_bytes_sent +=
  5373. mg_printf(de->conn,
  5374. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5375. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5376. de->conn->request_info.local_uri,
  5377. href,
  5378. de->file.is_directory ? "/" : "",
  5379. de->file_name,
  5380. de->file.is_directory ? "/" : "",
  5381. mod,
  5382. size);
  5383. }
  5384. /* This function is called from send_directory() and used for
  5385. * sorting directory entries by size, or name, or modification time.
  5386. * On windows, __cdecl specification is needed in case if project is built
  5387. * with __stdcall convention. qsort always requires __cdels callback. */
  5388. static int WINCDECL
  5389. compare_dir_entries(const void *p1, const void *p2)
  5390. {
  5391. if (p1 && p2) {
  5392. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5393. const char *query_string = a->conn->request_info.query_string;
  5394. int cmp_result = 0;
  5395. if (query_string == NULL) {
  5396. query_string = "na";
  5397. }
  5398. if (a->file.is_directory && !b->file.is_directory) {
  5399. return -1; /* Always put directories on top */
  5400. } else if (!a->file.is_directory && b->file.is_directory) {
  5401. return 1; /* Always put directories on top */
  5402. } else if (*query_string == 'n') {
  5403. cmp_result = strcmp(a->file_name, b->file_name);
  5404. } else if (*query_string == 's') {
  5405. cmp_result = (a->file.size == b->file.size)
  5406. ? 0
  5407. : ((a->file.size > b->file.size) ? 1 : -1);
  5408. } else if (*query_string == 'd') {
  5409. cmp_result =
  5410. (a->file.last_modified == b->file.last_modified)
  5411. ? 0
  5412. : ((a->file.last_modified > b->file.last_modified) ? 1
  5413. : -1);
  5414. }
  5415. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5416. }
  5417. return 0;
  5418. }
  5419. static int
  5420. must_hide_file(struct mg_connection *conn, const char *path)
  5421. {
  5422. if (conn && conn->ctx) {
  5423. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5424. const char *pattern = conn->ctx->config[HIDE_FILES];
  5425. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5426. || (pattern != NULL
  5427. && match_prefix(pattern, strlen(pattern), path) > 0);
  5428. }
  5429. return 0;
  5430. }
  5431. static int
  5432. scan_directory(struct mg_connection *conn,
  5433. const char *dir,
  5434. void *data,
  5435. void (*cb)(struct de *, void *))
  5436. {
  5437. char path[PATH_MAX];
  5438. struct dirent *dp;
  5439. DIR *dirp;
  5440. struct de de;
  5441. int truncated;
  5442. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5443. return 0;
  5444. } else {
  5445. de.conn = conn;
  5446. while ((dp = mg_readdir(dirp)) != NULL) {
  5447. /* Do not show current dir and hidden files */
  5448. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5449. || must_hide_file(conn, dp->d_name)) {
  5450. continue;
  5451. }
  5452. mg_snprintf(
  5453. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5454. /* If we don't memset stat structure to zero, mtime will have
  5455. * garbage and strftime() will segfault later on in
  5456. * print_dir_entry(). memset is required only if mg_stat()
  5457. * fails. For more details, see
  5458. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5459. memset(&de.file, 0, sizeof(de.file));
  5460. if (truncated) {
  5461. /* If the path is not complete, skip processing. */
  5462. continue;
  5463. }
  5464. if (!mg_stat(conn, path, &de.file)) {
  5465. mg_cry(conn,
  5466. "%s: mg_stat(%s) failed: %s",
  5467. __func__,
  5468. path,
  5469. strerror(ERRNO));
  5470. }
  5471. de.file_name = dp->d_name;
  5472. cb(&de, data);
  5473. }
  5474. (void)mg_closedir(dirp);
  5475. }
  5476. return 1;
  5477. }
  5478. #if !defined(NO_FILES)
  5479. static int
  5480. remove_directory(struct mg_connection *conn, const char *dir)
  5481. {
  5482. char path[PATH_MAX];
  5483. struct dirent *dp;
  5484. DIR *dirp;
  5485. struct de de;
  5486. int truncated;
  5487. int ok = 1;
  5488. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5489. return 0;
  5490. } else {
  5491. de.conn = conn;
  5492. while ((dp = mg_readdir(dirp)) != NULL) {
  5493. /* Do not show current dir (but show hidden files as they will
  5494. * also be removed) */
  5495. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5496. continue;
  5497. }
  5498. mg_snprintf(
  5499. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5500. /* If we don't memset stat structure to zero, mtime will have
  5501. * garbage and strftime() will segfault later on in
  5502. * print_dir_entry(). memset is required only if mg_stat()
  5503. * fails. For more details, see
  5504. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5505. memset(&de.file, 0, sizeof(de.file));
  5506. if (truncated) {
  5507. /* Do not delete anything shorter */
  5508. ok = 0;
  5509. continue;
  5510. }
  5511. if (!mg_stat(conn, path, &de.file)) {
  5512. mg_cry(conn,
  5513. "%s: mg_stat(%s) failed: %s",
  5514. __func__,
  5515. path,
  5516. strerror(ERRNO));
  5517. ok = 0;
  5518. }
  5519. if (de.file.membuf == NULL) {
  5520. /* file is not in memory */
  5521. if (de.file.is_directory) {
  5522. if (remove_directory(conn, path) == 0) {
  5523. ok = 0;
  5524. }
  5525. } else {
  5526. if (mg_remove(conn, path) == 0) {
  5527. ok = 0;
  5528. }
  5529. }
  5530. } else {
  5531. /* file is in memory. It can not be deleted. */
  5532. ok = 0;
  5533. }
  5534. }
  5535. (void)mg_closedir(dirp);
  5536. IGNORE_UNUSED_RESULT(rmdir(dir));
  5537. }
  5538. return ok;
  5539. }
  5540. #endif
  5541. struct dir_scan_data {
  5542. struct de *entries;
  5543. unsigned int num_entries;
  5544. unsigned int arr_size;
  5545. };
  5546. /* Behaves like realloc(), but frees original pointer on failure */
  5547. static void *
  5548. realloc2(void *ptr, size_t size)
  5549. {
  5550. void *new_ptr = mg_realloc(ptr, size);
  5551. if (new_ptr == NULL) {
  5552. mg_free(ptr);
  5553. }
  5554. return new_ptr;
  5555. }
  5556. static void
  5557. dir_scan_callback(struct de *de, void *data)
  5558. {
  5559. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5560. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5561. dsd->arr_size *= 2;
  5562. dsd->entries =
  5563. (struct de *)realloc2(dsd->entries,
  5564. dsd->arr_size * sizeof(dsd->entries[0]));
  5565. }
  5566. if (dsd->entries == NULL) {
  5567. /* TODO(lsm, low): propagate an error to the caller */
  5568. dsd->num_entries = 0;
  5569. } else {
  5570. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5571. dsd->entries[dsd->num_entries].file = de->file;
  5572. dsd->entries[dsd->num_entries].conn = de->conn;
  5573. dsd->num_entries++;
  5574. }
  5575. }
  5576. static void
  5577. handle_directory_request(struct mg_connection *conn, const char *dir)
  5578. {
  5579. unsigned int i;
  5580. int sort_direction;
  5581. struct dir_scan_data data = {NULL, 0, 128};
  5582. char date[64];
  5583. time_t curtime = time(NULL);
  5584. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5585. send_http_error(conn,
  5586. 500,
  5587. "Error: Cannot open directory\nopendir(%s): %s",
  5588. dir,
  5589. strerror(ERRNO));
  5590. return;
  5591. }
  5592. gmt_time_string(date, sizeof(date), &curtime);
  5593. if (!conn) {
  5594. return;
  5595. }
  5596. sort_direction = ((conn->request_info.query_string != NULL)
  5597. && (conn->request_info.query_string[1] == 'd'))
  5598. ? 'a'
  5599. : 'd';
  5600. conn->must_close = 1;
  5601. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5602. send_static_cache_header(conn);
  5603. mg_printf(conn,
  5604. "Date: %s\r\n"
  5605. "Connection: close\r\n"
  5606. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5607. date);
  5608. conn->num_bytes_sent +=
  5609. mg_printf(conn,
  5610. "<html><head><title>Index of %s</title>"
  5611. "<style>th {text-align: left;}</style></head>"
  5612. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5613. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5614. "<th><a href=\"?d%c\">Modified</a></th>"
  5615. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5616. "<tr><td colspan=\"3\"><hr></td></tr>",
  5617. conn->request_info.local_uri,
  5618. conn->request_info.local_uri,
  5619. sort_direction,
  5620. sort_direction,
  5621. sort_direction);
  5622. /* Print first entry - link to a parent directory */
  5623. conn->num_bytes_sent +=
  5624. mg_printf(conn,
  5625. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5626. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5627. conn->request_info.local_uri,
  5628. "..",
  5629. "Parent directory",
  5630. "-",
  5631. "-");
  5632. /* Sort and print directory entries */
  5633. if (data.entries != NULL) {
  5634. qsort(data.entries,
  5635. (size_t)data.num_entries,
  5636. sizeof(data.entries[0]),
  5637. compare_dir_entries);
  5638. for (i = 0; i < data.num_entries; i++) {
  5639. print_dir_entry(&data.entries[i]);
  5640. mg_free(data.entries[i].file_name);
  5641. }
  5642. mg_free(data.entries);
  5643. }
  5644. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5645. conn->status_code = 200;
  5646. }
  5647. /* Send len bytes from the opened file to the client. */
  5648. static void
  5649. send_file_data(struct mg_connection *conn,
  5650. struct file *filep,
  5651. int64_t offset,
  5652. int64_t len)
  5653. {
  5654. char buf[MG_BUF_LEN];
  5655. int to_read, num_read, num_written;
  5656. int64_t size;
  5657. if (!filep || !conn) {
  5658. return;
  5659. }
  5660. /* Sanity check the offset */
  5661. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5662. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5663. if (len > 0 && filep->membuf != NULL && size > 0) {
  5664. /* file stored in memory */
  5665. if (len > size - offset) {
  5666. len = size - offset;
  5667. }
  5668. mg_write(conn, filep->membuf + offset, (size_t)len);
  5669. } else if (len > 0 && filep->fp != NULL) {
  5670. /* file stored on disk */
  5671. #if defined(__linux__)
  5672. /* sendfile is only available for Linux */
  5673. if (conn->throttle == 0 && conn->ssl == 0) {
  5674. off_t sf_offs = (off_t)offset;
  5675. ssize_t sf_sent;
  5676. int sf_file = fileno(filep->fp);
  5677. int loop_cnt = 0;
  5678. do {
  5679. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5680. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5681. size_t sf_tosend =
  5682. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5683. sf_sent =
  5684. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5685. if (sf_sent > 0) {
  5686. conn->num_bytes_sent += sf_sent;
  5687. len -= sf_sent;
  5688. offset += sf_sent;
  5689. } else if (loop_cnt == 0) {
  5690. /* This file can not be sent using sendfile.
  5691. * This might be the case for pseudo-files in the
  5692. * /sys/ and /proc/ file system.
  5693. * Use the regular user mode copy code instead. */
  5694. break;
  5695. } else if (sf_sent == 0) {
  5696. /* No error, but 0 bytes sent. May be EOF? */
  5697. return;
  5698. }
  5699. loop_cnt++;
  5700. } while ((len > 0) && (sf_sent >= 0));
  5701. if (sf_sent > 0) {
  5702. return; /* OK */
  5703. }
  5704. /* sf_sent<0 means error, thus fall back to the classic way */
  5705. /* This is always the case, if sf_file is not a "normal" file,
  5706. * e.g., for sending data from the output of a CGI process. */
  5707. offset = (int64_t)sf_offs;
  5708. }
  5709. #endif
  5710. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5711. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5712. send_http_error(
  5713. conn,
  5714. 500,
  5715. "%s",
  5716. "Error: Unable to access file at requested position.");
  5717. } else {
  5718. while (len > 0) {
  5719. /* Calculate how much to read from the file in the buffer */
  5720. to_read = sizeof(buf);
  5721. if ((int64_t)to_read > len) {
  5722. to_read = (int)len;
  5723. }
  5724. /* Read from file, exit the loop on error */
  5725. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5726. <= 0) {
  5727. break;
  5728. }
  5729. /* Send read bytes to the client, exit the loop on error */
  5730. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5731. != num_read) {
  5732. break;
  5733. }
  5734. /* Both read and were successful, adjust counters */
  5735. conn->num_bytes_sent += num_written;
  5736. len -= num_written;
  5737. }
  5738. }
  5739. }
  5740. }
  5741. static int
  5742. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5743. {
  5744. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5745. }
  5746. static void
  5747. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5748. {
  5749. if (filep != NULL && buf != NULL) {
  5750. mg_snprintf(NULL,
  5751. NULL, /* All calls to construct_etag use 64 byte buffer */
  5752. buf,
  5753. buf_len,
  5754. "\"%lx.%" INT64_FMT "\"",
  5755. (unsigned long)filep->last_modified,
  5756. filep->size);
  5757. }
  5758. }
  5759. static void
  5760. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5761. {
  5762. if (filep != NULL && filep->fp != NULL) {
  5763. #ifdef _WIN32
  5764. (void)conn; /* Unused. */
  5765. #else
  5766. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5767. mg_cry(conn,
  5768. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5769. __func__,
  5770. strerror(ERRNO));
  5771. }
  5772. #endif
  5773. }
  5774. }
  5775. static void
  5776. handle_static_file_request(struct mg_connection *conn,
  5777. const char *path,
  5778. struct file *filep,
  5779. const char *mime_type)
  5780. {
  5781. char date[64], lm[64], etag[64];
  5782. char range[128]; /* large enough, so there will be no overflow */
  5783. const char *msg = "OK", *hdr;
  5784. time_t curtime = time(NULL);
  5785. int64_t cl, r1, r2;
  5786. struct vec mime_vec;
  5787. int n, truncated;
  5788. char gz_path[PATH_MAX];
  5789. const char *encoding = "";
  5790. const char *cors1, *cors2, *cors3;
  5791. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5792. return;
  5793. }
  5794. if (mime_type == NULL) {
  5795. get_mime_type(conn->ctx, path, &mime_vec);
  5796. } else {
  5797. mime_vec.ptr = mime_type;
  5798. mime_vec.len = strlen(mime_type);
  5799. }
  5800. if (filep->size > INT64_MAX) {
  5801. send_http_error(conn,
  5802. 500,
  5803. "Error: File size is too large to send\n%" INT64_FMT,
  5804. filep->size);
  5805. }
  5806. cl = (int64_t)filep->size;
  5807. conn->status_code = 200;
  5808. range[0] = '\0';
  5809. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5810. * it's important to rewrite the filename after resolving
  5811. * the mime type from it, to preserve the actual file's type */
  5812. if (filep->gzipped) {
  5813. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5814. if (truncated) {
  5815. send_http_error(conn,
  5816. 500,
  5817. "Error: Path of zipped file too long (%s)",
  5818. path);
  5819. return;
  5820. }
  5821. path = gz_path;
  5822. encoding = "Content-Encoding: gzip\r\n";
  5823. }
  5824. if (!mg_fopen(conn, path, "rb", filep)) {
  5825. send_http_error(conn,
  5826. 500,
  5827. "Error: Cannot open file\nfopen(%s): %s",
  5828. path,
  5829. strerror(ERRNO));
  5830. return;
  5831. }
  5832. fclose_on_exec(filep, conn);
  5833. /* If Range: header specified, act accordingly */
  5834. r1 = r2 = 0;
  5835. hdr = mg_get_header(conn, "Range");
  5836. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5837. && r2 >= 0) {
  5838. /* actually, range requests don't play well with a pre-gzipped
  5839. * file (since the range is specified in the uncompressed space) */
  5840. if (filep->gzipped) {
  5841. send_http_error(
  5842. conn,
  5843. 501,
  5844. "%s",
  5845. "Error: Range requests in gzipped files are not supported");
  5846. mg_fclose(filep);
  5847. return;
  5848. }
  5849. conn->status_code = 206;
  5850. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5851. mg_snprintf(conn,
  5852. NULL, /* range buffer is big enough */
  5853. range,
  5854. sizeof(range),
  5855. "Content-Range: bytes "
  5856. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5857. r1,
  5858. r1 + cl - 1,
  5859. filep->size);
  5860. msg = "Partial Content";
  5861. }
  5862. hdr = mg_get_header(conn, "Origin");
  5863. if (hdr) {
  5864. /* Cross-origin resource sharing (CORS), see
  5865. * http://www.html5rocks.com/en/tutorials/cors/,
  5866. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5867. * preflight is not supported for files. */
  5868. cors1 = "Access-Control-Allow-Origin: ";
  5869. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5870. cors3 = "\r\n";
  5871. } else {
  5872. cors1 = cors2 = cors3 = "";
  5873. }
  5874. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5875. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5876. gmt_time_string(date, sizeof(date), &curtime);
  5877. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5878. construct_etag(etag, sizeof(etag), filep);
  5879. (void)mg_printf(conn,
  5880. "HTTP/1.1 %d %s\r\n"
  5881. "%s%s%s"
  5882. "Date: %s\r\n",
  5883. conn->status_code,
  5884. msg,
  5885. cors1,
  5886. cors2,
  5887. cors3,
  5888. date);
  5889. send_static_cache_header(conn);
  5890. (void)mg_printf(conn,
  5891. "Last-Modified: %s\r\n"
  5892. "Etag: %s\r\n"
  5893. "Content-Type: %.*s\r\n"
  5894. "Content-Length: %" INT64_FMT "\r\n"
  5895. "Connection: %s\r\n"
  5896. "Accept-Ranges: bytes\r\n"
  5897. "%s%s\r\n",
  5898. lm,
  5899. etag,
  5900. (int)mime_vec.len,
  5901. mime_vec.ptr,
  5902. cl,
  5903. suggest_connection_header(conn),
  5904. range,
  5905. encoding);
  5906. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5907. send_file_data(conn, filep, r1, cl);
  5908. }
  5909. mg_fclose(filep);
  5910. }
  5911. #if !defined(NO_CACHING)
  5912. static void
  5913. handle_not_modified_static_file_request(struct mg_connection *conn,
  5914. struct file *filep)
  5915. {
  5916. char date[64], lm[64], etag[64];
  5917. time_t curtime = time(NULL);
  5918. if (conn == NULL || filep == NULL) {
  5919. return;
  5920. }
  5921. conn->status_code = 304;
  5922. gmt_time_string(date, sizeof(date), &curtime);
  5923. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5924. construct_etag(etag, sizeof(etag), filep);
  5925. (void)mg_printf(conn,
  5926. "HTTP/1.1 %d %s\r\n"
  5927. "Date: %s\r\n",
  5928. conn->status_code,
  5929. mg_get_response_code_text(conn, conn->status_code),
  5930. date);
  5931. send_static_cache_header(conn);
  5932. (void)mg_printf(conn,
  5933. "Last-Modified: %s\r\n"
  5934. "Etag: %s\r\n"
  5935. "Connection: %s\r\n"
  5936. "\r\n",
  5937. lm,
  5938. etag,
  5939. suggest_connection_header(conn));
  5940. }
  5941. #endif
  5942. void
  5943. mg_send_file(struct mg_connection *conn, const char *path)
  5944. {
  5945. mg_send_mime_file(conn, path, NULL);
  5946. }
  5947. void
  5948. mg_send_mime_file(struct mg_connection *conn,
  5949. const char *path,
  5950. const char *mime_type)
  5951. {
  5952. struct file file = STRUCT_FILE_INITIALIZER;
  5953. if (mg_stat(conn, path, &file)) {
  5954. if (file.is_directory) {
  5955. if (!conn) {
  5956. return;
  5957. }
  5958. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5959. "yes")) {
  5960. handle_directory_request(conn, path);
  5961. } else {
  5962. send_http_error(conn,
  5963. 403,
  5964. "%s",
  5965. "Error: Directory listing denied");
  5966. }
  5967. } else {
  5968. handle_static_file_request(conn, path, &file, mime_type);
  5969. }
  5970. } else {
  5971. send_http_error(conn, 404, "%s", "Error: File not found");
  5972. }
  5973. }
  5974. /* For a given PUT path, create all intermediate subdirectories.
  5975. * Return 0 if the path itself is a directory.
  5976. * Return 1 if the path leads to a file.
  5977. * Return -1 for if the path is too long.
  5978. * Return -2 if path can not be created.
  5979. */
  5980. static int
  5981. put_dir(struct mg_connection *conn, const char *path)
  5982. {
  5983. char buf[PATH_MAX];
  5984. const char *s, *p;
  5985. struct file file = STRUCT_FILE_INITIALIZER;
  5986. size_t len;
  5987. int res = 1;
  5988. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5989. len = (size_t)(p - path);
  5990. if (len >= sizeof(buf)) {
  5991. /* path too long */
  5992. res = -1;
  5993. break;
  5994. }
  5995. memcpy(buf, path, len);
  5996. buf[len] = '\0';
  5997. /* Try to create intermediate directory */
  5998. DEBUG_TRACE("mkdir(%s)", buf);
  5999. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6000. /* path does not exixt and can not be created */
  6001. res = -2;
  6002. break;
  6003. }
  6004. /* Is path itself a directory? */
  6005. if (p[1] == '\0') {
  6006. res = 0;
  6007. }
  6008. }
  6009. return res;
  6010. }
  6011. static void
  6012. remove_bad_file(const struct mg_connection *conn, const char *path)
  6013. {
  6014. int r = mg_remove(conn, path);
  6015. if (r != 0) {
  6016. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6017. }
  6018. }
  6019. long long
  6020. mg_store_body(struct mg_connection *conn, const char *path)
  6021. {
  6022. char buf[MG_BUF_LEN];
  6023. long long len = 0;
  6024. int ret, n;
  6025. struct file fi;
  6026. if (conn->consumed_content != 0) {
  6027. mg_cry(conn, "%s: Contents already consumed", __func__);
  6028. return -11;
  6029. }
  6030. ret = put_dir(conn, path);
  6031. if (ret < 0) {
  6032. /* -1 for path too long,
  6033. * -2 for path can not be created. */
  6034. return ret;
  6035. }
  6036. if (ret != 1) {
  6037. /* Return 0 means, path itself is a directory. */
  6038. return 0;
  6039. }
  6040. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6041. return -12;
  6042. }
  6043. ret = mg_read(conn, buf, sizeof(buf));
  6044. while (ret > 0) {
  6045. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6046. if (n != ret) {
  6047. mg_fclose(&fi);
  6048. remove_bad_file(conn, path);
  6049. return -13;
  6050. }
  6051. ret = mg_read(conn, buf, sizeof(buf));
  6052. }
  6053. /* TODO: mg_fclose should return an error,
  6054. * and every caller should check and handle it. */
  6055. if (fclose(fi.fp) != 0) {
  6056. remove_bad_file(conn, path);
  6057. return -14;
  6058. }
  6059. return len;
  6060. }
  6061. /* Parse HTTP headers from the given buffer, advance buf pointer
  6062. * to the point where parsing stopped.
  6063. * All parameters must be valid pointers (not NULL).
  6064. * Return <0 on error. */
  6065. static int
  6066. parse_http_headers(char **buf, struct mg_request_info *ri)
  6067. {
  6068. int i;
  6069. ri->num_headers = 0;
  6070. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6071. char *dp = *buf;
  6072. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6073. dp++;
  6074. }
  6075. if (dp == *buf) {
  6076. /* End of headers reached. */
  6077. break;
  6078. }
  6079. if (*dp != ':') {
  6080. /* This is not a valid field. */
  6081. return -1;
  6082. }
  6083. /* End of header key (*dp == ':') */
  6084. /* Truncate here and set the key name */
  6085. *dp = 0;
  6086. ri->http_headers[i].name = *buf;
  6087. do {
  6088. dp++;
  6089. } while (*dp == ' ');
  6090. /* The rest of the line is the value */
  6091. ri->http_headers[i].value = dp;
  6092. *buf = dp + strcspn(dp, "\r\n");
  6093. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6094. *buf = NULL;
  6095. }
  6096. ri->num_headers = i + 1;
  6097. if (*buf) {
  6098. (*buf)[0] = 0;
  6099. (*buf)[1] = 0;
  6100. *buf += 2;
  6101. } else {
  6102. *buf = dp;
  6103. break;
  6104. }
  6105. if ((*buf)[0] == '\r') {
  6106. /* This is the end of the header */
  6107. break;
  6108. }
  6109. }
  6110. return ri->num_headers;
  6111. }
  6112. static int
  6113. is_valid_http_method(const char *method)
  6114. {
  6115. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6116. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6117. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6118. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6119. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6120. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6121. /* TRACE method (RFC 2616) is not supported for security reasons */
  6122. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6123. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6124. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6125. /* Unsupported WEBDAV Methods: */
  6126. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6127. /* + 11 methods from RFC 3253 */
  6128. /* ORDERPATCH (RFC 3648) */
  6129. /* ACL (RFC 3744) */
  6130. /* SEARCH (RFC 5323) */
  6131. /* + MicroSoft extensions
  6132. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6133. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6134. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6135. }
  6136. /* Parse HTTP request, fill in mg_request_info structure.
  6137. * This function modifies the buffer by NUL-terminating
  6138. * HTTP request components, header names and header values.
  6139. * Parameters:
  6140. * buf (in/out): pointer to the HTTP header to parse and split
  6141. * len (in): length of HTTP header buffer
  6142. * re (out): parsed header as mg_request_info
  6143. * buf and ri must be valid pointers (not NULL), len>0.
  6144. * Returns <0 on error. */
  6145. static int
  6146. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6147. {
  6148. int is_request, request_length;
  6149. char *start_line;
  6150. request_length = get_request_len(buf, len);
  6151. if (request_length > 0) {
  6152. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6153. * remote_port */
  6154. ri->remote_user = ri->request_method = ri->request_uri =
  6155. ri->http_version = NULL;
  6156. ri->num_headers = 0;
  6157. buf[request_length - 1] = '\0';
  6158. /* RFC says that all initial whitespaces should be ingored */
  6159. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6160. buf++;
  6161. }
  6162. start_line = skip(&buf, "\r\n");
  6163. ri->request_method = skip(&start_line, " ");
  6164. ri->request_uri = skip(&start_line, " ");
  6165. ri->http_version = start_line;
  6166. /* HTTP message could be either HTTP request:
  6167. * "GET / HTTP/1.0 ..."
  6168. * or a HTTP response:
  6169. * "HTTP/1.0 200 OK ..."
  6170. * otherwise it is invalid.
  6171. */
  6172. is_request = is_valid_http_method(ri->request_method);
  6173. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6174. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6175. /* Not a valid request or response: invalid */
  6176. return -1;
  6177. }
  6178. if (is_request) {
  6179. ri->http_version += 5;
  6180. }
  6181. if (parse_http_headers(&buf, ri) < 0) {
  6182. /* Error while parsing headers */
  6183. return -1;
  6184. }
  6185. }
  6186. return request_length;
  6187. }
  6188. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6189. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6190. * buffer (which marks the end of HTTP request). Buffer buf may already
  6191. * have some data. The length of the data is stored in nread.
  6192. * Upon every read operation, increase nread by the number of bytes read. */
  6193. static int
  6194. read_request(FILE *fp,
  6195. struct mg_connection *conn,
  6196. char *buf,
  6197. int bufsiz,
  6198. int *nread)
  6199. {
  6200. int request_len, n = 0;
  6201. struct timespec last_action_time;
  6202. double request_timeout;
  6203. if (!conn) {
  6204. return 0;
  6205. }
  6206. memset(&last_action_time, 0, sizeof(last_action_time));
  6207. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6208. /* value of request_timeout is in seconds, config in milliseconds */
  6209. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6210. } else {
  6211. request_timeout = -1.0;
  6212. }
  6213. request_len = get_request_len(buf, *nread);
  6214. /* first time reading from this connection */
  6215. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6216. while (
  6217. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6218. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6219. <= request_timeout) || (request_timeout < 0))
  6220. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6221. > 0)) {
  6222. *nread += n;
  6223. /* assert(*nread <= bufsiz); */
  6224. if (*nread > bufsiz) {
  6225. return -2;
  6226. }
  6227. request_len = get_request_len(buf, *nread);
  6228. if (request_timeout > 0.0) {
  6229. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6230. }
  6231. }
  6232. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6233. }
  6234. #if !defined(NO_FILES)
  6235. /* For given directory path, substitute it to valid index file.
  6236. * Return 1 if index file has been found, 0 if not found.
  6237. * If the file is found, it's stats is returned in stp. */
  6238. static int
  6239. substitute_index_file(struct mg_connection *conn,
  6240. char *path,
  6241. size_t path_len,
  6242. struct file *filep)
  6243. {
  6244. if (conn && conn->ctx) {
  6245. const char *list = conn->ctx->config[INDEX_FILES];
  6246. struct file file = STRUCT_FILE_INITIALIZER;
  6247. struct vec filename_vec;
  6248. size_t n = strlen(path);
  6249. int found = 0;
  6250. /* The 'path' given to us points to the directory. Remove all trailing
  6251. * directory separator characters from the end of the path, and
  6252. * then append single directory separator character. */
  6253. while (n > 0 && path[n - 1] == '/') {
  6254. n--;
  6255. }
  6256. path[n] = '/';
  6257. /* Traverse index files list. For each entry, append it to the given
  6258. * path and see if the file exists. If it exists, break the loop */
  6259. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6260. /* Ignore too long entries that may overflow path buffer */
  6261. if (filename_vec.len > path_len - (n + 2)) {
  6262. continue;
  6263. }
  6264. /* Prepare full path to the index file */
  6265. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6266. /* Does it exist? */
  6267. if (mg_stat(conn, path, &file)) {
  6268. /* Yes it does, break the loop */
  6269. *filep = file;
  6270. found = 1;
  6271. break;
  6272. }
  6273. }
  6274. /* If no index file exists, restore directory path */
  6275. if (!found) {
  6276. path[n] = '\0';
  6277. }
  6278. return found;
  6279. }
  6280. return 0;
  6281. }
  6282. #endif
  6283. #if !defined(NO_CACHING)
  6284. /* Return True if we should reply 304 Not Modified. */
  6285. static int
  6286. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6287. {
  6288. char etag[64];
  6289. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6290. const char *inm = mg_get_header(conn, "If-None-Match");
  6291. construct_etag(etag, sizeof(etag), filep);
  6292. if (!filep) {
  6293. return 0;
  6294. }
  6295. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6296. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6297. }
  6298. #endif /* !NO_CACHING */
  6299. #if !defined(NO_CGI) || !defined(NO_FILES)
  6300. static int
  6301. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6302. {
  6303. const char *expect, *body;
  6304. char buf[MG_BUF_LEN];
  6305. int to_read, nread, success = 0;
  6306. int64_t buffered_len;
  6307. double timeout = -1.0;
  6308. if (!conn) {
  6309. return 0;
  6310. }
  6311. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6312. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6313. }
  6314. expect = mg_get_header(conn, "Expect");
  6315. /* assert(fp != NULL); */
  6316. if (!fp) {
  6317. send_http_error(conn, 500, "%s", "Error: NULL File");
  6318. return 0;
  6319. }
  6320. if (conn->content_len == -1 && !conn->is_chunked) {
  6321. /* Content length is not specified by the client. */
  6322. send_http_error(conn,
  6323. 411,
  6324. "%s",
  6325. "Error: Client did not specify content length");
  6326. } else if ((expect != NULL)
  6327. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6328. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6329. send_http_error(conn,
  6330. 417,
  6331. "Error: Can not fulfill expectation %s",
  6332. expect);
  6333. } else {
  6334. if (expect != NULL) {
  6335. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6336. conn->status_code = 100;
  6337. } else {
  6338. conn->status_code = 200;
  6339. }
  6340. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6341. - conn->consumed_content;
  6342. /* assert(buffered_len >= 0); */
  6343. /* assert(conn->consumed_content == 0); */
  6344. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6345. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6346. return 0;
  6347. }
  6348. if (buffered_len > 0) {
  6349. if ((int64_t)buffered_len > conn->content_len) {
  6350. buffered_len = (int)conn->content_len;
  6351. }
  6352. body = conn->buf + conn->request_len + conn->consumed_content;
  6353. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6354. conn->consumed_content += buffered_len;
  6355. }
  6356. nread = 0;
  6357. while (conn->consumed_content < conn->content_len) {
  6358. to_read = sizeof(buf);
  6359. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6360. to_read = (int)(conn->content_len - conn->consumed_content);
  6361. }
  6362. nread = pull(NULL, conn, buf, to_read, timeout);
  6363. if (nread <= 0
  6364. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6365. break;
  6366. }
  6367. conn->consumed_content += nread;
  6368. }
  6369. if (conn->consumed_content == conn->content_len) {
  6370. success = (nread >= 0);
  6371. }
  6372. /* Each error code path in this function must send an error */
  6373. if (!success) {
  6374. /* NOTE: Maybe some data has already been sent. */
  6375. /* TODO (low): If some data has been sent, a correct error
  6376. * reply can no longer be sent, so just close the connection */
  6377. send_http_error(conn, 500, "%s", "");
  6378. }
  6379. }
  6380. return success;
  6381. }
  6382. #endif
  6383. #if !defined(NO_CGI)
  6384. /* This structure helps to create an environment for the spawned CGI program.
  6385. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6386. * last element must be NULL.
  6387. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6388. * strings must reside in a contiguous buffer. The end of the buffer is
  6389. * marked by two '\0' characters.
  6390. * We satisfy both worlds: we create an envp array (which is vars), all
  6391. * entries are actually pointers inside buf. */
  6392. struct cgi_environment {
  6393. struct mg_connection *conn;
  6394. /* Data block */
  6395. char *buf; /* Environment buffer */
  6396. size_t buflen; /* Space available in buf */
  6397. size_t bufused; /* Space taken in buf */
  6398. /* Index block */
  6399. char **var; /* char **envp */
  6400. size_t varlen; /* Number of variables available in var */
  6401. size_t varused; /* Number of variables stored in var */
  6402. };
  6403. static void addenv(struct cgi_environment *env,
  6404. PRINTF_FORMAT_STRING(const char *fmt),
  6405. ...) PRINTF_ARGS(2, 3);
  6406. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6407. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6408. static void
  6409. addenv(struct cgi_environment *env, const char *fmt, ...)
  6410. {
  6411. size_t n, space;
  6412. int truncated;
  6413. char *added;
  6414. va_list ap;
  6415. /* Calculate how much space is left in the buffer */
  6416. space = (env->buflen - env->bufused);
  6417. /* Calculate an estimate for the required space */
  6418. n = strlen(fmt) + 2 + 128;
  6419. do {
  6420. if (space <= n) {
  6421. /* Allocate new buffer */
  6422. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6423. added = (char *)mg_realloc(env->buf, n);
  6424. if (!added) {
  6425. /* Out of memory */
  6426. mg_cry(env->conn,
  6427. "%s: Cannot allocate memory for CGI variable [%s]",
  6428. __func__,
  6429. fmt);
  6430. return;
  6431. }
  6432. env->buf = added;
  6433. env->buflen = n;
  6434. space = (env->buflen - env->bufused);
  6435. }
  6436. /* Make a pointer to the free space int the buffer */
  6437. added = env->buf + env->bufused;
  6438. /* Copy VARIABLE=VALUE\0 string into the free space */
  6439. va_start(ap, fmt);
  6440. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6441. va_end(ap);
  6442. /* Do not add truncated strings to the environment */
  6443. if (truncated) {
  6444. /* Reallocate the buffer */
  6445. space = 0;
  6446. n = 1;
  6447. }
  6448. } while (truncated);
  6449. /* Calculate number of bytes added to the environment */
  6450. n = strlen(added) + 1;
  6451. env->bufused += n;
  6452. /* Now update the variable index */
  6453. space = (env->varlen - env->varused);
  6454. if (space < 2) {
  6455. mg_cry(env->conn,
  6456. "%s: Cannot register CGI variable [%s]",
  6457. __func__,
  6458. fmt);
  6459. return;
  6460. }
  6461. /* Append a pointer to the added string into the envp array */
  6462. env->var[env->varused] = added;
  6463. env->varused++;
  6464. }
  6465. static void
  6466. prepare_cgi_environment(struct mg_connection *conn,
  6467. const char *prog,
  6468. struct cgi_environment *env)
  6469. {
  6470. const char *s;
  6471. struct vec var_vec;
  6472. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6473. int i, truncated;
  6474. if (conn == NULL || prog == NULL || env == NULL) {
  6475. return;
  6476. }
  6477. env->conn = conn;
  6478. env->buflen = CGI_ENVIRONMENT_SIZE;
  6479. env->bufused = 0;
  6480. env->buf = (char *)mg_malloc(env->buflen);
  6481. env->varlen = MAX_CGI_ENVIR_VARS;
  6482. env->varused = 0;
  6483. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6484. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6485. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6486. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6487. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6488. /* Prepare the environment block */
  6489. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6490. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6491. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6492. #if defined(USE_IPV6)
  6493. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6494. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6495. } else
  6496. #endif
  6497. {
  6498. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6499. }
  6500. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6501. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6502. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6503. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6504. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6505. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6506. /* SCRIPT_NAME */
  6507. addenv(env,
  6508. "SCRIPT_NAME=%.*s",
  6509. (int)strlen(conn->request_info.local_uri)
  6510. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6511. conn->request_info.local_uri);
  6512. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6513. if (conn->path_info == NULL) {
  6514. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6515. } else {
  6516. addenv(env,
  6517. "PATH_TRANSLATED=%s%s",
  6518. conn->ctx->config[DOCUMENT_ROOT],
  6519. conn->path_info);
  6520. }
  6521. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6522. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6523. addenv(env, "CONTENT_TYPE=%s", s);
  6524. }
  6525. if (conn->request_info.query_string != NULL) {
  6526. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6527. }
  6528. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6529. addenv(env, "CONTENT_LENGTH=%s", s);
  6530. }
  6531. if ((s = getenv("PATH")) != NULL) {
  6532. addenv(env, "PATH=%s", s);
  6533. }
  6534. if (conn->path_info != NULL) {
  6535. addenv(env, "PATH_INFO=%s", conn->path_info);
  6536. }
  6537. if (conn->status_code > 0) {
  6538. /* CGI error handler should show the status code */
  6539. addenv(env, "STATUS=%d", conn->status_code);
  6540. }
  6541. #if defined(_WIN32)
  6542. if ((s = getenv("COMSPEC")) != NULL) {
  6543. addenv(env, "COMSPEC=%s", s);
  6544. }
  6545. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6546. addenv(env, "SYSTEMROOT=%s", s);
  6547. }
  6548. if ((s = getenv("SystemDrive")) != NULL) {
  6549. addenv(env, "SystemDrive=%s", s);
  6550. }
  6551. if ((s = getenv("ProgramFiles")) != NULL) {
  6552. addenv(env, "ProgramFiles=%s", s);
  6553. }
  6554. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6555. addenv(env, "ProgramFiles(x86)=%s", s);
  6556. }
  6557. #else
  6558. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6559. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6560. }
  6561. #endif /* _WIN32 */
  6562. if ((s = getenv("PERLLIB")) != NULL) {
  6563. addenv(env, "PERLLIB=%s", s);
  6564. }
  6565. if (conn->request_info.remote_user != NULL) {
  6566. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6567. addenv(env, "%s", "AUTH_TYPE=Digest");
  6568. }
  6569. /* Add all headers as HTTP_* variables */
  6570. for (i = 0; i < conn->request_info.num_headers; i++) {
  6571. (void)mg_snprintf(conn,
  6572. &truncated,
  6573. http_var_name,
  6574. sizeof(http_var_name),
  6575. "HTTP_%s",
  6576. conn->request_info.http_headers[i].name);
  6577. if (truncated) {
  6578. mg_cry(conn,
  6579. "%s: HTTP header variable too long [%s]",
  6580. __func__,
  6581. conn->request_info.http_headers[i].name);
  6582. continue;
  6583. }
  6584. /* Convert variable name into uppercase, and change - to _ */
  6585. for (p = http_var_name; *p != '\0'; p++) {
  6586. if (*p == '-') {
  6587. *p = '_';
  6588. }
  6589. *p = (char)toupper(*(unsigned char *)p);
  6590. }
  6591. addenv(env,
  6592. "%s=%s",
  6593. http_var_name,
  6594. conn->request_info.http_headers[i].value);
  6595. }
  6596. /* Add user-specified variables */
  6597. s = conn->ctx->config[CGI_ENVIRONMENT];
  6598. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6599. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6600. }
  6601. env->var[env->varused] = NULL;
  6602. env->buf[env->bufused] = '\0';
  6603. }
  6604. static void
  6605. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6606. {
  6607. char *buf;
  6608. size_t buflen;
  6609. int headers_len, data_len, i, truncated;
  6610. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6611. const char *status, *status_text, *connection_state;
  6612. char *pbuf, dir[PATH_MAX], *p;
  6613. struct mg_request_info ri;
  6614. struct cgi_environment blk;
  6615. FILE *in = NULL, *out = NULL, *err = NULL;
  6616. struct file fout = STRUCT_FILE_INITIALIZER;
  6617. pid_t pid = (pid_t)-1;
  6618. if (conn == NULL) {
  6619. return;
  6620. }
  6621. buf = NULL;
  6622. buflen = 16384;
  6623. prepare_cgi_environment(conn, prog, &blk);
  6624. /* CGI must be executed in its own directory. 'dir' must point to the
  6625. * directory containing executable program, 'p' must point to the
  6626. * executable program name relative to 'dir'. */
  6627. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6628. if (truncated) {
  6629. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6630. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6631. goto done;
  6632. }
  6633. if ((p = strrchr(dir, '/')) != NULL) {
  6634. *p++ = '\0';
  6635. } else {
  6636. dir[0] = '.', dir[1] = '\0';
  6637. p = (char *)prog;
  6638. }
  6639. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6640. status = strerror(ERRNO);
  6641. mg_cry(conn,
  6642. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6643. prog,
  6644. status);
  6645. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6646. goto done;
  6647. }
  6648. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6649. if (pid == (pid_t)-1) {
  6650. status = strerror(ERRNO);
  6651. mg_cry(conn,
  6652. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6653. prog,
  6654. status);
  6655. send_http_error(conn,
  6656. 500,
  6657. "Error: Cannot spawn CGI process [%s]: %s",
  6658. prog,
  6659. status);
  6660. goto done;
  6661. }
  6662. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6663. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6664. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6665. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6666. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6667. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6668. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6669. /* Parent closes only one side of the pipes.
  6670. * If we don't mark them as closed, close() attempt before
  6671. * return from this function throws an exception on Windows.
  6672. * Windows does not like when closed descriptor is closed again. */
  6673. (void)close(fdin[0]);
  6674. (void)close(fdout[1]);
  6675. (void)close(fderr[1]);
  6676. fdin[0] = fdout[1] = fderr[1] = -1;
  6677. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6678. status = strerror(ERRNO);
  6679. mg_cry(conn,
  6680. "Error: CGI program \"%s\": Can not open stdin: %s",
  6681. prog,
  6682. status);
  6683. send_http_error(conn,
  6684. 500,
  6685. "Error: CGI can not open fdin\nfopen: %s",
  6686. status);
  6687. goto done;
  6688. }
  6689. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6690. status = strerror(ERRNO);
  6691. mg_cry(conn,
  6692. "Error: CGI program \"%s\": Can not open stdout: %s",
  6693. prog,
  6694. status);
  6695. send_http_error(conn,
  6696. 500,
  6697. "Error: CGI can not open fdout\nfopen: %s",
  6698. status);
  6699. goto done;
  6700. }
  6701. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6702. status = strerror(ERRNO);
  6703. mg_cry(conn,
  6704. "Error: CGI program \"%s\": Can not open stderr: %s",
  6705. prog,
  6706. status);
  6707. send_http_error(conn,
  6708. 500,
  6709. "Error: CGI can not open fdout\nfopen: %s",
  6710. status);
  6711. goto done;
  6712. }
  6713. setbuf(in, NULL);
  6714. setbuf(out, NULL);
  6715. setbuf(err, NULL);
  6716. fout.fp = out;
  6717. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6718. /* This is a POST/PUT request, or another request with body data. */
  6719. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6720. /* Error sending the body data */
  6721. mg_cry(conn,
  6722. "Error: CGI program \"%s\": Forward body data failed",
  6723. prog);
  6724. goto done;
  6725. }
  6726. }
  6727. /* Close so child gets an EOF. */
  6728. fclose(in);
  6729. in = NULL;
  6730. fdin[1] = -1;
  6731. /* Now read CGI reply into a buffer. We need to set correct
  6732. * status code, thus we need to see all HTTP headers first.
  6733. * Do not send anything back to client, until we buffer in all
  6734. * HTTP headers. */
  6735. data_len = 0;
  6736. buf = (char *)mg_malloc(buflen);
  6737. if (buf == NULL) {
  6738. send_http_error(conn,
  6739. 500,
  6740. "Error: Not enough memory for CGI buffer (%u bytes)",
  6741. (unsigned int)buflen);
  6742. mg_cry(conn,
  6743. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6744. "bytes)",
  6745. prog,
  6746. (unsigned int)buflen);
  6747. goto done;
  6748. }
  6749. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6750. if (headers_len <= 0) {
  6751. /* Could not parse the CGI response. Check if some error message on
  6752. * stderr. */
  6753. i = pull_all(err, conn, buf, (int)buflen);
  6754. if (i > 0) {
  6755. mg_cry(conn,
  6756. "Error: CGI program \"%s\" sent error "
  6757. "message: [%.*s]",
  6758. prog,
  6759. i,
  6760. buf);
  6761. send_http_error(conn,
  6762. 500,
  6763. "Error: CGI program \"%s\" sent error "
  6764. "message: [%.*s]",
  6765. prog,
  6766. i,
  6767. buf);
  6768. } else {
  6769. mg_cry(conn,
  6770. "Error: CGI program sent malformed or too big "
  6771. "(>%u bytes) HTTP headers: [%.*s]",
  6772. (unsigned)buflen,
  6773. data_len,
  6774. buf);
  6775. send_http_error(conn,
  6776. 500,
  6777. "Error: CGI program sent malformed or too big "
  6778. "(>%u bytes) HTTP headers: [%.*s]",
  6779. (unsigned)buflen,
  6780. data_len,
  6781. buf);
  6782. }
  6783. goto done;
  6784. }
  6785. pbuf = buf;
  6786. buf[headers_len - 1] = '\0';
  6787. parse_http_headers(&pbuf, &ri);
  6788. /* Make up and send the status line */
  6789. status_text = "OK";
  6790. if ((status = get_header(&ri, "Status")) != NULL) {
  6791. conn->status_code = atoi(status);
  6792. status_text = status;
  6793. while (isdigit(*(const unsigned char *)status_text)
  6794. || *status_text == ' ') {
  6795. status_text++;
  6796. }
  6797. } else if (get_header(&ri, "Location") != NULL) {
  6798. conn->status_code = 302;
  6799. } else {
  6800. conn->status_code = 200;
  6801. }
  6802. connection_state = get_header(&ri, "Connection");
  6803. if (!header_has_option(connection_state, "keep-alive")) {
  6804. conn->must_close = 1;
  6805. }
  6806. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6807. /* Send headers */
  6808. for (i = 0; i < ri.num_headers; i++) {
  6809. mg_printf(conn,
  6810. "%s: %s\r\n",
  6811. ri.http_headers[i].name,
  6812. ri.http_headers[i].value);
  6813. }
  6814. mg_write(conn, "\r\n", 2);
  6815. /* Send chunk of data that may have been read after the headers */
  6816. conn->num_bytes_sent +=
  6817. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6818. /* Read the rest of CGI output and send to the client */
  6819. send_file_data(conn, &fout, 0, INT64_MAX);
  6820. done:
  6821. mg_free(blk.var);
  6822. mg_free(blk.buf);
  6823. if (pid != (pid_t)-1) {
  6824. kill(pid, SIGKILL);
  6825. #if !defined(_WIN32)
  6826. {
  6827. int st;
  6828. while (waitpid(pid, &st, 0) != -1)
  6829. ; /* clean zombies */
  6830. }
  6831. #endif
  6832. }
  6833. if (fdin[0] != -1) {
  6834. close(fdin[0]);
  6835. }
  6836. if (fdout[1] != -1) {
  6837. close(fdout[1]);
  6838. }
  6839. if (in != NULL) {
  6840. fclose(in);
  6841. } else if (fdin[1] != -1) {
  6842. close(fdin[1]);
  6843. }
  6844. if (out != NULL) {
  6845. fclose(out);
  6846. } else if (fdout[0] != -1) {
  6847. close(fdout[0]);
  6848. }
  6849. if (err != NULL) {
  6850. fclose(err);
  6851. } else if (fderr[0] != -1) {
  6852. close(fderr[0]);
  6853. }
  6854. if (buf != NULL) {
  6855. mg_free(buf);
  6856. }
  6857. }
  6858. #endif /* !NO_CGI */
  6859. #if !defined(NO_FILES)
  6860. static void
  6861. mkcol(struct mg_connection *conn, const char *path)
  6862. {
  6863. int rc, body_len;
  6864. struct de de;
  6865. char date[64];
  6866. time_t curtime = time(NULL);
  6867. if (conn == NULL) {
  6868. return;
  6869. }
  6870. /* TODO (mid): Check the send_http_error situations in this function */
  6871. memset(&de.file, 0, sizeof(de.file));
  6872. if (!mg_stat(conn, path, &de.file)) {
  6873. mg_cry(conn,
  6874. "%s: mg_stat(%s) failed: %s",
  6875. __func__,
  6876. path,
  6877. strerror(ERRNO));
  6878. }
  6879. if (de.file.last_modified) {
  6880. /* TODO (high): This check does not seem to make any sense ! */
  6881. send_http_error(
  6882. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6883. return;
  6884. }
  6885. body_len = conn->data_len - conn->request_len;
  6886. if (body_len > 0) {
  6887. send_http_error(
  6888. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6889. return;
  6890. }
  6891. rc = mg_mkdir(conn, path, 0755);
  6892. if (rc == 0) {
  6893. conn->status_code = 201;
  6894. gmt_time_string(date, sizeof(date), &curtime);
  6895. mg_printf(conn,
  6896. "HTTP/1.1 %d Created\r\n"
  6897. "Date: %s\r\n",
  6898. conn->status_code,
  6899. date);
  6900. send_static_cache_header(conn);
  6901. mg_printf(conn,
  6902. "Content-Length: 0\r\n"
  6903. "Connection: %s\r\n\r\n",
  6904. suggest_connection_header(conn));
  6905. } else if (rc == -1) {
  6906. if (errno == EEXIST) {
  6907. send_http_error(
  6908. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6909. } else if (errno == EACCES) {
  6910. send_http_error(
  6911. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6912. } else if (errno == ENOENT) {
  6913. send_http_error(
  6914. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6915. } else {
  6916. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6917. }
  6918. }
  6919. }
  6920. static void
  6921. put_file(struct mg_connection *conn, const char *path)
  6922. {
  6923. struct file file = STRUCT_FILE_INITIALIZER;
  6924. const char *range;
  6925. int64_t r1, r2;
  6926. int rc;
  6927. char date[64];
  6928. time_t curtime = time(NULL);
  6929. if (conn == NULL) {
  6930. return;
  6931. }
  6932. if (mg_stat(conn, path, &file)) {
  6933. /* File already exists */
  6934. conn->status_code = 200;
  6935. if (file.is_directory) {
  6936. /* This is an already existing directory,
  6937. * so there is nothing to do for the server. */
  6938. rc = 0;
  6939. } else {
  6940. /* File exists and is not a directory. */
  6941. /* Can it be replaced? */
  6942. if (file.membuf != NULL) {
  6943. /* This is an "in-memory" file, that can not be replaced */
  6944. send_http_error(
  6945. conn,
  6946. 405,
  6947. "Error: Put not possible\nReplacing %s is not supported",
  6948. path);
  6949. return;
  6950. }
  6951. /* Check if the server may write this file */
  6952. if (access(path, W_OK) == 0) {
  6953. /* Access granted */
  6954. conn->status_code = 200;
  6955. rc = 1;
  6956. } else {
  6957. send_http_error(
  6958. conn,
  6959. 403,
  6960. "Error: Put not possible\nReplacing %s is not allowed",
  6961. path);
  6962. return;
  6963. }
  6964. }
  6965. } else {
  6966. /* File should be created */
  6967. conn->status_code = 201;
  6968. rc = put_dir(conn, path);
  6969. }
  6970. if (rc == 0) {
  6971. /* put_dir returns 0 if path is a directory */
  6972. gmt_time_string(date, sizeof(date), &curtime);
  6973. mg_printf(conn,
  6974. "HTTP/1.1 %d %s\r\n",
  6975. conn->status_code,
  6976. mg_get_response_code_text(NULL, conn->status_code));
  6977. send_no_cache_header(conn);
  6978. mg_printf(conn,
  6979. "Date: %s\r\n"
  6980. "Content-Length: 0\r\n"
  6981. "Connection: %s\r\n\r\n",
  6982. date,
  6983. suggest_connection_header(conn));
  6984. /* Request to create a directory has been fulfilled successfully.
  6985. * No need to put a file. */
  6986. return;
  6987. }
  6988. if (rc == -1) {
  6989. /* put_dir returns -1 if the path is too long */
  6990. send_http_error(conn,
  6991. 414,
  6992. "Error: Path too long\nput_dir(%s): %s",
  6993. path,
  6994. strerror(ERRNO));
  6995. return;
  6996. }
  6997. if (rc == -2) {
  6998. /* put_dir returns -2 if the directory can not be created */
  6999. send_http_error(conn,
  7000. 500,
  7001. "Error: Can not create directory\nput_dir(%s): %s",
  7002. path,
  7003. strerror(ERRNO));
  7004. return;
  7005. }
  7006. /* A file should be created or overwritten. */
  7007. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7008. mg_fclose(&file);
  7009. send_http_error(conn,
  7010. 500,
  7011. "Error: Can not create file\nfopen(%s): %s",
  7012. path,
  7013. strerror(ERRNO));
  7014. return;
  7015. }
  7016. fclose_on_exec(&file, conn);
  7017. range = mg_get_header(conn, "Content-Range");
  7018. r1 = r2 = 0;
  7019. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7020. conn->status_code = 206; /* Partial content */
  7021. fseeko(file.fp, r1, SEEK_SET);
  7022. }
  7023. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7024. /* forward_body_data failed.
  7025. * The error code has already been sent to the client,
  7026. * and conn->status_code is already set. */
  7027. mg_fclose(&file);
  7028. return;
  7029. }
  7030. gmt_time_string(date, sizeof(date), &curtime);
  7031. mg_printf(conn,
  7032. "HTTP/1.1 %d %s\r\n",
  7033. conn->status_code,
  7034. mg_get_response_code_text(NULL, conn->status_code));
  7035. send_no_cache_header(conn);
  7036. mg_printf(conn,
  7037. "Date: %s\r\n"
  7038. "Content-Length: 0\r\n"
  7039. "Connection: %s\r\n\r\n",
  7040. date,
  7041. suggest_connection_header(conn));
  7042. mg_fclose(&file);
  7043. }
  7044. static void
  7045. delete_file(struct mg_connection *conn, const char *path)
  7046. {
  7047. struct de de;
  7048. memset(&de.file, 0, sizeof(de.file));
  7049. if (!mg_stat(conn, path, &de.file)) {
  7050. /* mg_stat returns 0 if the file does not exist */
  7051. send_http_error(conn,
  7052. 404,
  7053. "Error: Cannot delete file\nFile %s not found",
  7054. path);
  7055. return;
  7056. }
  7057. if (de.file.membuf != NULL) {
  7058. /* the file is cached in memory */
  7059. send_http_error(
  7060. conn,
  7061. 405,
  7062. "Error: Delete not possible\nDeleting %s is not supported",
  7063. path);
  7064. return;
  7065. }
  7066. if (de.file.is_directory) {
  7067. if (remove_directory(conn, path)) {
  7068. /* Delete is successful: Return 204 without content. */
  7069. send_http_error(conn, 204, "%s", "");
  7070. } else {
  7071. /* Delete is not successful: Return 500 (Server error). */
  7072. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7073. }
  7074. return;
  7075. }
  7076. /* This is an existing file (not a directory).
  7077. * Check if write permission is granted. */
  7078. if (access(path, W_OK) != 0) {
  7079. /* File is read only */
  7080. send_http_error(
  7081. conn,
  7082. 403,
  7083. "Error: Delete not possible\nDeleting %s is not allowed",
  7084. path);
  7085. return;
  7086. }
  7087. /* Try to delete it. */
  7088. if (mg_remove(conn, path) == 0) {
  7089. /* Delete was successful: Return 204 without content. */
  7090. send_http_error(conn, 204, "%s", "");
  7091. } else {
  7092. /* Delete not successful (file locked). */
  7093. send_http_error(conn,
  7094. 423,
  7095. "Error: Cannot delete file\nremove(%s): %s",
  7096. path,
  7097. strerror(ERRNO));
  7098. }
  7099. }
  7100. #endif /* !NO_FILES */
  7101. static void
  7102. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7103. static void
  7104. do_ssi_include(struct mg_connection *conn,
  7105. const char *ssi,
  7106. char *tag,
  7107. int include_level)
  7108. {
  7109. char file_name[MG_BUF_LEN], path[512], *p;
  7110. struct file file = STRUCT_FILE_INITIALIZER;
  7111. size_t len;
  7112. int truncated = 0;
  7113. if (conn == NULL) {
  7114. return;
  7115. }
  7116. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7117. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7118. * always < MG_BUF_LEN. */
  7119. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7120. /* File name is relative to the webserver root */
  7121. file_name[511] = 0;
  7122. (void)mg_snprintf(conn,
  7123. &truncated,
  7124. path,
  7125. sizeof(path),
  7126. "%s/%s",
  7127. conn->ctx->config[DOCUMENT_ROOT],
  7128. file_name);
  7129. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7130. /* File name is relative to the webserver working directory
  7131. * or it is absolute system path */
  7132. file_name[511] = 0;
  7133. (void)
  7134. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7135. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7136. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7137. /* File name is relative to the currect document */
  7138. file_name[511] = 0;
  7139. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7140. if (!truncated) {
  7141. if ((p = strrchr(path, '/')) != NULL) {
  7142. p[1] = '\0';
  7143. }
  7144. len = strlen(path);
  7145. (void)mg_snprintf(conn,
  7146. &truncated,
  7147. path + len,
  7148. sizeof(path) - len,
  7149. "%s",
  7150. file_name);
  7151. }
  7152. } else {
  7153. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7154. return;
  7155. }
  7156. if (truncated) {
  7157. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7158. return;
  7159. }
  7160. if (!mg_fopen(conn, path, "rb", &file)) {
  7161. mg_cry(conn,
  7162. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7163. tag,
  7164. path,
  7165. strerror(ERRNO));
  7166. } else {
  7167. fclose_on_exec(&file, conn);
  7168. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7169. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7170. path) > 0) {
  7171. send_ssi_file(conn, path, &file, include_level + 1);
  7172. } else {
  7173. send_file_data(conn, &file, 0, INT64_MAX);
  7174. }
  7175. mg_fclose(&file);
  7176. }
  7177. }
  7178. #if !defined(NO_POPEN)
  7179. static void
  7180. do_ssi_exec(struct mg_connection *conn, char *tag)
  7181. {
  7182. char cmd[1024] = "";
  7183. struct file file = STRUCT_FILE_INITIALIZER;
  7184. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7185. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7186. } else {
  7187. cmd[1023] = 0;
  7188. if ((file.fp = popen(cmd, "r")) == NULL) {
  7189. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7190. } else {
  7191. send_file_data(conn, &file, 0, INT64_MAX);
  7192. pclose(file.fp);
  7193. }
  7194. }
  7195. }
  7196. #endif /* !NO_POPEN */
  7197. static int
  7198. mg_fgetc(struct file *filep, int offset)
  7199. {
  7200. if (filep == NULL) {
  7201. return EOF;
  7202. }
  7203. if (filep->membuf != NULL && offset >= 0
  7204. && ((unsigned int)(offset)) < filep->size) {
  7205. return ((const unsigned char *)filep->membuf)[offset];
  7206. } else if (filep->fp != NULL) {
  7207. return fgetc(filep->fp);
  7208. } else {
  7209. return EOF;
  7210. }
  7211. }
  7212. static void
  7213. send_ssi_file(struct mg_connection *conn,
  7214. const char *path,
  7215. struct file *filep,
  7216. int include_level)
  7217. {
  7218. char buf[MG_BUF_LEN];
  7219. int ch, offset, len, in_ssi_tag;
  7220. if (include_level > 10) {
  7221. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7222. return;
  7223. }
  7224. in_ssi_tag = len = offset = 0;
  7225. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7226. if (in_ssi_tag && ch == '>') {
  7227. in_ssi_tag = 0;
  7228. buf[len++] = (char)ch;
  7229. buf[len] = '\0';
  7230. /* assert(len <= (int) sizeof(buf)); */
  7231. if (len > (int)sizeof(buf)) {
  7232. break;
  7233. }
  7234. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7235. /* Not an SSI tag, pass it */
  7236. (void)mg_write(conn, buf, (size_t)len);
  7237. } else {
  7238. if (!memcmp(buf + 5, "include", 7)) {
  7239. do_ssi_include(conn, path, buf + 12, include_level);
  7240. #if !defined(NO_POPEN)
  7241. } else if (!memcmp(buf + 5, "exec", 4)) {
  7242. do_ssi_exec(conn, buf + 9);
  7243. #endif /* !NO_POPEN */
  7244. } else {
  7245. mg_cry(conn,
  7246. "%s: unknown SSI "
  7247. "command: \"%s\"",
  7248. path,
  7249. buf);
  7250. }
  7251. }
  7252. len = 0;
  7253. } else if (in_ssi_tag) {
  7254. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7255. /* Not an SSI tag */
  7256. in_ssi_tag = 0;
  7257. } else if (len == (int)sizeof(buf) - 2) {
  7258. mg_cry(conn, "%s: SSI tag is too large", path);
  7259. len = 0;
  7260. }
  7261. buf[len++] = (char)(ch & 0xff);
  7262. } else if (ch == '<') {
  7263. in_ssi_tag = 1;
  7264. if (len > 0) {
  7265. mg_write(conn, buf, (size_t)len);
  7266. }
  7267. len = 0;
  7268. buf[len++] = (char)(ch & 0xff);
  7269. } else {
  7270. buf[len++] = (char)(ch & 0xff);
  7271. if (len == (int)sizeof(buf)) {
  7272. mg_write(conn, buf, (size_t)len);
  7273. len = 0;
  7274. }
  7275. }
  7276. }
  7277. /* Send the rest of buffered data */
  7278. if (len > 0) {
  7279. mg_write(conn, buf, (size_t)len);
  7280. }
  7281. }
  7282. static void
  7283. handle_ssi_file_request(struct mg_connection *conn,
  7284. const char *path,
  7285. struct file *filep)
  7286. {
  7287. char date[64];
  7288. time_t curtime = time(NULL);
  7289. const char *cors1, *cors2, *cors3;
  7290. if (conn == NULL || path == NULL || filep == NULL) {
  7291. return;
  7292. }
  7293. if (mg_get_header(conn, "Origin")) {
  7294. /* Cross-origin resource sharing (CORS). */
  7295. cors1 = "Access-Control-Allow-Origin: ";
  7296. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7297. cors3 = "\r\n";
  7298. } else {
  7299. cors1 = cors2 = cors3 = "";
  7300. }
  7301. if (!mg_fopen(conn, path, "rb", filep)) {
  7302. /* File exists (precondition for calling this function),
  7303. * but can not be opened by the server. */
  7304. send_http_error(conn,
  7305. 500,
  7306. "Error: Cannot read file\nfopen(%s): %s",
  7307. path,
  7308. strerror(ERRNO));
  7309. } else {
  7310. conn->must_close = 1;
  7311. gmt_time_string(date, sizeof(date), &curtime);
  7312. fclose_on_exec(filep, conn);
  7313. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7314. send_no_cache_header(conn);
  7315. mg_printf(conn,
  7316. "%s%s%s"
  7317. "Date: %s\r\n"
  7318. "Content-Type: text/html\r\n"
  7319. "Connection: %s\r\n\r\n",
  7320. cors1,
  7321. cors2,
  7322. cors3,
  7323. date,
  7324. suggest_connection_header(conn));
  7325. send_ssi_file(conn, path, filep, 0);
  7326. mg_fclose(filep);
  7327. }
  7328. }
  7329. #if !defined(NO_FILES)
  7330. static void
  7331. send_options(struct mg_connection *conn)
  7332. {
  7333. char date[64];
  7334. time_t curtime = time(NULL);
  7335. if (!conn) {
  7336. return;
  7337. }
  7338. conn->status_code = 200;
  7339. conn->must_close = 1;
  7340. gmt_time_string(date, sizeof(date), &curtime);
  7341. mg_printf(conn,
  7342. "HTTP/1.1 200 OK\r\n"
  7343. "Date: %s\r\n"
  7344. /* TODO: "Cache-Control" (?) */
  7345. "Connection: %s\r\n"
  7346. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7347. "PROPFIND, MKCOL\r\n"
  7348. "DAV: 1\r\n\r\n",
  7349. date,
  7350. suggest_connection_header(conn));
  7351. }
  7352. /* Writes PROPFIND properties for a collection element */
  7353. static void
  7354. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7355. {
  7356. char mtime[64];
  7357. if (conn == NULL || uri == NULL || filep == NULL) {
  7358. return;
  7359. }
  7360. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7361. conn->num_bytes_sent +=
  7362. mg_printf(conn,
  7363. "<d:response>"
  7364. "<d:href>%s</d:href>"
  7365. "<d:propstat>"
  7366. "<d:prop>"
  7367. "<d:resourcetype>%s</d:resourcetype>"
  7368. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7369. "<d:getlastmodified>%s</d:getlastmodified>"
  7370. "</d:prop>"
  7371. "<d:status>HTTP/1.1 200 OK</d:status>"
  7372. "</d:propstat>"
  7373. "</d:response>\n",
  7374. uri,
  7375. filep->is_directory ? "<d:collection/>" : "",
  7376. filep->size,
  7377. mtime);
  7378. }
  7379. static void
  7380. print_dav_dir_entry(struct de *de, void *data)
  7381. {
  7382. char href[PATH_MAX];
  7383. char href_encoded[PATH_MAX * 3 /* worst case */];
  7384. int truncated;
  7385. struct mg_connection *conn = (struct mg_connection *)data;
  7386. if (!de || !conn) {
  7387. return;
  7388. }
  7389. mg_snprintf(conn,
  7390. &truncated,
  7391. href,
  7392. sizeof(href),
  7393. "%s%s",
  7394. conn->request_info.local_uri,
  7395. de->file_name);
  7396. if (!truncated) {
  7397. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7398. print_props(conn, href_encoded, &de->file);
  7399. }
  7400. }
  7401. static void
  7402. handle_propfind(struct mg_connection *conn,
  7403. const char *path,
  7404. struct file *filep)
  7405. {
  7406. const char *depth = mg_get_header(conn, "Depth");
  7407. char date[64];
  7408. time_t curtime = time(NULL);
  7409. gmt_time_string(date, sizeof(date), &curtime);
  7410. if (!conn || !path || !filep || !conn->ctx) {
  7411. return;
  7412. }
  7413. conn->must_close = 1;
  7414. conn->status_code = 207;
  7415. mg_printf(conn,
  7416. "HTTP/1.1 207 Multi-Status\r\n"
  7417. "Date: %s\r\n",
  7418. date);
  7419. send_static_cache_header(conn);
  7420. mg_printf(conn,
  7421. "Connection: %s\r\n"
  7422. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7423. suggest_connection_header(conn));
  7424. conn->num_bytes_sent +=
  7425. mg_printf(conn,
  7426. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7427. "<d:multistatus xmlns:d='DAV:'>\n");
  7428. /* Print properties for the requested resource itself */
  7429. print_props(conn, conn->request_info.local_uri, filep);
  7430. /* If it is a directory, print directory entries too if Depth is not 0 */
  7431. if (filep && filep->is_directory
  7432. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7433. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7434. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7435. }
  7436. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7437. }
  7438. #endif
  7439. void
  7440. mg_lock_connection(struct mg_connection *conn)
  7441. {
  7442. if (conn) {
  7443. (void)pthread_mutex_lock(&conn->mutex);
  7444. }
  7445. }
  7446. void
  7447. mg_unlock_connection(struct mg_connection *conn)
  7448. {
  7449. if (conn) {
  7450. (void)pthread_mutex_unlock(&conn->mutex);
  7451. }
  7452. }
  7453. void
  7454. mg_lock_context(struct mg_context *ctx)
  7455. {
  7456. if (ctx) {
  7457. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7458. }
  7459. }
  7460. void
  7461. mg_unlock_context(struct mg_context *ctx)
  7462. {
  7463. if (ctx) {
  7464. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7465. }
  7466. }
  7467. #if defined(USE_TIMERS)
  7468. #include "timer.inl"
  7469. #endif /* USE_TIMERS */
  7470. #ifdef USE_LUA
  7471. #include "mod_lua.inl"
  7472. #endif /* USE_LUA */
  7473. #ifdef USE_DUKTAPE
  7474. #include "mod_duktape.inl"
  7475. #endif /* USE_DUKTAPE */
  7476. #if defined(USE_WEBSOCKET)
  7477. /* START OF SHA-1 code
  7478. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7479. #define SHA1HANDSOFF
  7480. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7481. *
  7482. * #if defined(__sun)
  7483. * #include "solarisfixes.h"
  7484. * #endif
  7485. */
  7486. static int
  7487. is_big_endian(void)
  7488. {
  7489. static const int n = 1;
  7490. return ((char *)&n)[0] == 0;
  7491. }
  7492. union char64long16 {
  7493. unsigned char c[64];
  7494. uint32_t l[16];
  7495. };
  7496. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7497. static uint32_t
  7498. blk0(union char64long16 *block, int i)
  7499. {
  7500. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7501. if (!is_big_endian()) {
  7502. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7503. | (rol(block->l[i], 8) & 0x00FF00FF);
  7504. }
  7505. return block->l[i];
  7506. }
  7507. #define blk(i) \
  7508. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7509. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7510. 1))
  7511. #define R0(v, w, x, y, z, i) \
  7512. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7513. w = rol(w, 30);
  7514. #define R1(v, w, x, y, z, i) \
  7515. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7516. w = rol(w, 30);
  7517. #define R2(v, w, x, y, z, i) \
  7518. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7519. w = rol(w, 30);
  7520. #define R3(v, w, x, y, z, i) \
  7521. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7522. w = rol(w, 30);
  7523. #define R4(v, w, x, y, z, i) \
  7524. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7525. w = rol(w, 30);
  7526. typedef struct {
  7527. uint32_t state[5];
  7528. uint32_t count[2];
  7529. unsigned char buffer[64];
  7530. } SHA1_CTX;
  7531. static void
  7532. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7533. {
  7534. uint32_t a, b, c, d, e;
  7535. union char64long16 block[1];
  7536. memcpy(block, buffer, 64);
  7537. a = state[0];
  7538. b = state[1];
  7539. c = state[2];
  7540. d = state[3];
  7541. e = state[4];
  7542. R0(a, b, c, d, e, 0);
  7543. R0(e, a, b, c, d, 1);
  7544. R0(d, e, a, b, c, 2);
  7545. R0(c, d, e, a, b, 3);
  7546. R0(b, c, d, e, a, 4);
  7547. R0(a, b, c, d, e, 5);
  7548. R0(e, a, b, c, d, 6);
  7549. R0(d, e, a, b, c, 7);
  7550. R0(c, d, e, a, b, 8);
  7551. R0(b, c, d, e, a, 9);
  7552. R0(a, b, c, d, e, 10);
  7553. R0(e, a, b, c, d, 11);
  7554. R0(d, e, a, b, c, 12);
  7555. R0(c, d, e, a, b, 13);
  7556. R0(b, c, d, e, a, 14);
  7557. R0(a, b, c, d, e, 15);
  7558. R1(e, a, b, c, d, 16);
  7559. R1(d, e, a, b, c, 17);
  7560. R1(c, d, e, a, b, 18);
  7561. R1(b, c, d, e, a, 19);
  7562. R2(a, b, c, d, e, 20);
  7563. R2(e, a, b, c, d, 21);
  7564. R2(d, e, a, b, c, 22);
  7565. R2(c, d, e, a, b, 23);
  7566. R2(b, c, d, e, a, 24);
  7567. R2(a, b, c, d, e, 25);
  7568. R2(e, a, b, c, d, 26);
  7569. R2(d, e, a, b, c, 27);
  7570. R2(c, d, e, a, b, 28);
  7571. R2(b, c, d, e, a, 29);
  7572. R2(a, b, c, d, e, 30);
  7573. R2(e, a, b, c, d, 31);
  7574. R2(d, e, a, b, c, 32);
  7575. R2(c, d, e, a, b, 33);
  7576. R2(b, c, d, e, a, 34);
  7577. R2(a, b, c, d, e, 35);
  7578. R2(e, a, b, c, d, 36);
  7579. R2(d, e, a, b, c, 37);
  7580. R2(c, d, e, a, b, 38);
  7581. R2(b, c, d, e, a, 39);
  7582. R3(a, b, c, d, e, 40);
  7583. R3(e, a, b, c, d, 41);
  7584. R3(d, e, a, b, c, 42);
  7585. R3(c, d, e, a, b, 43);
  7586. R3(b, c, d, e, a, 44);
  7587. R3(a, b, c, d, e, 45);
  7588. R3(e, a, b, c, d, 46);
  7589. R3(d, e, a, b, c, 47);
  7590. R3(c, d, e, a, b, 48);
  7591. R3(b, c, d, e, a, 49);
  7592. R3(a, b, c, d, e, 50);
  7593. R3(e, a, b, c, d, 51);
  7594. R3(d, e, a, b, c, 52);
  7595. R3(c, d, e, a, b, 53);
  7596. R3(b, c, d, e, a, 54);
  7597. R3(a, b, c, d, e, 55);
  7598. R3(e, a, b, c, d, 56);
  7599. R3(d, e, a, b, c, 57);
  7600. R3(c, d, e, a, b, 58);
  7601. R3(b, c, d, e, a, 59);
  7602. R4(a, b, c, d, e, 60);
  7603. R4(e, a, b, c, d, 61);
  7604. R4(d, e, a, b, c, 62);
  7605. R4(c, d, e, a, b, 63);
  7606. R4(b, c, d, e, a, 64);
  7607. R4(a, b, c, d, e, 65);
  7608. R4(e, a, b, c, d, 66);
  7609. R4(d, e, a, b, c, 67);
  7610. R4(c, d, e, a, b, 68);
  7611. R4(b, c, d, e, a, 69);
  7612. R4(a, b, c, d, e, 70);
  7613. R4(e, a, b, c, d, 71);
  7614. R4(d, e, a, b, c, 72);
  7615. R4(c, d, e, a, b, 73);
  7616. R4(b, c, d, e, a, 74);
  7617. R4(a, b, c, d, e, 75);
  7618. R4(e, a, b, c, d, 76);
  7619. R4(d, e, a, b, c, 77);
  7620. R4(c, d, e, a, b, 78);
  7621. R4(b, c, d, e, a, 79);
  7622. state[0] += a;
  7623. state[1] += b;
  7624. state[2] += c;
  7625. state[3] += d;
  7626. state[4] += e;
  7627. a = b = c = d = e = 0;
  7628. memset(block, '\0', sizeof(block));
  7629. }
  7630. static void
  7631. SHA1Init(SHA1_CTX *context)
  7632. {
  7633. context->state[0] = 0x67452301;
  7634. context->state[1] = 0xEFCDAB89;
  7635. context->state[2] = 0x98BADCFE;
  7636. context->state[3] = 0x10325476;
  7637. context->state[4] = 0xC3D2E1F0;
  7638. context->count[0] = context->count[1] = 0;
  7639. }
  7640. static void
  7641. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7642. {
  7643. uint32_t i, j;
  7644. j = context->count[0];
  7645. if ((context->count[0] += len << 3) < j) {
  7646. context->count[1]++;
  7647. }
  7648. context->count[1] += (len >> 29);
  7649. j = (j >> 3) & 63;
  7650. if ((j + len) > 63) {
  7651. memcpy(&context->buffer[j], data, (i = 64 - j));
  7652. SHA1Transform(context->state, context->buffer);
  7653. for (; i + 63 < len; i += 64) {
  7654. SHA1Transform(context->state, &data[i]);
  7655. }
  7656. j = 0;
  7657. } else
  7658. i = 0;
  7659. memcpy(&context->buffer[j], &data[i], len - i);
  7660. }
  7661. static void
  7662. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7663. {
  7664. unsigned i;
  7665. unsigned char finalcount[8], c;
  7666. for (i = 0; i < 8; i++) {
  7667. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7668. >> ((3 - (i & 3)) * 8)) & 255);
  7669. }
  7670. c = 0200;
  7671. SHA1Update(context, &c, 1);
  7672. while ((context->count[0] & 504) != 448) {
  7673. c = 0000;
  7674. SHA1Update(context, &c, 1);
  7675. }
  7676. SHA1Update(context, finalcount, 8);
  7677. for (i = 0; i < 20; i++) {
  7678. digest[i] = (unsigned char)((context->state[i >> 2]
  7679. >> ((3 - (i & 3)) * 8)) & 255);
  7680. }
  7681. memset(context, '\0', sizeof(*context));
  7682. memset(&finalcount, '\0', sizeof(finalcount));
  7683. }
  7684. /* END OF SHA1 CODE */
  7685. static int
  7686. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7687. {
  7688. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7689. const char *protocol = NULL;
  7690. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7691. SHA1_CTX sha_ctx;
  7692. int truncated;
  7693. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7694. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7695. if (truncated) {
  7696. conn->must_close = 1;
  7697. return 0;
  7698. }
  7699. SHA1Init(&sha_ctx);
  7700. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7701. SHA1Final((unsigned char *)sha, &sha_ctx);
  7702. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7703. mg_printf(conn,
  7704. "HTTP/1.1 101 Switching Protocols\r\n"
  7705. "Upgrade: websocket\r\n"
  7706. "Connection: Upgrade\r\n"
  7707. "Sec-WebSocket-Accept: %s\r\n",
  7708. b64_sha);
  7709. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7710. if (protocol) {
  7711. /* The protocol is a comma seperated list of names. */
  7712. /* The server must only return one value from this list. */
  7713. /* First check if it is a list or just a single value. */
  7714. const char *sep = strchr(protocol, ',');
  7715. if (sep == NULL) {
  7716. /* Just a single protocol -> accept it. */
  7717. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7718. } else {
  7719. /* Multiple protocols -> accept the first one. */
  7720. /* This is just a quick fix if the client offers multiple
  7721. * protocols. In order to get the behavior intended by
  7722. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7723. * required to have a list of websocket subprotocols accepted
  7724. * by the server. Then the server must either select a subprotocol
  7725. * supported by client and server, or the server has to abort the
  7726. * handshake by not returning a Sec-Websocket-Protocol header if
  7727. * no subprotocol is acceptable.
  7728. */
  7729. mg_printf(conn,
  7730. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7731. (int)(sep - protocol),
  7732. protocol);
  7733. }
  7734. /* TODO: Real subprotocol negotiation instead of just taking the first
  7735. * websocket subprotocol suggested by the client. */
  7736. } else {
  7737. mg_printf(conn, "%s", "\r\n");
  7738. }
  7739. return 1;
  7740. }
  7741. static void
  7742. read_websocket(struct mg_connection *conn,
  7743. mg_websocket_data_handler ws_data_handler,
  7744. void *callback_data)
  7745. {
  7746. /* Pointer to the beginning of the portion of the incoming websocket
  7747. * message queue.
  7748. * The original websocket upgrade request is never removed, so the queue
  7749. * begins after it. */
  7750. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7751. int n, error, exit_by_callback;
  7752. /* body_len is the length of the entire queue in bytes
  7753. * len is the length of the current message
  7754. * data_len is the length of the current message's data payload
  7755. * header_len is the length of the current message's header */
  7756. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7757. /* "The masking key is a 32-bit value chosen at random by the client."
  7758. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7759. */
  7760. unsigned char mask[4];
  7761. /* data points to the place where the message is stored when passed to
  7762. * the
  7763. * websocket_data callback. This is either mem on the stack, or a
  7764. * dynamically allocated buffer if it is too large. */
  7765. char mem[4096];
  7766. char *data = mem;
  7767. unsigned char mop; /* mask flag and opcode */
  7768. double timeout = -1.0;
  7769. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7770. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7771. }
  7772. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7773. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7774. }
  7775. mg_set_thread_name("wsock");
  7776. /* Loop continuously, reading messages from the socket, invoking the
  7777. * callback, and waiting repeatedly until an error occurs. */
  7778. while (!conn->ctx->stop_flag) {
  7779. header_len = 0;
  7780. assert(conn->data_len >= conn->request_len);
  7781. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7782. len = buf[1] & 127;
  7783. mask_len = (buf[1] & 128) ? 4 : 0;
  7784. if ((len < 126) && (body_len >= mask_len)) {
  7785. data_len = len;
  7786. header_len = 2 + mask_len;
  7787. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7788. header_len = 4 + mask_len;
  7789. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7790. } else if (body_len >= (10 + mask_len)) {
  7791. header_len = 10 + mask_len;
  7792. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7793. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7794. }
  7795. }
  7796. if (header_len > 0 && body_len >= header_len) {
  7797. /* Allocate space to hold websocket payload */
  7798. data = mem;
  7799. if (data_len > sizeof(mem)) {
  7800. data = (char *)mg_malloc(data_len);
  7801. if (data == NULL) {
  7802. /* Allocation failed, exit the loop and then close the
  7803. * connection */
  7804. mg_cry(conn, "websocket out of memory; closing connection");
  7805. break;
  7806. }
  7807. }
  7808. /* Copy the mask before we shift the queue and destroy it */
  7809. if (mask_len > 0) {
  7810. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7811. } else {
  7812. memset(mask, 0, sizeof(mask));
  7813. }
  7814. /* Read frame payload from the first message in the queue into
  7815. * data and advance the queue by moving the memory in place. */
  7816. assert(body_len >= header_len);
  7817. if (data_len + header_len > body_len) {
  7818. mop = buf[0]; /* current mask and opcode */
  7819. /* Overflow case */
  7820. len = body_len - header_len;
  7821. memcpy(data, buf + header_len, len);
  7822. error = 0;
  7823. while (len < data_len) {
  7824. n = pull(
  7825. NULL, conn, data + len, (int)(data_len - len), timeout);
  7826. if (n <= 0) {
  7827. error = 1;
  7828. break;
  7829. }
  7830. len += (size_t)n;
  7831. }
  7832. if (error) {
  7833. mg_cry(conn, "Websocket pull failed; closing connection");
  7834. break;
  7835. }
  7836. conn->data_len = conn->request_len;
  7837. } else {
  7838. mop = buf[0]; /* current mask and opcode, overwritten by
  7839. * memmove() */
  7840. /* Length of the message being read at the front of the
  7841. * queue */
  7842. len = data_len + header_len;
  7843. /* Copy the data payload into the data pointer for the
  7844. * callback */
  7845. memcpy(data, buf + header_len, data_len);
  7846. /* Move the queue forward len bytes */
  7847. memmove(buf, buf + len, body_len - len);
  7848. /* Mark the queue as advanced */
  7849. conn->data_len -= (int)len;
  7850. }
  7851. /* Apply mask if necessary */
  7852. if (mask_len > 0) {
  7853. for (i = 0; i < data_len; ++i) {
  7854. data[i] ^= mask[i & 3];
  7855. }
  7856. }
  7857. /* Exit the loop if callback signals to exit (server side),
  7858. * or "connection close" opcode received (client side). */
  7859. exit_by_callback = 0;
  7860. if ((ws_data_handler != NULL)
  7861. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7862. exit_by_callback = 1;
  7863. }
  7864. if (data != mem) {
  7865. mg_free(data);
  7866. }
  7867. if (exit_by_callback
  7868. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7869. /* Opcode == 8, connection close */
  7870. break;
  7871. }
  7872. /* Not breaking the loop, process next websocket frame. */
  7873. } else {
  7874. /* Read from the socket into the next available location in the
  7875. * message queue. */
  7876. if ((n = pull(NULL,
  7877. conn,
  7878. conn->buf + conn->data_len,
  7879. conn->buf_size - conn->data_len,
  7880. timeout)) <= 0) {
  7881. /* Error, no bytes read */
  7882. break;
  7883. }
  7884. conn->data_len += n;
  7885. }
  7886. }
  7887. mg_set_thread_name("worker");
  7888. }
  7889. static int
  7890. mg_websocket_write_exec(struct mg_connection *conn,
  7891. int opcode,
  7892. const char *data,
  7893. size_t dataLen,
  7894. uint32_t masking_key)
  7895. {
  7896. unsigned char header[14];
  7897. size_t headerLen = 1;
  7898. int retval = -1;
  7899. header[0] = 0x80 + (opcode & 0xF);
  7900. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7901. if (dataLen < 126) {
  7902. /* inline 7-bit length field */
  7903. header[1] = (unsigned char)dataLen;
  7904. headerLen = 2;
  7905. } else if (dataLen <= 0xFFFF) {
  7906. /* 16-bit length field */
  7907. header[1] = 126;
  7908. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7909. headerLen = 4;
  7910. } else {
  7911. /* 64-bit length field */
  7912. header[1] = 127;
  7913. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7914. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7915. headerLen = 10;
  7916. }
  7917. if (masking_key) {
  7918. /* add mask */
  7919. header[1] |= 0x80;
  7920. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7921. headerLen += 4;
  7922. }
  7923. /* Note that POSIX/Winsock's send() is threadsafe
  7924. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7925. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7926. * push(), although that is only a problem if the packet is large or
  7927. * outgoing buffer is full). */
  7928. (void)mg_lock_connection(conn);
  7929. retval = mg_write(conn, header, headerLen);
  7930. if (dataLen > 0) {
  7931. retval = mg_write(conn, data, dataLen);
  7932. }
  7933. mg_unlock_connection(conn);
  7934. return retval;
  7935. }
  7936. int
  7937. mg_websocket_write(struct mg_connection *conn,
  7938. int opcode,
  7939. const char *data,
  7940. size_t dataLen)
  7941. {
  7942. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7943. }
  7944. static void
  7945. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7946. {
  7947. size_t i = 0;
  7948. i = 0;
  7949. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7950. /* Convert in 32 bit words, if data is 4 byte aligned */
  7951. while (i < (in_len - 3)) {
  7952. *(uint32_t *)(void *)(out + i) =
  7953. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7954. i += 4;
  7955. }
  7956. }
  7957. if (i != in_len) {
  7958. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7959. while (i < in_len) {
  7960. *(uint8_t *)(void *)(out + i) =
  7961. *(uint8_t *)(void *)(in + i)
  7962. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7963. i++;
  7964. }
  7965. }
  7966. }
  7967. int
  7968. mg_websocket_client_write(struct mg_connection *conn,
  7969. int opcode,
  7970. const char *data,
  7971. size_t dataLen)
  7972. {
  7973. int retval = -1;
  7974. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7975. uint32_t masking_key = (uint32_t)get_random();
  7976. if (masked_data == NULL) {
  7977. /* Return -1 in an error case */
  7978. mg_cry(conn,
  7979. "Cannot allocate buffer for masked websocket response: "
  7980. "Out of memory");
  7981. return -1;
  7982. }
  7983. mask_data(data, dataLen, masking_key, masked_data);
  7984. retval = mg_websocket_write_exec(
  7985. conn, opcode, masked_data, dataLen, masking_key);
  7986. mg_free(masked_data);
  7987. return retval;
  7988. }
  7989. static void
  7990. handle_websocket_request(struct mg_connection *conn,
  7991. const char *path,
  7992. int is_callback_resource,
  7993. mg_websocket_connect_handler ws_connect_handler,
  7994. mg_websocket_ready_handler ws_ready_handler,
  7995. mg_websocket_data_handler ws_data_handler,
  7996. mg_websocket_close_handler ws_close_handler,
  7997. void *cbData)
  7998. {
  7999. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8000. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8001. int lua_websock = 0;
  8002. #if !defined(USE_LUA)
  8003. (void)path;
  8004. #endif
  8005. /* Step 1: Check websocket protocol version. */
  8006. /* Step 1.1: Check Sec-WebSocket-Key. */
  8007. if (!websock_key) {
  8008. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8009. * requires a Sec-WebSocket-Key header.
  8010. */
  8011. /* It could be the hixie draft version
  8012. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8013. */
  8014. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8015. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8016. char key3[8];
  8017. if ((key1 != NULL) && (key2 != NULL)) {
  8018. /* This version uses 8 byte body data in a GET request */
  8019. conn->content_len = 8;
  8020. if (8 == mg_read(conn, key3, 8)) {
  8021. /* This is the hixie version */
  8022. send_http_error(conn,
  8023. 426,
  8024. "%s",
  8025. "Protocol upgrade to RFC 6455 required");
  8026. return;
  8027. }
  8028. }
  8029. /* This is an unknown version */
  8030. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8031. return;
  8032. }
  8033. /* Step 1.2: Check websocket protocol version. */
  8034. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8035. if (version == NULL || strcmp(version, "13") != 0) {
  8036. /* Reject wrong versions */
  8037. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8038. return;
  8039. }
  8040. /* Step 1.3: Could check for "Host", but we do not really nead this
  8041. * value for anything, so just ignore it. */
  8042. /* Step 2: If a callback is responsible, call it. */
  8043. if (is_callback_resource) {
  8044. if (ws_connect_handler != NULL
  8045. && ws_connect_handler(conn, cbData) != 0) {
  8046. /* C callback has returned non-zero, do not proceed with
  8047. * handshake.
  8048. */
  8049. /* Note that C callbacks are no longer called when Lua is
  8050. * responsible, so C can no longer filter callbacks for Lua. */
  8051. return;
  8052. }
  8053. }
  8054. #if defined(USE_LUA)
  8055. /* Step 3: No callback. Check if Lua is responsible. */
  8056. else {
  8057. /* Step 3.1: Check if Lua is responsible. */
  8058. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8059. lua_websock =
  8060. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8061. strlen(
  8062. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8063. path);
  8064. }
  8065. if (lua_websock) {
  8066. /* Step 3.2: Lua is responsible: call it. */
  8067. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8068. if (!conn->lua_websocket_state) {
  8069. /* Lua rejected the new client */
  8070. return;
  8071. }
  8072. }
  8073. }
  8074. #endif
  8075. /* Step 4: Check if there is a responsible websocket handler. */
  8076. if (!is_callback_resource && !lua_websock) {
  8077. /* There is no callback, an Lua is not responsible either. */
  8078. /* Reply with a 404 Not Found or with nothing at all?
  8079. * TODO (mid): check the websocket standards, how to reply to
  8080. * requests to invalid websocket addresses. */
  8081. send_http_error(conn, 404, "%s", "Not found");
  8082. return;
  8083. }
  8084. /* Step 5: The websocket connection has been accepted */
  8085. if (!send_websocket_handshake(conn, websock_key)) {
  8086. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8087. return;
  8088. }
  8089. /* Step 6: Call the ready handler */
  8090. if (is_callback_resource) {
  8091. if (ws_ready_handler != NULL) {
  8092. ws_ready_handler(conn, cbData);
  8093. }
  8094. #if defined(USE_LUA)
  8095. } else if (lua_websock) {
  8096. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8097. /* the ready handler returned false */
  8098. return;
  8099. }
  8100. #endif
  8101. }
  8102. /* Step 7: Enter the read loop */
  8103. if (is_callback_resource) {
  8104. read_websocket(conn, ws_data_handler, cbData);
  8105. #if defined(USE_LUA)
  8106. } else if (lua_websock) {
  8107. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8108. #endif
  8109. }
  8110. /* Step 8: Call the close handler */
  8111. if (ws_close_handler) {
  8112. ws_close_handler(conn, cbData);
  8113. }
  8114. }
  8115. static int
  8116. is_websocket_protocol(const struct mg_connection *conn)
  8117. {
  8118. const char *upgrade, *connection;
  8119. /* A websocket protocoll has the following HTTP headers:
  8120. *
  8121. * Connection: Upgrade
  8122. * Upgrade: Websocket
  8123. */
  8124. upgrade = mg_get_header(conn, "Upgrade");
  8125. if (upgrade == NULL) {
  8126. return 0; /* fail early, don't waste time checking other header
  8127. * fields
  8128. */
  8129. }
  8130. if (!mg_strcasestr(upgrade, "websocket")) {
  8131. return 0;
  8132. }
  8133. connection = mg_get_header(conn, "Connection");
  8134. if (connection == NULL) {
  8135. return 0;
  8136. }
  8137. if (!mg_strcasestr(connection, "upgrade")) {
  8138. return 0;
  8139. }
  8140. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8141. * "Sec-WebSocket-Version" are also required.
  8142. * Don't check them here, since even an unsupported websocket protocol
  8143. * request still IS a websocket request (in contrast to a standard HTTP
  8144. * request). It will fail later in handle_websocket_request.
  8145. */
  8146. return 1;
  8147. }
  8148. #endif /* !USE_WEBSOCKET */
  8149. static int
  8150. isbyte(int n)
  8151. {
  8152. return n >= 0 && n <= 255;
  8153. }
  8154. static int
  8155. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8156. {
  8157. int n, a, b, c, d, slash = 32, len = 0;
  8158. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8159. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8160. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8161. && slash < 33) {
  8162. len = n;
  8163. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8164. | (uint32_t)d;
  8165. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8166. }
  8167. return len;
  8168. }
  8169. static int
  8170. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8171. {
  8172. int throttle = 0;
  8173. struct vec vec, val;
  8174. uint32_t net, mask;
  8175. char mult;
  8176. double v;
  8177. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8178. mult = ',';
  8179. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8180. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8181. && mult != ',')) {
  8182. continue;
  8183. }
  8184. v *= (lowercase(&mult) == 'k')
  8185. ? 1024
  8186. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8187. if (vec.len == 1 && vec.ptr[0] == '*') {
  8188. throttle = (int)v;
  8189. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8190. if ((remote_ip & mask) == net) {
  8191. throttle = (int)v;
  8192. }
  8193. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8194. throttle = (int)v;
  8195. }
  8196. }
  8197. return throttle;
  8198. }
  8199. static uint32_t
  8200. get_remote_ip(const struct mg_connection *conn)
  8201. {
  8202. if (!conn) {
  8203. return 0;
  8204. }
  8205. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8206. }
  8207. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8208. #include "handle_form.inl"
  8209. #if defined(MG_LEGACY_INTERFACE)
  8210. /* Implement the deprecated mg_upload function by calling the new
  8211. * mg_handle_form_request function. While mg_upload could only handle
  8212. * HTML forms sent as POST request in multipart/form-data format
  8213. * containing only file input elements, mg_handle_form_request can
  8214. * handle all form input elements and all standard request methods. */
  8215. struct mg_upload_user_data {
  8216. struct mg_connection *conn;
  8217. const char *destination_dir;
  8218. int num_uploaded_files;
  8219. };
  8220. /* Helper function for deprecated mg_upload. */
  8221. static int
  8222. mg_upload_field_found(const char *key,
  8223. const char *filename,
  8224. char *path,
  8225. size_t pathlen,
  8226. void *user_data)
  8227. {
  8228. int truncated = 0;
  8229. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8230. (void)key;
  8231. if (!filename) {
  8232. mg_cry(fud->conn, "%s: No filename set", __func__);
  8233. return FORM_FIELD_STORAGE_ABORT;
  8234. }
  8235. mg_snprintf(fud->conn,
  8236. &truncated,
  8237. path,
  8238. pathlen - 1,
  8239. "%s/%s",
  8240. fud->destination_dir,
  8241. filename);
  8242. if (!truncated) {
  8243. mg_cry(fud->conn, "%s: File path too long", __func__);
  8244. return FORM_FIELD_STORAGE_ABORT;
  8245. }
  8246. return FORM_FIELD_STORAGE_STORE;
  8247. }
  8248. /* Helper function for deprecated mg_upload. */
  8249. static int
  8250. mg_upload_field_get(const char *key,
  8251. const char *value,
  8252. size_t value_size,
  8253. void *user_data)
  8254. {
  8255. /* Function should never be called */
  8256. (void)key;
  8257. (void)value;
  8258. (void)value_size;
  8259. (void)user_data;
  8260. return 0;
  8261. }
  8262. /* Helper function for deprecated mg_upload. */
  8263. static int
  8264. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8265. {
  8266. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8267. (void)file_size;
  8268. fud->num_uploaded_files++;
  8269. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8270. return 0;
  8271. }
  8272. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8273. int
  8274. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8275. {
  8276. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8277. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8278. mg_upload_field_get,
  8279. mg_upload_field_stored,
  8280. 0};
  8281. int ret;
  8282. fdh.user_data = (void *)&fud;
  8283. ret = mg_handle_form_request(conn, &fdh);
  8284. if (ret < 0) {
  8285. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8286. }
  8287. return fud.num_uploaded_files;
  8288. }
  8289. #endif
  8290. static int
  8291. get_first_ssl_listener_index(const struct mg_context *ctx)
  8292. {
  8293. unsigned int i;
  8294. int idx = -1;
  8295. if (ctx) {
  8296. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8297. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8298. }
  8299. }
  8300. return idx;
  8301. }
  8302. static void
  8303. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8304. {
  8305. char host[1025];
  8306. const char *host_header;
  8307. size_t hostlen;
  8308. host_header = mg_get_header(conn, "Host");
  8309. hostlen = sizeof(host);
  8310. if (host_header != NULL) {
  8311. char *pos;
  8312. mg_strlcpy(host, host_header, hostlen);
  8313. host[hostlen - 1] = '\0';
  8314. pos = strchr(host, ':');
  8315. if (pos != NULL) {
  8316. *pos = '\0';
  8317. }
  8318. } else {
  8319. /* Cannot get host from the Host: header.
  8320. * Fallback to our IP address. */
  8321. if (conn) {
  8322. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8323. }
  8324. }
  8325. /* Send host, port, uri and (if it exists) ?query_string */
  8326. if (conn) {
  8327. mg_printf(conn,
  8328. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8329. host,
  8330. #if defined(USE_IPV6)
  8331. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8332. == AF_INET6)
  8333. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8334. .lsa.sin6.sin6_port)
  8335. :
  8336. #endif
  8337. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8338. .lsa.sin.sin_port),
  8339. conn->request_info.local_uri,
  8340. (conn->request_info.query_string == NULL) ? "" : "?",
  8341. (conn->request_info.query_string == NULL)
  8342. ? ""
  8343. : conn->request_info.query_string);
  8344. }
  8345. }
  8346. static void
  8347. mg_set_handler_type(struct mg_context *ctx,
  8348. const char *uri,
  8349. int handler_type,
  8350. int is_delete_request,
  8351. mg_request_handler handler,
  8352. mg_websocket_connect_handler connect_handler,
  8353. mg_websocket_ready_handler ready_handler,
  8354. mg_websocket_data_handler data_handler,
  8355. mg_websocket_close_handler close_handler,
  8356. mg_authorization_handler auth_handler,
  8357. void *cbdata)
  8358. {
  8359. struct mg_handler_info *tmp_rh, **lastref;
  8360. size_t urilen = strlen(uri);
  8361. if (handler_type == WEBSOCKET_HANDLER) {
  8362. /* assert(handler == NULL); */
  8363. /* assert(is_delete_request || connect_handler!=NULL ||
  8364. * ready_handler!=NULL || data_handler!=NULL ||
  8365. * close_handler!=NULL);
  8366. */
  8367. /* assert(auth_handler == NULL); */
  8368. if (handler != NULL) {
  8369. return;
  8370. }
  8371. if (!is_delete_request && connect_handler == NULL
  8372. && ready_handler == NULL
  8373. && data_handler == NULL
  8374. && close_handler == NULL) {
  8375. return;
  8376. }
  8377. if (auth_handler != NULL) {
  8378. return;
  8379. }
  8380. } else if (handler_type == REQUEST_HANDLER) {
  8381. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8382. * data_handler==NULL && close_handler==NULL); */
  8383. /* assert(is_delete_request || (handler!=NULL));
  8384. */
  8385. /* assert(auth_handler == NULL); */
  8386. if (connect_handler != NULL || ready_handler != NULL
  8387. || data_handler != NULL
  8388. || close_handler != NULL) {
  8389. return;
  8390. }
  8391. if (!is_delete_request && (handler == NULL)) {
  8392. return;
  8393. }
  8394. if (auth_handler != NULL) {
  8395. return;
  8396. }
  8397. } else { /* AUTH_HANDLER */
  8398. /* assert(handler == NULL); */
  8399. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8400. * data_handler==NULL && close_handler==NULL); */
  8401. /* assert(auth_handler != NULL); */
  8402. if (handler != NULL) {
  8403. return;
  8404. }
  8405. if (connect_handler != NULL || ready_handler != NULL
  8406. || data_handler != NULL
  8407. || close_handler != NULL) {
  8408. return;
  8409. }
  8410. if (!is_delete_request && (auth_handler == NULL)) {
  8411. return;
  8412. }
  8413. }
  8414. if (!ctx) {
  8415. return;
  8416. }
  8417. mg_lock_context(ctx);
  8418. /* first try to find an existing handler */
  8419. lastref = &(ctx->handlers);
  8420. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8421. if (tmp_rh->handler_type == handler_type) {
  8422. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8423. if (!is_delete_request) {
  8424. /* update existing handler */
  8425. if (handler_type == REQUEST_HANDLER) {
  8426. tmp_rh->handler = handler;
  8427. } else if (handler_type == WEBSOCKET_HANDLER) {
  8428. tmp_rh->connect_handler = connect_handler;
  8429. tmp_rh->ready_handler = ready_handler;
  8430. tmp_rh->data_handler = data_handler;
  8431. tmp_rh->close_handler = close_handler;
  8432. } else { /* AUTH_HANDLER */
  8433. tmp_rh->auth_handler = auth_handler;
  8434. }
  8435. tmp_rh->cbdata = cbdata;
  8436. } else {
  8437. /* remove existing handler */
  8438. *lastref = tmp_rh->next;
  8439. mg_free(tmp_rh->uri);
  8440. mg_free(tmp_rh);
  8441. }
  8442. mg_unlock_context(ctx);
  8443. return;
  8444. }
  8445. }
  8446. lastref = &(tmp_rh->next);
  8447. }
  8448. if (is_delete_request) {
  8449. /* no handler to set, this was a remove request to a non-existing
  8450. * handler */
  8451. mg_unlock_context(ctx);
  8452. return;
  8453. }
  8454. tmp_rh =
  8455. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8456. if (tmp_rh == NULL) {
  8457. mg_unlock_context(ctx);
  8458. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8459. return;
  8460. }
  8461. tmp_rh->uri = mg_strdup(uri);
  8462. if (!tmp_rh->uri) {
  8463. mg_unlock_context(ctx);
  8464. mg_free(tmp_rh);
  8465. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8466. return;
  8467. }
  8468. tmp_rh->uri_len = urilen;
  8469. if (handler_type == REQUEST_HANDLER) {
  8470. tmp_rh->handler = handler;
  8471. } else if (handler_type == WEBSOCKET_HANDLER) {
  8472. tmp_rh->connect_handler = connect_handler;
  8473. tmp_rh->ready_handler = ready_handler;
  8474. tmp_rh->data_handler = data_handler;
  8475. tmp_rh->close_handler = close_handler;
  8476. } else { /* AUTH_HANDLER */
  8477. tmp_rh->auth_handler = auth_handler;
  8478. }
  8479. tmp_rh->cbdata = cbdata;
  8480. tmp_rh->handler_type = handler_type;
  8481. tmp_rh->next = NULL;
  8482. *lastref = tmp_rh;
  8483. mg_unlock_context(ctx);
  8484. }
  8485. void
  8486. mg_set_request_handler(struct mg_context *ctx,
  8487. const char *uri,
  8488. mg_request_handler handler,
  8489. void *cbdata)
  8490. {
  8491. mg_set_handler_type(ctx,
  8492. uri,
  8493. REQUEST_HANDLER,
  8494. handler == NULL,
  8495. handler,
  8496. NULL,
  8497. NULL,
  8498. NULL,
  8499. NULL,
  8500. NULL,
  8501. cbdata);
  8502. }
  8503. void
  8504. mg_set_websocket_handler(struct mg_context *ctx,
  8505. const char *uri,
  8506. mg_websocket_connect_handler connect_handler,
  8507. mg_websocket_ready_handler ready_handler,
  8508. mg_websocket_data_handler data_handler,
  8509. mg_websocket_close_handler close_handler,
  8510. void *cbdata)
  8511. {
  8512. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8513. && (data_handler == NULL)
  8514. && (close_handler == NULL);
  8515. mg_set_handler_type(ctx,
  8516. uri,
  8517. WEBSOCKET_HANDLER,
  8518. is_delete_request,
  8519. NULL,
  8520. connect_handler,
  8521. ready_handler,
  8522. data_handler,
  8523. close_handler,
  8524. NULL,
  8525. cbdata);
  8526. }
  8527. void
  8528. mg_set_auth_handler(struct mg_context *ctx,
  8529. const char *uri,
  8530. mg_request_handler handler,
  8531. void *cbdata)
  8532. {
  8533. mg_set_handler_type(ctx,
  8534. uri,
  8535. AUTH_HANDLER,
  8536. handler == NULL,
  8537. NULL,
  8538. NULL,
  8539. NULL,
  8540. NULL,
  8541. NULL,
  8542. handler,
  8543. cbdata);
  8544. }
  8545. static int
  8546. get_request_handler(struct mg_connection *conn,
  8547. int handler_type,
  8548. mg_request_handler *handler,
  8549. mg_websocket_connect_handler *connect_handler,
  8550. mg_websocket_ready_handler *ready_handler,
  8551. mg_websocket_data_handler *data_handler,
  8552. mg_websocket_close_handler *close_handler,
  8553. mg_authorization_handler *auth_handler,
  8554. void **cbdata)
  8555. {
  8556. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8557. if (request_info) {
  8558. const char *uri = request_info->local_uri;
  8559. size_t urilen = strlen(uri);
  8560. struct mg_handler_info *tmp_rh;
  8561. if (!conn || !conn->ctx) {
  8562. return 0;
  8563. }
  8564. mg_lock_context(conn->ctx);
  8565. /* first try for an exact match */
  8566. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8567. tmp_rh = tmp_rh->next) {
  8568. if (tmp_rh->handler_type == handler_type) {
  8569. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8570. if (handler_type == WEBSOCKET_HANDLER) {
  8571. *connect_handler = tmp_rh->connect_handler;
  8572. *ready_handler = tmp_rh->ready_handler;
  8573. *data_handler = tmp_rh->data_handler;
  8574. *close_handler = tmp_rh->close_handler;
  8575. } else if (handler_type == REQUEST_HANDLER) {
  8576. *handler = tmp_rh->handler;
  8577. } else { /* AUTH_HANDLER */
  8578. *auth_handler = tmp_rh->auth_handler;
  8579. }
  8580. *cbdata = tmp_rh->cbdata;
  8581. mg_unlock_context(conn->ctx);
  8582. return 1;
  8583. }
  8584. }
  8585. }
  8586. /* next try for a partial match, we will accept uri/something */
  8587. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8588. tmp_rh = tmp_rh->next) {
  8589. if (tmp_rh->handler_type == handler_type) {
  8590. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8591. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8592. if (handler_type == WEBSOCKET_HANDLER) {
  8593. *connect_handler = tmp_rh->connect_handler;
  8594. *ready_handler = tmp_rh->ready_handler;
  8595. *data_handler = tmp_rh->data_handler;
  8596. *close_handler = tmp_rh->close_handler;
  8597. } else if (handler_type == REQUEST_HANDLER) {
  8598. *handler = tmp_rh->handler;
  8599. } else { /* AUTH_HANDLER */
  8600. *auth_handler = tmp_rh->auth_handler;
  8601. }
  8602. *cbdata = tmp_rh->cbdata;
  8603. mg_unlock_context(conn->ctx);
  8604. return 1;
  8605. }
  8606. }
  8607. }
  8608. /* finally try for pattern match */
  8609. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8610. tmp_rh = tmp_rh->next) {
  8611. if (tmp_rh->handler_type == handler_type) {
  8612. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8613. if (handler_type == WEBSOCKET_HANDLER) {
  8614. *connect_handler = tmp_rh->connect_handler;
  8615. *ready_handler = tmp_rh->ready_handler;
  8616. *data_handler = tmp_rh->data_handler;
  8617. *close_handler = tmp_rh->close_handler;
  8618. } else if (handler_type == REQUEST_HANDLER) {
  8619. *handler = tmp_rh->handler;
  8620. } else { /* AUTH_HANDLER */
  8621. *auth_handler = tmp_rh->auth_handler;
  8622. }
  8623. *cbdata = tmp_rh->cbdata;
  8624. mg_unlock_context(conn->ctx);
  8625. return 1;
  8626. }
  8627. }
  8628. }
  8629. mg_unlock_context(conn->ctx);
  8630. }
  8631. return 0; /* none found */
  8632. }
  8633. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8634. static int
  8635. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8636. void *cbdata)
  8637. {
  8638. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8639. if (pcallbacks->websocket_connect) {
  8640. return pcallbacks->websocket_connect(conn);
  8641. }
  8642. /* No handler set - assume "OK" */
  8643. return 0;
  8644. }
  8645. static void
  8646. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8647. {
  8648. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8649. if (pcallbacks->websocket_ready) {
  8650. pcallbacks->websocket_ready(conn);
  8651. }
  8652. }
  8653. static int
  8654. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8655. int bits,
  8656. char *data,
  8657. size_t len,
  8658. void *cbdata)
  8659. {
  8660. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8661. if (pcallbacks->websocket_data) {
  8662. return pcallbacks->websocket_data(conn, bits, data, len);
  8663. }
  8664. /* No handler set - assume "OK" */
  8665. return 1;
  8666. }
  8667. #endif
  8668. /* This is the heart of the Civetweb's logic.
  8669. * This function is called when the request is read, parsed and validated,
  8670. * and Civetweb must decide what action to take: serve a file, or
  8671. * a directory, or call embedded function, etcetera. */
  8672. static void
  8673. handle_request(struct mg_connection *conn)
  8674. {
  8675. if (conn) {
  8676. struct mg_request_info *ri = &conn->request_info;
  8677. char path[PATH_MAX];
  8678. int uri_len, ssl_index;
  8679. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8680. is_put_or_delete_request = 0, is_callback_resource = 0;
  8681. int i;
  8682. struct file file = STRUCT_FILE_INITIALIZER;
  8683. mg_request_handler callback_handler = NULL;
  8684. mg_websocket_connect_handler ws_connect_handler = NULL;
  8685. mg_websocket_ready_handler ws_ready_handler = NULL;
  8686. mg_websocket_data_handler ws_data_handler = NULL;
  8687. mg_websocket_close_handler ws_close_handler = NULL;
  8688. void *callback_data = NULL;
  8689. mg_authorization_handler auth_handler = NULL;
  8690. void *auth_callback_data = NULL;
  8691. #if !defined(NO_FILES)
  8692. time_t curtime = time(NULL);
  8693. char date[64];
  8694. #endif
  8695. path[0] = 0;
  8696. if (!ri) {
  8697. return;
  8698. }
  8699. /* 1. get the request url */
  8700. /* 1.1. split into url and query string */
  8701. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8702. != NULL) {
  8703. *((char *)conn->request_info.query_string++) = '\0';
  8704. }
  8705. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8706. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8707. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8708. if (ssl_index >= 0) {
  8709. redirect_to_https_port(conn, ssl_index);
  8710. } else {
  8711. /* A http to https forward port has been specified,
  8712. * but no https port to forward to. */
  8713. send_http_error(conn,
  8714. 503,
  8715. "%s",
  8716. "Error: SSL forward not configured properly");
  8717. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8718. }
  8719. return;
  8720. }
  8721. uri_len = (int)strlen(ri->local_uri);
  8722. /* 1.3. decode url (if config says so) */
  8723. if (should_decode_url(conn)) {
  8724. mg_url_decode(
  8725. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8726. }
  8727. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8728. * not possible */
  8729. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8730. /* step 1. completed, the url is known now */
  8731. DEBUG_TRACE("URL: %s", ri->local_uri);
  8732. /* 3. if this ip has limited speed, set it for this connection */
  8733. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8734. get_remote_ip(conn),
  8735. ri->local_uri);
  8736. /* 4. call a "handle everything" callback, if registered */
  8737. if (conn->ctx->callbacks.begin_request != NULL) {
  8738. /* Note that since V1.7 the "begin_request" function is called
  8739. * before an authorization check. If an authorization check is
  8740. * required, use a request_handler instead. */
  8741. i = conn->ctx->callbacks.begin_request(conn);
  8742. if (i > 0) {
  8743. /* callback already processed the request. Store the
  8744. return value as a status code for the access log. */
  8745. conn->status_code = i;
  8746. return;
  8747. } else if (i == 0) {
  8748. /* civetweb should process the request */
  8749. } else {
  8750. /* unspecified - may change with the next version */
  8751. return;
  8752. }
  8753. }
  8754. /* request not yet handled by a handler or redirect, so the request
  8755. * is processed here */
  8756. /* 5. interpret the url to find out how the request must be handled
  8757. */
  8758. /* 5.1. first test, if the request targets the regular http(s)://
  8759. * protocol namespace or the websocket ws(s):// protocol namespace.
  8760. */
  8761. is_websocket_request = is_websocket_protocol(conn);
  8762. /* 5.2. check if the request will be handled by a callback */
  8763. if (get_request_handler(conn,
  8764. is_websocket_request ? WEBSOCKET_HANDLER
  8765. : REQUEST_HANDLER,
  8766. &callback_handler,
  8767. &ws_connect_handler,
  8768. &ws_ready_handler,
  8769. &ws_data_handler,
  8770. &ws_close_handler,
  8771. NULL,
  8772. &callback_data)) {
  8773. /* 5.2.1. A callback will handle this request. All requests
  8774. * handled
  8775. * by a callback have to be considered as requests to a script
  8776. * resource. */
  8777. is_callback_resource = 1;
  8778. is_script_resource = 1;
  8779. is_put_or_delete_request = is_put_or_delete_method(conn);
  8780. } else {
  8781. no_callback_resource:
  8782. /* 5.2.2. No callback is responsible for this request. The URI
  8783. * addresses a file based resource (static content or Lua/cgi
  8784. * scripts in the file system). */
  8785. is_callback_resource = 0;
  8786. interpret_uri(conn,
  8787. path,
  8788. sizeof(path),
  8789. &file,
  8790. &is_found,
  8791. &is_script_resource,
  8792. &is_websocket_request,
  8793. &is_put_or_delete_request);
  8794. }
  8795. /* 6. authorization check */
  8796. /* 6.1. a custom authorization handler is installed */
  8797. if (get_request_handler(conn,
  8798. AUTH_HANDLER,
  8799. NULL,
  8800. NULL,
  8801. NULL,
  8802. NULL,
  8803. NULL,
  8804. &auth_handler,
  8805. &auth_callback_data)) {
  8806. if (!auth_handler(conn, auth_callback_data)) {
  8807. return;
  8808. }
  8809. } else if (is_put_or_delete_request && !is_script_resource
  8810. && !is_callback_resource) {
  8811. /* 6.2. this request is a PUT/DELETE to a real file */
  8812. /* 6.2.1. thus, the server must have real files */
  8813. #if defined(NO_FILES)
  8814. if (1) {
  8815. #else
  8816. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8817. #endif
  8818. /* This server does not have any real files, thus the
  8819. * PUT/DELETE methods are not valid. */
  8820. send_http_error(conn,
  8821. 405,
  8822. "%s method not allowed",
  8823. conn->request_info.request_method);
  8824. return;
  8825. }
  8826. #if !defined(NO_FILES)
  8827. /* 6.2.2. Check if put authorization for static files is
  8828. * available.
  8829. */
  8830. if (!is_authorized_for_put(conn)) {
  8831. send_authorization_request(conn);
  8832. return;
  8833. }
  8834. #endif
  8835. } else {
  8836. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8837. * or it is a PUT or DELETE request to a resource that does not
  8838. * correspond to a file. Check authorization. */
  8839. if (!check_authorization(conn, path)) {
  8840. send_authorization_request(conn);
  8841. return;
  8842. }
  8843. }
  8844. /* request is authorized or does not need authorization */
  8845. /* 7. check if there are request handlers for this uri */
  8846. if (is_callback_resource) {
  8847. if (!is_websocket_request) {
  8848. i = callback_handler(conn, callback_data);
  8849. if (i > 0) {
  8850. /* Do nothing, callback has served the request. Store
  8851. * the
  8852. * return value as status code for the log and discard
  8853. * all
  8854. * data from the client not used by the callback. */
  8855. conn->status_code = i;
  8856. discard_unread_request_data(conn);
  8857. } else {
  8858. /* TODO (high): what if the handler did NOT handle the
  8859. * request */
  8860. /* The last version did handle this as a file request,
  8861. * but
  8862. * since a file request is not always a script resource,
  8863. * the authorization check might be different */
  8864. interpret_uri(conn,
  8865. path,
  8866. sizeof(path),
  8867. &file,
  8868. &is_found,
  8869. &is_script_resource,
  8870. &is_websocket_request,
  8871. &is_put_or_delete_request);
  8872. callback_handler = NULL;
  8873. /* TODO (very low): goto is deprecated but for the
  8874. * moment,
  8875. * a goto is simpler than some curious loop. */
  8876. /* The situation "callback does not handle the request"
  8877. * needs to be reconsidered anyway. */
  8878. goto no_callback_resource;
  8879. }
  8880. } else {
  8881. #if defined(USE_WEBSOCKET)
  8882. handle_websocket_request(conn,
  8883. path,
  8884. is_callback_resource,
  8885. ws_connect_handler,
  8886. ws_ready_handler,
  8887. ws_data_handler,
  8888. ws_close_handler,
  8889. callback_data);
  8890. #endif
  8891. }
  8892. return;
  8893. }
  8894. /* 8. handle websocket requests */
  8895. #if defined(USE_WEBSOCKET)
  8896. if (is_websocket_request) {
  8897. if (is_script_resource) {
  8898. /* Websocket Lua script */
  8899. handle_websocket_request(conn,
  8900. path,
  8901. 0 /* Lua Script */,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. NULL,
  8906. &conn->ctx->callbacks);
  8907. } else {
  8908. #if defined(MG_LEGACY_INTERFACE)
  8909. handle_websocket_request(
  8910. conn,
  8911. path,
  8912. !is_script_resource /* could be deprecated global callback */,
  8913. deprecated_websocket_connect_wrapper,
  8914. deprecated_websocket_ready_wrapper,
  8915. deprecated_websocket_data_wrapper,
  8916. NULL,
  8917. &conn->ctx->callbacks);
  8918. #else
  8919. send_http_error(conn, 404, "%s", "Not found");
  8920. #endif
  8921. }
  8922. return;
  8923. } else
  8924. #endif
  8925. #if defined(NO_FILES)
  8926. /* 9a. In case the server uses only callbacks, this uri is
  8927. * unknown.
  8928. * Then, all request handling ends here. */
  8929. send_http_error(conn, 404, "%s", "Not Found");
  8930. #else
  8931. /* 9b. This request is either for a static file or resource handled
  8932. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8933. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8934. send_http_error(conn, 404, "%s", "Not Found");
  8935. return;
  8936. }
  8937. /* 10. File is handled by a script. */
  8938. if (is_script_resource) {
  8939. handle_file_based_request(conn, path, &file);
  8940. return;
  8941. }
  8942. /* 11. Handle put/delete/mkcol requests */
  8943. if (is_put_or_delete_request) {
  8944. /* 11.1. PUT method */
  8945. if (!strcmp(ri->request_method, "PUT")) {
  8946. put_file(conn, path);
  8947. return;
  8948. }
  8949. /* 11.2. DELETE method */
  8950. if (!strcmp(ri->request_method, "DELETE")) {
  8951. delete_file(conn, path);
  8952. return;
  8953. }
  8954. /* 11.3. MKCOL method */
  8955. if (!strcmp(ri->request_method, "MKCOL")) {
  8956. mkcol(conn, path);
  8957. return;
  8958. }
  8959. /* 11.4. PATCH method
  8960. * This method is not supported for static resources,
  8961. * only for scripts (Lua, CGI) and callbacks. */
  8962. send_http_error(conn,
  8963. 405,
  8964. "%s method not allowed",
  8965. conn->request_info.request_method);
  8966. return;
  8967. }
  8968. /* 11. File does not exist, or it was configured that it should be
  8969. * hidden */
  8970. if (!is_found || (must_hide_file(conn, path))) {
  8971. send_http_error(conn, 404, "%s", "Not found");
  8972. return;
  8973. }
  8974. /* 12. Directory uris should end with a slash */
  8975. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8976. gmt_time_string(date, sizeof(date), &curtime);
  8977. mg_printf(conn,
  8978. "HTTP/1.1 301 Moved Permanently\r\n"
  8979. "Location: %s/\r\n"
  8980. "Date: %s\r\n"
  8981. /* "Cache-Control: private\r\n" (= default) */
  8982. "Content-Length: 0\r\n"
  8983. "Connection: %s\r\n\r\n",
  8984. ri->request_uri,
  8985. date,
  8986. suggest_connection_header(conn));
  8987. return;
  8988. }
  8989. /* 13. Handle other methods than GET/HEAD */
  8990. /* 13.1. Handle PROPFIND */
  8991. if (!strcmp(ri->request_method, "PROPFIND")) {
  8992. handle_propfind(conn, path, &file);
  8993. return;
  8994. }
  8995. /* 13.2. Handle OPTIONS for files */
  8996. if (!strcmp(ri->request_method, "OPTIONS")) {
  8997. /* This standard handler is only used for real files.
  8998. * Scripts should support the OPTIONS method themselves, to allow a
  8999. * maximum flexibility.
  9000. * Lua and CGI scripts may fully support CORS this way (including
  9001. * preflights). */
  9002. send_options(conn);
  9003. return;
  9004. }
  9005. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9006. if (0 != strcmp(ri->request_method, "GET")
  9007. && 0 != strcmp(ri->request_method, "HEAD")) {
  9008. send_http_error(conn,
  9009. 405,
  9010. "%s method not allowed",
  9011. conn->request_info.request_method);
  9012. return;
  9013. }
  9014. /* 14. directories */
  9015. if (file.is_directory) {
  9016. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9017. /* 14.1. use a substitute file */
  9018. /* TODO (high): substitute index may be a script resource.
  9019. * define what should be possible in this case. */
  9020. } else {
  9021. /* 14.2. no substitute file */
  9022. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9023. "yes")) {
  9024. handle_directory_request(conn, path);
  9025. } else {
  9026. send_http_error(conn,
  9027. 403,
  9028. "%s",
  9029. "Error: Directory listing denied");
  9030. }
  9031. return;
  9032. }
  9033. }
  9034. handle_file_based_request(conn, path, &file);
  9035. #endif /* !defined(NO_FILES) */
  9036. #if 0
  9037. /* Perform redirect and auth checks before calling begin_request()
  9038. * handler.
  9039. * Otherwise, begin_request() would need to perform auth checks and
  9040. * redirects. */
  9041. #endif
  9042. }
  9043. return;
  9044. }
  9045. static void
  9046. handle_file_based_request(struct mg_connection *conn,
  9047. const char *path,
  9048. struct file *file)
  9049. {
  9050. if (!conn || !conn->ctx) {
  9051. return;
  9052. }
  9053. if (0) {
  9054. #ifdef USE_LUA
  9055. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9056. strlen(
  9057. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9058. path) > 0) {
  9059. /* Lua server page: an SSI like page containing mostly plain html
  9060. * code
  9061. * plus some tags with server generated contents. */
  9062. handle_lsp_request(conn, path, file, NULL);
  9063. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9064. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9065. path) > 0) {
  9066. /* Lua in-server module script: a CGI like script used to generate
  9067. * the
  9068. * entire reply. */
  9069. mg_exec_lua_script(conn, path, NULL);
  9070. #endif
  9071. #if defined(USE_DUKTAPE)
  9072. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9073. strlen(
  9074. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9075. path) > 0) {
  9076. /* Call duktape to generate the page */
  9077. mg_exec_duktape_script(conn, path);
  9078. #endif
  9079. #if !defined(NO_CGI)
  9080. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9081. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9082. path) > 0) {
  9083. /* CGI scripts may support all HTTP methods */
  9084. handle_cgi_request(conn, path);
  9085. #endif /* !NO_CGI */
  9086. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9087. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9088. path) > 0) {
  9089. handle_ssi_file_request(conn, path, file);
  9090. #if !defined(NO_CACHING)
  9091. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9092. /* Send 304 "Not Modified" - this must not send any body data */
  9093. handle_not_modified_static_file_request(conn, file);
  9094. #endif /* !NO_CACHING */
  9095. } else {
  9096. handle_static_file_request(conn, path, file, NULL);
  9097. }
  9098. }
  9099. static void
  9100. close_all_listening_sockets(struct mg_context *ctx)
  9101. {
  9102. unsigned int i;
  9103. if (!ctx) {
  9104. return;
  9105. }
  9106. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9107. closesocket(ctx->listening_sockets[i].sock);
  9108. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9109. }
  9110. mg_free(ctx->listening_sockets);
  9111. ctx->listening_sockets = NULL;
  9112. mg_free(ctx->listening_socket_fds);
  9113. ctx->listening_socket_fds = NULL;
  9114. }
  9115. /* Valid listening port specification is: [ip_address:]port[s]
  9116. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9117. * Examples for IPv6: [::]:80, [::1]:80,
  9118. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9119. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9120. static int
  9121. parse_port_string(const struct vec *vec, struct socket *so)
  9122. {
  9123. unsigned int a, b, c, d, port;
  9124. int ch, len;
  9125. #if defined(USE_IPV6)
  9126. char buf[100] = {0};
  9127. #endif
  9128. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9129. * Also, all-zeroes in the socket address means binding to all addresses
  9130. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9131. memset(so, 0, sizeof(*so));
  9132. so->lsa.sin.sin_family = AF_INET;
  9133. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9134. == 5) {
  9135. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9136. so->lsa.sin.sin_addr.s_addr =
  9137. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9138. so->lsa.sin.sin_port = htons((uint16_t)port);
  9139. #if defined(USE_IPV6)
  9140. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9141. && mg_inet_pton(
  9142. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9143. /* IPv6 address, examples: see above */
  9144. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9145. */
  9146. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9147. #endif
  9148. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9149. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9150. so->lsa.sin.sin_port = htons((uint16_t)port);
  9151. } else {
  9152. /* Parsing failure. Make port invalid. */
  9153. port = 0;
  9154. len = 0;
  9155. }
  9156. /* sscanf and the option splitting code ensure the following condition
  9157. */
  9158. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9159. return 0;
  9160. }
  9161. ch = vec->ptr[len]; /* Next character after the port number */
  9162. so->is_ssl = (ch == 's');
  9163. so->ssl_redir = (ch == 'r');
  9164. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9165. return is_valid_port(port)
  9166. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9167. }
  9168. static int
  9169. set_ports_option(struct mg_context *ctx)
  9170. {
  9171. const char *list;
  9172. int on = 1;
  9173. #if defined(USE_IPV6)
  9174. int off = 0;
  9175. #endif
  9176. struct vec vec;
  9177. struct socket so, *ptr;
  9178. struct pollfd *pfd;
  9179. union usa usa;
  9180. socklen_t len;
  9181. int portsTotal = 0;
  9182. int portsOk = 0;
  9183. if (!ctx) {
  9184. return 0;
  9185. }
  9186. memset(&so, 0, sizeof(so));
  9187. memset(&usa, 0, sizeof(usa));
  9188. len = sizeof(usa);
  9189. list = ctx->config[LISTENING_PORTS];
  9190. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9191. portsTotal++;
  9192. if (!parse_port_string(&vec, &so)) {
  9193. mg_cry(fc(ctx),
  9194. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9195. (int)vec.len,
  9196. vec.ptr,
  9197. portsTotal,
  9198. "[IP_ADDRESS:]PORT[s|r]");
  9199. continue;
  9200. }
  9201. #if !defined(NO_SSL)
  9202. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9203. mg_cry(fc(ctx),
  9204. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9205. "option set?",
  9206. portsTotal);
  9207. continue;
  9208. }
  9209. #endif
  9210. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9211. == INVALID_SOCKET) {
  9212. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9213. continue;
  9214. }
  9215. #ifdef _WIN32
  9216. /* Windows SO_REUSEADDR lets many procs binds to a
  9217. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9218. * if someone already has the socket -- DTL */
  9219. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9220. * Windows might need a few seconds before
  9221. * the same port can be used again in the
  9222. * same process, so a short Sleep may be
  9223. * required between mg_stop and mg_start.
  9224. */
  9225. if (setsockopt(so.sock,
  9226. SOL_SOCKET,
  9227. SO_EXCLUSIVEADDRUSE,
  9228. (SOCK_OPT_TYPE)&on,
  9229. sizeof(on)) != 0) {
  9230. mg_cry(fc(ctx),
  9231. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9232. portsTotal);
  9233. }
  9234. #else
  9235. if (setsockopt(so.sock,
  9236. SOL_SOCKET,
  9237. SO_REUSEADDR,
  9238. (SOCK_OPT_TYPE)&on,
  9239. sizeof(on)) != 0) {
  9240. mg_cry(fc(ctx),
  9241. "cannot set socket option SO_REUSEADDR (entry %i)",
  9242. portsTotal);
  9243. }
  9244. #endif
  9245. #if defined(USE_IPV6)
  9246. if (so.lsa.sa.sa_family == AF_INET6
  9247. && setsockopt(so.sock,
  9248. IPPROTO_IPV6,
  9249. IPV6_V6ONLY,
  9250. (void *)&off,
  9251. sizeof(off)) != 0) {
  9252. mg_cry(fc(ctx),
  9253. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9254. portsTotal);
  9255. }
  9256. #endif
  9257. if (so.lsa.sa.sa_family == AF_INET) {
  9258. len = sizeof(so.lsa.sin);
  9259. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9260. mg_cry(fc(ctx),
  9261. "cannot bind to %.*s: %d (%s)",
  9262. (int)vec.len,
  9263. vec.ptr,
  9264. (int)ERRNO,
  9265. strerror(errno));
  9266. closesocket(so.sock);
  9267. so.sock = INVALID_SOCKET;
  9268. continue;
  9269. }
  9270. }
  9271. #if defined(USE_IPV6)
  9272. else if (so.lsa.sa.sa_family == AF_INET6) {
  9273. len = sizeof(so.lsa.sin6);
  9274. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9275. mg_cry(fc(ctx),
  9276. "cannot bind to IPv6 %.*s: %d (%s)",
  9277. (int)vec.len,
  9278. vec.ptr,
  9279. (int)ERRNO,
  9280. strerror(errno));
  9281. closesocket(so.sock);
  9282. so.sock = INVALID_SOCKET;
  9283. continue;
  9284. }
  9285. }
  9286. #endif
  9287. else {
  9288. mg_cry(fc(ctx),
  9289. "cannot bind: address family not supported (entry %i)",
  9290. portsTotal);
  9291. continue;
  9292. }
  9293. if (listen(so.sock, SOMAXCONN) != 0) {
  9294. mg_cry(fc(ctx),
  9295. "cannot listen to %.*s: %d (%s)",
  9296. (int)vec.len,
  9297. vec.ptr,
  9298. (int)ERRNO,
  9299. strerror(errno));
  9300. closesocket(so.sock);
  9301. so.sock = INVALID_SOCKET;
  9302. continue;
  9303. }
  9304. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9305. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9306. int err = (int)ERRNO;
  9307. mg_cry(fc(ctx),
  9308. "call to getsockname failed %.*s: %d (%s)",
  9309. (int)vec.len,
  9310. vec.ptr,
  9311. err,
  9312. strerror(errno));
  9313. closesocket(so.sock);
  9314. so.sock = INVALID_SOCKET;
  9315. continue;
  9316. }
  9317. /* Update lsa port in case of random free ports */
  9318. #if defined(USE_IPV6)
  9319. if (so.lsa.sa.sa_family == AF_INET6) {
  9320. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9321. } else
  9322. #endif
  9323. {
  9324. so.lsa.sin.sin_port = usa.sin.sin_port;
  9325. }
  9326. if ((ptr = (struct socket *)
  9327. mg_realloc(ctx->listening_sockets,
  9328. (ctx->num_listening_sockets + 1)
  9329. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9330. mg_cry(fc(ctx), "%s", "Out of memory");
  9331. closesocket(so.sock);
  9332. so.sock = INVALID_SOCKET;
  9333. continue;
  9334. }
  9335. if ((pfd = (struct pollfd *)mg_realloc(
  9336. ctx->listening_socket_fds,
  9337. (ctx->num_listening_sockets + 1)
  9338. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9339. mg_cry(fc(ctx), "%s", "Out of memory");
  9340. closesocket(so.sock);
  9341. so.sock = INVALID_SOCKET;
  9342. mg_free(ptr);
  9343. continue;
  9344. }
  9345. set_close_on_exec(so.sock, fc(ctx));
  9346. ctx->listening_sockets = ptr;
  9347. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9348. ctx->listening_socket_fds = pfd;
  9349. ctx->num_listening_sockets++;
  9350. portsOk++;
  9351. }
  9352. if (portsOk != portsTotal) {
  9353. close_all_listening_sockets(ctx);
  9354. portsOk = 0;
  9355. }
  9356. return portsOk;
  9357. }
  9358. static const char *
  9359. header_val(const struct mg_connection *conn, const char *header)
  9360. {
  9361. const char *header_value;
  9362. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9363. return "-";
  9364. } else {
  9365. return header_value;
  9366. }
  9367. }
  9368. static void
  9369. log_access(const struct mg_connection *conn)
  9370. {
  9371. const struct mg_request_info *ri;
  9372. struct file fi;
  9373. char date[64], src_addr[IP_ADDR_STR_LEN];
  9374. struct tm *tm;
  9375. const char *referer;
  9376. const char *user_agent;
  9377. char buf[4096];
  9378. if (!conn || !conn->ctx) {
  9379. return;
  9380. }
  9381. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9382. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9383. == 0) {
  9384. fi.fp = NULL;
  9385. }
  9386. } else {
  9387. fi.fp = NULL;
  9388. }
  9389. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9390. return;
  9391. }
  9392. tm = localtime(&conn->conn_birth_time);
  9393. if (tm != NULL) {
  9394. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9395. } else {
  9396. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9397. date[sizeof(date) - 1] = '\0';
  9398. }
  9399. ri = &conn->request_info;
  9400. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9401. referer = header_val(conn, "Referer");
  9402. user_agent = header_val(conn, "User-Agent");
  9403. mg_snprintf(conn,
  9404. NULL, /* Ignore truncation in access log */
  9405. buf,
  9406. sizeof(buf),
  9407. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9408. src_addr,
  9409. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9410. date,
  9411. ri->request_method ? ri->request_method : "-",
  9412. ri->request_uri ? ri->request_uri : "-",
  9413. ri->query_string ? "?" : "",
  9414. ri->query_string ? ri->query_string : "",
  9415. ri->http_version,
  9416. conn->status_code,
  9417. conn->num_bytes_sent,
  9418. referer,
  9419. user_agent);
  9420. if (conn->ctx->callbacks.log_access) {
  9421. conn->ctx->callbacks.log_access(conn, buf);
  9422. }
  9423. if (fi.fp) {
  9424. flockfile(fi.fp);
  9425. fprintf(fi.fp, "%s\n", buf);
  9426. fflush(fi.fp);
  9427. funlockfile(fi.fp);
  9428. mg_fclose(&fi);
  9429. }
  9430. }
  9431. /* Verify given socket address against the ACL.
  9432. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9433. */
  9434. static int
  9435. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9436. {
  9437. int allowed, flag;
  9438. uint32_t net, mask;
  9439. struct vec vec;
  9440. if (ctx) {
  9441. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9442. /* If any ACL is set, deny by default */
  9443. allowed = (list == NULL) ? '+' : '-';
  9444. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9445. flag = vec.ptr[0];
  9446. if ((flag != '+' && flag != '-')
  9447. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9448. mg_cry(fc(ctx),
  9449. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9450. __func__);
  9451. return -1;
  9452. }
  9453. if (net == (remote_ip & mask)) {
  9454. allowed = flag;
  9455. }
  9456. }
  9457. return allowed == '+';
  9458. }
  9459. return -1;
  9460. }
  9461. #if !defined(_WIN32)
  9462. static int
  9463. set_uid_option(struct mg_context *ctx)
  9464. {
  9465. struct passwd *pw;
  9466. if (ctx) {
  9467. const char *uid = ctx->config[RUN_AS_USER];
  9468. int success = 0;
  9469. if (uid == NULL) {
  9470. success = 1;
  9471. } else {
  9472. if ((pw = getpwnam(uid)) == NULL) {
  9473. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9474. } else if (setgid(pw->pw_gid) == -1) {
  9475. mg_cry(fc(ctx),
  9476. "%s: setgid(%s): %s",
  9477. __func__,
  9478. uid,
  9479. strerror(errno));
  9480. } else if (setgroups(0, NULL)) {
  9481. mg_cry(fc(ctx),
  9482. "%s: setgroups(): %s",
  9483. __func__,
  9484. strerror(errno));
  9485. } else if (setuid(pw->pw_uid) == -1) {
  9486. mg_cry(fc(ctx),
  9487. "%s: setuid(%s): %s",
  9488. __func__,
  9489. uid,
  9490. strerror(errno));
  9491. } else {
  9492. success = 1;
  9493. }
  9494. }
  9495. return success;
  9496. }
  9497. return 0;
  9498. }
  9499. #endif /* !_WIN32 */
  9500. static void
  9501. tls_dtor(void *key)
  9502. {
  9503. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9504. /* key == pthread_getspecific(sTlsKey); */
  9505. if (tls) {
  9506. if (tls->is_master == 2) {
  9507. tls->is_master = -3; /* Mark memory as dead */
  9508. mg_free(tls);
  9509. }
  9510. }
  9511. pthread_setspecific(sTlsKey, NULL);
  9512. }
  9513. #if !defined(NO_SSL)
  9514. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9515. static unsigned long
  9516. ssl_id_callback(void)
  9517. {
  9518. #ifdef _WIN32
  9519. return GetCurrentThreadId();
  9520. #else
  9521. #ifdef __clang__
  9522. #pragma clang diagnostic push
  9523. #pragma clang diagnostic ignored "-Wunreachable-code"
  9524. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9525. * or not, so one of the two conditions will be unreachable by construction.
  9526. * Unfortunately the C standard does not define a way to check this at
  9527. * compile time, since the #if preprocessor conditions can not use the sizeof
  9528. * operator as an argument. */
  9529. #endif
  9530. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9531. /* This is the problematic case for CRYPTO_set_id_callback:
  9532. * The OS pthread_t can not be cast to unsigned long. */
  9533. struct mg_workerTLS *tls =
  9534. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9535. if (tls == NULL) {
  9536. /* SSL called from an unknown thread: Create some thread index.
  9537. */
  9538. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9539. tls->is_master = -2; /* -2 means "3rd party thread" */
  9540. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9541. pthread_setspecific(sTlsKey, tls);
  9542. }
  9543. return tls->thread_idx;
  9544. } else {
  9545. /* pthread_t may be any data type, so a simple cast to unsigned long
  9546. * can rise a warning/error, depending on the platform.
  9547. * Here memcpy is used as an anything-to-anything cast. */
  9548. unsigned long ret = 0;
  9549. pthread_t t = pthread_self();
  9550. memcpy(&ret, &t, sizeof(pthread_t));
  9551. return ret;
  9552. }
  9553. #ifdef __clang__
  9554. #pragma clang diagnostic pop
  9555. #endif
  9556. #endif
  9557. }
  9558. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9559. static const char *ssl_error(void);
  9560. static int
  9561. refresh_trust(struct mg_connection *conn)
  9562. {
  9563. static int reload_lock = 0;
  9564. static long int data_check = 0;
  9565. struct stat cert_buf;
  9566. long int t;
  9567. char *pem;
  9568. int should_verify_peer;
  9569. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9570. && conn->ctx->callbacks.init_ssl == NULL) {
  9571. return 0;
  9572. }
  9573. t = data_check;
  9574. if (stat(pem, &cert_buf) != -1) {
  9575. t = (long int)cert_buf.st_mtime;
  9576. }
  9577. if (data_check != t) {
  9578. data_check = t;
  9579. should_verify_peer =
  9580. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9581. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9582. == 0);
  9583. if (should_verify_peer) {
  9584. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9585. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9586. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9587. ca_file,
  9588. ca_path) != 1) {
  9589. mg_cry(fc(conn->ctx),
  9590. "SSL_CTX_load_verify_locations error: %s "
  9591. "ssl_verify_peer requires setting "
  9592. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9593. "present in "
  9594. "the .conf file?",
  9595. ssl_error());
  9596. return 0;
  9597. }
  9598. }
  9599. if (!reload_lock) {
  9600. reload_lock = 1;
  9601. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9602. return 0;
  9603. }
  9604. reload_lock = 0;
  9605. }
  9606. }
  9607. /* lock while cert is reloading */
  9608. while (reload_lock) {
  9609. sleep(1);
  9610. }
  9611. return 1;
  9612. }
  9613. static pthread_mutex_t *ssl_mutexes;
  9614. static int
  9615. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9616. {
  9617. int ret, err;
  9618. int short_trust;
  9619. unsigned i;
  9620. if (!conn) {
  9621. return 0;
  9622. }
  9623. short_trust =
  9624. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9625. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9626. if (short_trust) {
  9627. int trust_ret = refresh_trust(conn);
  9628. if (!trust_ret) {
  9629. return trust_ret;
  9630. }
  9631. }
  9632. conn->ssl = SSL_new(s);
  9633. if (conn->ssl == NULL) {
  9634. return 0;
  9635. }
  9636. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9637. if (ret != 1) {
  9638. err = SSL_get_error(conn->ssl, ret);
  9639. (void)err; /* TODO: set some error message */
  9640. SSL_free(conn->ssl);
  9641. conn->ssl = NULL;
  9642. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9643. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9644. ERR_remove_state(0);
  9645. return 0;
  9646. }
  9647. /* SSL functions may fail and require to be called again:
  9648. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9649. * Here "func" could be SSL_connect or SSL_accept. */
  9650. for (i = 0; i <= 16; i *= 2) {
  9651. ret = func(conn->ssl);
  9652. if (ret != 1) {
  9653. err = SSL_get_error(conn->ssl, ret);
  9654. if ((err == SSL_ERROR_WANT_CONNECT)
  9655. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9656. /* Retry */
  9657. mg_sleep(i);
  9658. } else {
  9659. /* This is an error */
  9660. /* TODO: set some error message */
  9661. break;
  9662. }
  9663. } else {
  9664. /* success */
  9665. break;
  9666. }
  9667. }
  9668. if (ret != 1) {
  9669. SSL_free(conn->ssl);
  9670. conn->ssl = NULL;
  9671. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9672. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9673. ERR_remove_state(0);
  9674. return 0;
  9675. }
  9676. return 1;
  9677. }
  9678. /* Return OpenSSL error message (from CRYPTO lib) */
  9679. static const char *
  9680. ssl_error(void)
  9681. {
  9682. unsigned long err;
  9683. err = ERR_get_error();
  9684. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9685. }
  9686. static void
  9687. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9688. {
  9689. (void)line;
  9690. (void)file;
  9691. if (mode & 1) {
  9692. /* 1 is CRYPTO_LOCK */
  9693. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9694. } else {
  9695. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9696. }
  9697. }
  9698. #if !defined(NO_SSL_DL)
  9699. static void *
  9700. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9701. {
  9702. union {
  9703. void *p;
  9704. void (*fp)(void);
  9705. } u;
  9706. void *dll_handle;
  9707. struct ssl_func *fp;
  9708. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9709. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9710. return NULL;
  9711. }
  9712. for (fp = sw; fp->name != NULL; fp++) {
  9713. #ifdef _WIN32
  9714. /* GetProcAddress() returns pointer to function */
  9715. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9716. #else
  9717. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9718. * pointers to function pointers. We need to use a union to make a
  9719. * cast. */
  9720. u.p = dlsym(dll_handle, fp->name);
  9721. #endif /* _WIN32 */
  9722. if (u.fp == NULL) {
  9723. mg_cry(fc(ctx),
  9724. "%s: %s: cannot find %s",
  9725. __func__,
  9726. dll_name,
  9727. fp->name);
  9728. dlclose(dll_handle);
  9729. return NULL;
  9730. } else {
  9731. fp->ptr = u.fp;
  9732. }
  9733. }
  9734. return dll_handle;
  9735. }
  9736. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9737. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9738. #endif /* NO_SSL_DL */
  9739. #if defined(SSL_ALREADY_INITIALIZED)
  9740. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9741. #else
  9742. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9743. #endif
  9744. static int
  9745. initialize_ssl(struct mg_context *ctx)
  9746. {
  9747. int i;
  9748. size_t size;
  9749. #if !defined(NO_SSL_DL)
  9750. if (!cryptolib_dll_handle) {
  9751. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9752. if (!cryptolib_dll_handle) {
  9753. return 0;
  9754. }
  9755. }
  9756. #endif /* NO_SSL_DL */
  9757. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9758. return 1;
  9759. }
  9760. /* Initialize locking callbacks, needed for thread safety.
  9761. * http://www.openssl.org/support/faq.html#PROG1
  9762. */
  9763. i = CRYPTO_num_locks();
  9764. if (i < 0) {
  9765. i = 0;
  9766. }
  9767. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9768. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9769. mg_cry(fc(ctx),
  9770. "%s: cannot allocate mutexes: %s",
  9771. __func__,
  9772. ssl_error());
  9773. return 0;
  9774. }
  9775. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9776. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9777. }
  9778. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9779. CRYPTO_set_id_callback(&ssl_id_callback);
  9780. return 1;
  9781. }
  9782. static int
  9783. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9784. {
  9785. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9786. mg_cry(fc(ctx),
  9787. "%s: cannot open certificate file %s: %s",
  9788. __func__,
  9789. pem,
  9790. ssl_error());
  9791. return 0;
  9792. }
  9793. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9794. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9795. mg_cry(fc(ctx),
  9796. "%s: cannot open private key file %s: %s",
  9797. __func__,
  9798. pem,
  9799. ssl_error());
  9800. return 0;
  9801. }
  9802. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9803. mg_cry(fc(ctx),
  9804. "%s: certificate and private key do not match: %s",
  9805. __func__,
  9806. pem);
  9807. return 0;
  9808. }
  9809. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9810. mg_cry(fc(ctx),
  9811. "%s: cannot use certificate chain file %s: %s",
  9812. __func__,
  9813. pem,
  9814. ssl_error());
  9815. return 0;
  9816. }
  9817. return 1;
  9818. }
  9819. static long
  9820. ssl_get_protocol(int version_id)
  9821. {
  9822. long ret = SSL_OP_ALL;
  9823. if (version_id > 0)
  9824. ret |= SSL_OP_NO_SSLv2;
  9825. if (version_id > 1)
  9826. ret |= SSL_OP_NO_SSLv3;
  9827. if (version_id > 2)
  9828. ret |= SSL_OP_NO_TLSv1;
  9829. if (version_id > 3)
  9830. ret |= SSL_OP_NO_TLSv1_1;
  9831. return ret;
  9832. }
  9833. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9834. static int
  9835. set_ssl_option(struct mg_context *ctx)
  9836. {
  9837. const char *pem;
  9838. int callback_ret;
  9839. int should_verify_peer;
  9840. const char *ca_path;
  9841. const char *ca_file;
  9842. int use_default_verify_paths;
  9843. int verify_depth;
  9844. time_t now_rt = time(NULL);
  9845. struct timespec now_mt;
  9846. md5_byte_t ssl_context_id[16];
  9847. md5_state_t md5state;
  9848. int protocol_ver;
  9849. /* If PEM file is not specified and the init_ssl callback
  9850. * is not specified, skip SSL initialization. */
  9851. if (!ctx) {
  9852. return 0;
  9853. }
  9854. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9855. && ctx->callbacks.init_ssl == NULL) {
  9856. return 1;
  9857. }
  9858. if (!initialize_ssl(ctx)) {
  9859. return 0;
  9860. }
  9861. #if !defined(NO_SSL_DL)
  9862. if (!ssllib_dll_handle) {
  9863. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9864. if (!ssllib_dll_handle) {
  9865. return 0;
  9866. }
  9867. }
  9868. #endif /* NO_SSL_DL */
  9869. /* Initialize SSL library */
  9870. SSL_library_init();
  9871. SSL_load_error_strings();
  9872. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9873. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9874. return 0;
  9875. }
  9876. SSL_CTX_clear_options(ctx->ssl_ctx,
  9877. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9878. | SSL_OP_NO_TLSv1_1);
  9879. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9880. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9881. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9882. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9883. /* If a callback has been specified, call it. */
  9884. callback_ret =
  9885. (ctx->callbacks.init_ssl == NULL)
  9886. ? 0
  9887. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9888. /* If callback returns 0, civetweb sets up the SSL certificate.
  9889. * If it returns 1, civetweb assumes the calback already did this.
  9890. * If it returns -1, initializing ssl fails. */
  9891. if (callback_ret < 0) {
  9892. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9893. return 0;
  9894. }
  9895. if (callback_ret > 0) {
  9896. if (pem != NULL) {
  9897. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9898. }
  9899. return 1;
  9900. }
  9901. /* Use some UID as session context ID. */
  9902. md5_init(&md5state);
  9903. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9904. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9905. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9906. md5_append(&md5state,
  9907. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9908. strlen(ctx->config[LISTENING_PORTS]));
  9909. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9910. md5_finish(&md5state, ssl_context_id);
  9911. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9912. (const unsigned char *)&ssl_context_id,
  9913. sizeof(ssl_context_id));
  9914. if (pem != NULL) {
  9915. if (!ssl_use_pem_file(ctx, pem)) {
  9916. return 0;
  9917. }
  9918. }
  9919. should_verify_peer =
  9920. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9921. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9922. use_default_verify_paths =
  9923. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9924. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9925. if (should_verify_peer) {
  9926. ca_path = ctx->config[SSL_CA_PATH];
  9927. ca_file = ctx->config[SSL_CA_FILE];
  9928. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9929. != 1) {
  9930. mg_cry(fc(ctx),
  9931. "SSL_CTX_load_verify_locations error: %s "
  9932. "ssl_verify_peer requires setting "
  9933. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9934. "present in "
  9935. "the .conf file?",
  9936. ssl_error());
  9937. return 0;
  9938. }
  9939. SSL_CTX_set_verify(ctx->ssl_ctx,
  9940. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9941. NULL);
  9942. if (use_default_verify_paths
  9943. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9944. mg_cry(fc(ctx),
  9945. "SSL_CTX_set_default_verify_paths error: %s",
  9946. ssl_error());
  9947. return 0;
  9948. }
  9949. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9950. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9951. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9952. }
  9953. }
  9954. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9955. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9956. != 1) {
  9957. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9958. }
  9959. }
  9960. return 1;
  9961. }
  9962. static void
  9963. uninitialize_ssl(struct mg_context *ctx)
  9964. {
  9965. int i;
  9966. (void)ctx;
  9967. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9968. /* Shutdown according to
  9969. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9970. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9971. */
  9972. CRYPTO_set_locking_callback(NULL);
  9973. CRYPTO_set_id_callback(NULL);
  9974. ENGINE_cleanup();
  9975. CONF_modules_unload(1);
  9976. ERR_free_strings();
  9977. EVP_cleanup();
  9978. CRYPTO_cleanup_all_ex_data();
  9979. ERR_remove_state(0);
  9980. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9981. pthread_mutex_destroy(&ssl_mutexes[i]);
  9982. }
  9983. mg_free(ssl_mutexes);
  9984. ssl_mutexes = NULL;
  9985. }
  9986. }
  9987. #endif /* !NO_SSL */
  9988. static int
  9989. set_gpass_option(struct mg_context *ctx)
  9990. {
  9991. if (ctx) {
  9992. struct file file = STRUCT_FILE_INITIALIZER;
  9993. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9994. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9995. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9996. return 0;
  9997. }
  9998. return 1;
  9999. }
  10000. return 0;
  10001. }
  10002. static int
  10003. set_acl_option(struct mg_context *ctx)
  10004. {
  10005. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10006. }
  10007. static void
  10008. reset_per_request_attributes(struct mg_connection *conn)
  10009. {
  10010. if (!conn) {
  10011. return;
  10012. }
  10013. conn->path_info = NULL;
  10014. conn->num_bytes_sent = conn->consumed_content = 0;
  10015. conn->status_code = -1;
  10016. conn->is_chunked = 0;
  10017. conn->must_close = conn->request_len = conn->throttle = 0;
  10018. conn->request_info.content_length = -1;
  10019. conn->request_info.remote_user = NULL;
  10020. conn->request_info.request_method = NULL;
  10021. conn->request_info.request_uri = NULL;
  10022. conn->request_info.local_uri = NULL;
  10023. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10024. * local_uri and request_uri */
  10025. conn->request_info.http_version = NULL;
  10026. conn->request_info.num_headers = 0;
  10027. conn->data_len = 0;
  10028. conn->chunk_remainder = 0;
  10029. conn->internal_error = 0;
  10030. }
  10031. static int
  10032. set_sock_timeout(SOCKET sock, int milliseconds)
  10033. {
  10034. int r0 = 0, r1, r2;
  10035. #ifdef _WIN32
  10036. /* Windows specific */
  10037. DWORD tv = (DWORD)milliseconds;
  10038. #else
  10039. /* Linux, ... (not Windows) */
  10040. struct timeval tv;
  10041. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10042. * max. time waiting for the acknowledged of TCP data before the connection
  10043. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10044. * If this option is not set, the default timeout of 20-30 minutes is used.
  10045. */
  10046. /* #define TCP_USER_TIMEOUT (18) */
  10047. #if defined(TCP_USER_TIMEOUT)
  10048. unsigned int uto = (unsigned int)milliseconds;
  10049. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10050. #endif
  10051. memset(&tv, 0, sizeof(tv));
  10052. tv.tv_sec = milliseconds / 1000;
  10053. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10054. #endif /* _WIN32 */
  10055. r1 = setsockopt(
  10056. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10057. r2 = setsockopt(
  10058. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10059. return r0 || r1 || r2;
  10060. }
  10061. static int
  10062. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10063. {
  10064. if (setsockopt(sock,
  10065. IPPROTO_TCP,
  10066. TCP_NODELAY,
  10067. (SOCK_OPT_TYPE)&nodelay_on,
  10068. sizeof(nodelay_on)) != 0) {
  10069. /* Error */
  10070. return 1;
  10071. }
  10072. /* OK */
  10073. return 0;
  10074. }
  10075. static void
  10076. close_socket_gracefully(struct mg_connection *conn)
  10077. {
  10078. #if defined(_WIN32)
  10079. char buf[MG_BUF_LEN];
  10080. int n;
  10081. #endif
  10082. struct linger linger;
  10083. if (!conn) {
  10084. return;
  10085. }
  10086. /* Set linger option to avoid socket hanging out after close. This
  10087. * prevent
  10088. * ephemeral port exhaust problem under high QPS. */
  10089. linger.l_onoff = 1;
  10090. linger.l_linger = 1;
  10091. if (setsockopt(conn->client.sock,
  10092. SOL_SOCKET,
  10093. SO_LINGER,
  10094. (char *)&linger,
  10095. sizeof(linger)) != 0) {
  10096. mg_cry(conn,
  10097. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10098. __func__,
  10099. strerror(ERRNO));
  10100. }
  10101. /* Send FIN to the client */
  10102. shutdown(conn->client.sock, SHUT_WR);
  10103. set_non_blocking_mode(conn->client.sock);
  10104. #if defined(_WIN32)
  10105. /* Read and discard pending incoming data. If we do not do that and
  10106. * close
  10107. * the socket, the data in the send buffer may be discarded. This
  10108. * behaviour is seen on Windows, when client keeps sending data
  10109. * when server decides to close the connection; then when client
  10110. * does recv() it gets no data back. */
  10111. do {
  10112. n = pull(
  10113. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10114. } while (n > 0);
  10115. #endif
  10116. /* Now we know that our FIN is ACK-ed, safe to close */
  10117. closesocket(conn->client.sock);
  10118. conn->client.sock = INVALID_SOCKET;
  10119. }
  10120. static void
  10121. close_connection(struct mg_connection *conn)
  10122. {
  10123. if (!conn || !conn->ctx) {
  10124. return;
  10125. }
  10126. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10127. if (conn->lua_websocket_state) {
  10128. lua_websocket_close(conn, conn->lua_websocket_state);
  10129. conn->lua_websocket_state = NULL;
  10130. }
  10131. #endif
  10132. /* call the connection_close callback if assigned */
  10133. if ((conn->ctx->callbacks.connection_close != NULL)
  10134. && (conn->ctx->context_type == 1)) {
  10135. conn->ctx->callbacks.connection_close(conn);
  10136. }
  10137. mg_lock_connection(conn);
  10138. conn->must_close = 1;
  10139. #ifndef NO_SSL
  10140. if (conn->ssl != NULL) {
  10141. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10142. */
  10143. SSL_shutdown(conn->ssl);
  10144. SSL_free(conn->ssl);
  10145. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10146. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10147. ERR_remove_state(0);
  10148. conn->ssl = NULL;
  10149. }
  10150. #endif
  10151. if (conn->client.sock != INVALID_SOCKET) {
  10152. close_socket_gracefully(conn);
  10153. conn->client.sock = INVALID_SOCKET;
  10154. }
  10155. mg_unlock_connection(conn);
  10156. }
  10157. void
  10158. mg_close_connection(struct mg_connection *conn)
  10159. {
  10160. struct mg_context *client_ctx = NULL;
  10161. unsigned int i;
  10162. if (conn == NULL) {
  10163. return;
  10164. }
  10165. if (conn->ctx->context_type == 2) {
  10166. client_ctx = conn->ctx;
  10167. /* client context: loops must end */
  10168. conn->ctx->stop_flag = 1;
  10169. }
  10170. #ifndef NO_SSL
  10171. if (conn->client_ssl_ctx != NULL) {
  10172. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10173. }
  10174. #endif
  10175. close_connection(conn);
  10176. if (client_ctx != NULL) {
  10177. /* join worker thread and free context */
  10178. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10179. if (client_ctx->workerthreadids[i] != 0) {
  10180. mg_join_thread(client_ctx->workerthreadids[i]);
  10181. }
  10182. }
  10183. mg_free(client_ctx->workerthreadids);
  10184. mg_free(client_ctx);
  10185. (void)pthread_mutex_destroy(&conn->mutex);
  10186. mg_free(conn);
  10187. }
  10188. }
  10189. static struct mg_connection *
  10190. mg_connect_client_impl(const struct mg_client_options *client_options,
  10191. int use_ssl,
  10192. char *ebuf,
  10193. size_t ebuf_len)
  10194. {
  10195. static struct mg_context fake_ctx;
  10196. struct mg_connection *conn = NULL;
  10197. SOCKET sock;
  10198. union usa sa;
  10199. if (!connect_socket(&fake_ctx,
  10200. client_options->host,
  10201. client_options->port,
  10202. use_ssl,
  10203. ebuf,
  10204. ebuf_len,
  10205. &sock,
  10206. &sa)) {
  10207. ;
  10208. } else if ((conn = (struct mg_connection *)
  10209. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10210. mg_snprintf(NULL,
  10211. NULL, /* No truncation check for ebuf */
  10212. ebuf,
  10213. ebuf_len,
  10214. "calloc(): %s",
  10215. strerror(ERRNO));
  10216. closesocket(sock);
  10217. #ifndef NO_SSL
  10218. } else if (use_ssl
  10219. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10220. == NULL) {
  10221. mg_snprintf(NULL,
  10222. NULL, /* No truncation check for ebuf */
  10223. ebuf,
  10224. ebuf_len,
  10225. "SSL_CTX_new error");
  10226. closesocket(sock);
  10227. mg_free(conn);
  10228. conn = NULL;
  10229. #endif /* NO_SSL */
  10230. } else {
  10231. #ifdef USE_IPV6
  10232. socklen_t len = (sa.sa.sa_family == AF_INET)
  10233. ? sizeof(conn->client.rsa.sin)
  10234. : sizeof(conn->client.rsa.sin6);
  10235. struct sockaddr *psa =
  10236. (sa.sa.sa_family == AF_INET)
  10237. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10238. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10239. #else
  10240. socklen_t len = sizeof(conn->client.rsa.sin);
  10241. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10242. #endif
  10243. conn->buf_size = MAX_REQUEST_SIZE;
  10244. conn->buf = (char *)(conn + 1);
  10245. conn->ctx = &fake_ctx;
  10246. conn->client.sock = sock;
  10247. conn->client.lsa = sa;
  10248. if (getsockname(sock, psa, &len) != 0) {
  10249. mg_cry(conn,
  10250. "%s: getsockname() failed: %s",
  10251. __func__,
  10252. strerror(ERRNO));
  10253. }
  10254. conn->client.is_ssl = use_ssl ? 1 : 0;
  10255. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10256. #ifndef NO_SSL
  10257. if (use_ssl) {
  10258. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10259. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10260. * SSL_CTX_set_verify call is needed to switch off server
  10261. * certificate checking, which is off by default in OpenSSL and
  10262. * on in yaSSL. */
  10263. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10264. * SSL_VERIFY_PEER, verify_ssl_server); */
  10265. if (client_options->client_cert) {
  10266. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10267. mg_snprintf(NULL,
  10268. NULL, /* No truncation check for ebuf */
  10269. ebuf,
  10270. ebuf_len,
  10271. "Can not use SSL client certificate");
  10272. SSL_CTX_free(conn->client_ssl_ctx);
  10273. closesocket(sock);
  10274. mg_free(conn);
  10275. conn = NULL;
  10276. }
  10277. }
  10278. if (client_options->server_cert) {
  10279. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10280. client_options->server_cert,
  10281. NULL);
  10282. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10283. } else {
  10284. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10285. }
  10286. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10287. mg_snprintf(NULL,
  10288. NULL, /* No truncation check for ebuf */
  10289. ebuf,
  10290. ebuf_len,
  10291. "SSL connection error");
  10292. SSL_CTX_free(conn->client_ssl_ctx);
  10293. closesocket(sock);
  10294. mg_free(conn);
  10295. conn = NULL;
  10296. }
  10297. }
  10298. #endif
  10299. }
  10300. return conn;
  10301. }
  10302. CIVETWEB_API struct mg_connection *
  10303. mg_connect_client_secure(const struct mg_client_options *client_options,
  10304. char *error_buffer,
  10305. size_t error_buffer_size)
  10306. {
  10307. return mg_connect_client_impl(client_options,
  10308. 1,
  10309. error_buffer,
  10310. error_buffer_size);
  10311. }
  10312. struct mg_connection *
  10313. mg_connect_client(const char *host,
  10314. int port,
  10315. int use_ssl,
  10316. char *error_buffer,
  10317. size_t error_buffer_size)
  10318. {
  10319. struct mg_client_options opts;
  10320. memset(&opts, 0, sizeof(opts));
  10321. opts.host = host;
  10322. opts.port = port;
  10323. return mg_connect_client_impl(&opts,
  10324. use_ssl,
  10325. error_buffer,
  10326. error_buffer_size);
  10327. }
  10328. static const struct {
  10329. const char *proto;
  10330. size_t proto_len;
  10331. unsigned default_port;
  10332. } abs_uri_protocols[] = {{"http://", 7, 80},
  10333. {"https://", 8, 443},
  10334. {"ws://", 5, 80},
  10335. {"wss://", 6, 443},
  10336. {NULL, 0, 0}};
  10337. /* Check if the uri is valid.
  10338. * return 0 for invalid uri,
  10339. * return 1 for *,
  10340. * return 2 for relative uri,
  10341. * return 3 for absolute uri without port,
  10342. * return 4 for absolute uri with port */
  10343. static int
  10344. get_uri_type(const char *uri)
  10345. {
  10346. int i;
  10347. char *hostend, *portbegin, *portend;
  10348. unsigned long port;
  10349. /* According to the HTTP standard
  10350. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10351. * URI can be an asterisk (*) or should start with slash (relative uri),
  10352. * or it should start with the protocol (absolute uri). */
  10353. if (uri[0] == '*' && uri[1] == '\0') {
  10354. /* asterisk */
  10355. return 1;
  10356. }
  10357. if (uri[0] == '/') {
  10358. /* relative uri */
  10359. return 2;
  10360. }
  10361. /* It could be an absolute uri: */
  10362. /* This function only checks if the uri is valid, not if it is
  10363. * addressing the current server. So civetweb can also be used
  10364. * as a proxy server. */
  10365. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10366. if (mg_strncasecmp(uri,
  10367. abs_uri_protocols[i].proto,
  10368. abs_uri_protocols[i].proto_len) == 0) {
  10369. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10370. if (!hostend) {
  10371. return 0;
  10372. }
  10373. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10374. if (!portbegin) {
  10375. return 3;
  10376. }
  10377. port = strtoul(portbegin + 1, &portend, 10);
  10378. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10379. return 0;
  10380. }
  10381. return 4;
  10382. }
  10383. }
  10384. return 0;
  10385. }
  10386. /* Return NULL or the relative uri at the current server */
  10387. static const char *
  10388. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10389. {
  10390. const char *server_domain;
  10391. size_t server_domain_len;
  10392. size_t request_domain_len = 0;
  10393. unsigned long port = 0;
  10394. int i;
  10395. const char *hostbegin = NULL;
  10396. const char *hostend = NULL;
  10397. const char *portbegin;
  10398. char *portend;
  10399. /* DNS is case insensitive, so use case insensitive string compare here
  10400. */
  10401. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10402. if (!server_domain) {
  10403. return 0;
  10404. }
  10405. server_domain_len = strlen(server_domain);
  10406. if (!server_domain_len) {
  10407. return 0;
  10408. }
  10409. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10410. if (mg_strncasecmp(uri,
  10411. abs_uri_protocols[i].proto,
  10412. abs_uri_protocols[i].proto_len) == 0) {
  10413. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10414. hostend = strchr(hostbegin, '/');
  10415. if (!hostend) {
  10416. return 0;
  10417. }
  10418. portbegin = strchr(hostbegin, ':');
  10419. if ((!portbegin) || (portbegin > hostend)) {
  10420. port = abs_uri_protocols[i].default_port;
  10421. request_domain_len = (size_t)(hostend - hostbegin);
  10422. } else {
  10423. port = strtoul(portbegin + 1, &portend, 10);
  10424. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10425. return 0;
  10426. }
  10427. request_domain_len = (size_t)(portbegin - hostbegin);
  10428. }
  10429. /* protocol found, port set */
  10430. break;
  10431. }
  10432. }
  10433. if (!port) {
  10434. /* port remains 0 if the protocol is not found */
  10435. return 0;
  10436. }
  10437. #if defined(USE_IPV6)
  10438. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10439. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10440. /* Request is directed to a different port */
  10441. return 0;
  10442. }
  10443. } else
  10444. #endif
  10445. {
  10446. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10447. /* Request is directed to a different port */
  10448. return 0;
  10449. }
  10450. }
  10451. if ((request_domain_len != server_domain_len)
  10452. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10453. /* Request is directed to another server */
  10454. return 0;
  10455. }
  10456. return hostend;
  10457. }
  10458. static int
  10459. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10460. {
  10461. const char *cl;
  10462. if (ebuf_len > 0) {
  10463. ebuf[0] = '\0';
  10464. }
  10465. *err = 0;
  10466. reset_per_request_attributes(conn);
  10467. if (!conn) {
  10468. mg_snprintf(conn,
  10469. NULL, /* No truncation check for ebuf */
  10470. ebuf,
  10471. ebuf_len,
  10472. "%s",
  10473. "Internal error");
  10474. *err = 500;
  10475. return 0;
  10476. }
  10477. /* Set the time the request was received. This value should be used for
  10478. * timeouts. */
  10479. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10480. conn->request_len =
  10481. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10482. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10483. */
  10484. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10485. mg_snprintf(conn,
  10486. NULL, /* No truncation check for ebuf */
  10487. ebuf,
  10488. ebuf_len,
  10489. "%s",
  10490. "Invalid request size");
  10491. *err = 500;
  10492. return 0;
  10493. }
  10494. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10495. mg_snprintf(conn,
  10496. NULL, /* No truncation check for ebuf */
  10497. ebuf,
  10498. ebuf_len,
  10499. "%s",
  10500. "Request Too Large");
  10501. *err = 413;
  10502. return 0;
  10503. } else if (conn->request_len <= 0) {
  10504. if (conn->data_len > 0) {
  10505. mg_snprintf(conn,
  10506. NULL, /* No truncation check for ebuf */
  10507. ebuf,
  10508. ebuf_len,
  10509. "%s",
  10510. "Client sent malformed request");
  10511. *err = 400;
  10512. } else {
  10513. /* Server did not send anything -> just close the connection */
  10514. conn->must_close = 1;
  10515. mg_snprintf(conn,
  10516. NULL, /* No truncation check for ebuf */
  10517. ebuf,
  10518. ebuf_len,
  10519. "%s",
  10520. "Client did not send a request");
  10521. *err = 0;
  10522. }
  10523. return 0;
  10524. } else if (parse_http_message(conn->buf,
  10525. conn->buf_size,
  10526. &conn->request_info) <= 0) {
  10527. mg_snprintf(conn,
  10528. NULL, /* No truncation check for ebuf */
  10529. ebuf,
  10530. ebuf_len,
  10531. "%s",
  10532. "Bad Request");
  10533. *err = 400;
  10534. return 0;
  10535. } else {
  10536. /* Message is a valid request or response */
  10537. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10538. /* Request/response has content length set */
  10539. char *endptr = NULL;
  10540. conn->content_len = strtoll(cl, &endptr, 10);
  10541. if (endptr == cl) {
  10542. mg_snprintf(conn,
  10543. NULL, /* No truncation check for ebuf */
  10544. ebuf,
  10545. ebuf_len,
  10546. "%s",
  10547. "Bad Request");
  10548. *err = 411;
  10549. return 0;
  10550. }
  10551. /* Publish the content length back to the request info. */
  10552. conn->request_info.content_length = conn->content_len;
  10553. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10554. != NULL
  10555. && !mg_strcasecmp(cl, "chunked")) {
  10556. conn->is_chunked = 1;
  10557. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10558. || !mg_strcasecmp(conn->request_info.request_method,
  10559. "PUT")) {
  10560. /* POST or PUT request without content length set */
  10561. conn->content_len = -1;
  10562. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10563. "HTTP/",
  10564. 5)) {
  10565. /* Response without content length set */
  10566. conn->content_len = -1;
  10567. } else {
  10568. /* Other request */
  10569. conn->content_len = 0;
  10570. }
  10571. }
  10572. return 1;
  10573. }
  10574. int
  10575. mg_get_response(struct mg_connection *conn,
  10576. char *ebuf,
  10577. size_t ebuf_len,
  10578. int timeout)
  10579. {
  10580. if (conn) {
  10581. /* Implementation of API function for HTTP clients */
  10582. int err, ret;
  10583. struct mg_context *octx = conn->ctx;
  10584. struct mg_context rctx = *(conn->ctx);
  10585. char txt[32]; /* will not overflow */
  10586. if (timeout >= 0) {
  10587. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10588. rctx.config[REQUEST_TIMEOUT] = txt;
  10589. set_sock_timeout(conn->client.sock, timeout);
  10590. } else {
  10591. rctx.config[REQUEST_TIMEOUT] = NULL;
  10592. }
  10593. conn->ctx = &rctx;
  10594. ret = getreq(conn, ebuf, ebuf_len, &err);
  10595. conn->ctx = octx;
  10596. /* TODO: 1) uri is deprecated;
  10597. * 2) here, ri.uri is the http response code */
  10598. conn->request_info.uri = conn->request_info.request_uri;
  10599. /* TODO (mid): Define proper return values - maybe return length?
  10600. * For the first test use <0 for error and >0 for OK */
  10601. return (ret == 0) ? -1 : +1;
  10602. }
  10603. return -1;
  10604. }
  10605. struct mg_connection *
  10606. mg_download(const char *host,
  10607. int port,
  10608. int use_ssl,
  10609. char *ebuf,
  10610. size_t ebuf_len,
  10611. const char *fmt,
  10612. ...)
  10613. {
  10614. struct mg_connection *conn;
  10615. va_list ap;
  10616. int i;
  10617. int reqerr;
  10618. va_start(ap, fmt);
  10619. ebuf[0] = '\0';
  10620. /* open a connection */
  10621. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10622. if (conn != NULL) {
  10623. i = mg_vprintf(conn, fmt, ap);
  10624. if (i <= 0) {
  10625. mg_snprintf(conn,
  10626. NULL, /* No truncation check for ebuf */
  10627. ebuf,
  10628. ebuf_len,
  10629. "%s",
  10630. "Error sending request");
  10631. } else {
  10632. getreq(conn, ebuf, ebuf_len, &reqerr);
  10633. /* TODO: 1) uri is deprecated;
  10634. * 2) here, ri.uri is the http response code */
  10635. conn->request_info.uri = conn->request_info.request_uri;
  10636. }
  10637. }
  10638. /* if an error occured, close the connection */
  10639. if (ebuf[0] != '\0' && conn != NULL) {
  10640. mg_close_connection(conn);
  10641. conn = NULL;
  10642. }
  10643. va_end(ap);
  10644. return conn;
  10645. }
  10646. struct websocket_client_thread_data {
  10647. struct mg_connection *conn;
  10648. mg_websocket_data_handler data_handler;
  10649. mg_websocket_close_handler close_handler;
  10650. void *callback_data;
  10651. };
  10652. #if defined(USE_WEBSOCKET)
  10653. #ifdef _WIN32
  10654. static unsigned __stdcall websocket_client_thread(void *data)
  10655. #else
  10656. static void *
  10657. websocket_client_thread(void *data)
  10658. #endif
  10659. {
  10660. struct websocket_client_thread_data *cdata =
  10661. (struct websocket_client_thread_data *)data;
  10662. mg_set_thread_name("ws-client");
  10663. if (cdata->conn->ctx) {
  10664. if (cdata->conn->ctx->callbacks.init_thread) {
  10665. /* 3 indicates a websocket client thread */
  10666. /* TODO: check if conn->ctx can be set */
  10667. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10668. }
  10669. }
  10670. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10671. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10672. if (cdata->close_handler != NULL) {
  10673. cdata->close_handler(cdata->conn, cdata->callback_data);
  10674. }
  10675. mg_free((void *)cdata);
  10676. #ifdef _WIN32
  10677. return 0;
  10678. #else
  10679. return NULL;
  10680. #endif
  10681. }
  10682. #endif
  10683. struct mg_connection *
  10684. mg_connect_websocket_client(const char *host,
  10685. int port,
  10686. int use_ssl,
  10687. char *error_buffer,
  10688. size_t error_buffer_size,
  10689. const char *path,
  10690. const char *origin,
  10691. mg_websocket_data_handler data_func,
  10692. mg_websocket_close_handler close_func,
  10693. void *user_data)
  10694. {
  10695. struct mg_connection *conn = NULL;
  10696. #if defined(USE_WEBSOCKET)
  10697. struct mg_context *newctx = NULL;
  10698. struct websocket_client_thread_data *thread_data;
  10699. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10700. static const char *handshake_req;
  10701. if (origin != NULL) {
  10702. handshake_req = "GET %s HTTP/1.1\r\n"
  10703. "Host: %s\r\n"
  10704. "Upgrade: websocket\r\n"
  10705. "Connection: Upgrade\r\n"
  10706. "Sec-WebSocket-Key: %s\r\n"
  10707. "Sec-WebSocket-Version: 13\r\n"
  10708. "Origin: %s\r\n"
  10709. "\r\n";
  10710. } else {
  10711. handshake_req = "GET %s HTTP/1.1\r\n"
  10712. "Host: %s\r\n"
  10713. "Upgrade: websocket\r\n"
  10714. "Connection: Upgrade\r\n"
  10715. "Sec-WebSocket-Key: %s\r\n"
  10716. "Sec-WebSocket-Version: 13\r\n"
  10717. "\r\n";
  10718. }
  10719. /* Establish the client connection and request upgrade */
  10720. conn = mg_download(host,
  10721. port,
  10722. use_ssl,
  10723. error_buffer,
  10724. error_buffer_size,
  10725. handshake_req,
  10726. path,
  10727. host,
  10728. magic,
  10729. origin);
  10730. /* Connection object will be null if something goes wrong */
  10731. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10732. if (!*error_buffer) {
  10733. /* if there is a connection, but it did not return 101,
  10734. * error_buffer is not yet set */
  10735. mg_snprintf(conn,
  10736. NULL, /* No truncation check for ebuf */
  10737. error_buffer,
  10738. error_buffer_size,
  10739. "Unexpected server reply");
  10740. }
  10741. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10742. if (conn != NULL) {
  10743. mg_free(conn);
  10744. conn = NULL;
  10745. }
  10746. return conn;
  10747. }
  10748. /* For client connections, mg_context is fake. Since we need to set a
  10749. * callback function, we need to create a copy and modify it. */
  10750. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10751. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10752. newctx->user_data = user_data;
  10753. newctx->context_type = 2; /* client context type */
  10754. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10755. newctx->workerthreadids =
  10756. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10757. conn->ctx = newctx;
  10758. thread_data = (struct websocket_client_thread_data *)
  10759. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10760. thread_data->conn = conn;
  10761. thread_data->data_handler = data_func;
  10762. thread_data->close_handler = close_func;
  10763. thread_data->callback_data = NULL;
  10764. /* Start a thread to read the websocket client connection
  10765. * This thread will automatically stop when mg_disconnect is
  10766. * called on the client connection */
  10767. if (mg_start_thread_with_id(websocket_client_thread,
  10768. (void *)thread_data,
  10769. newctx->workerthreadids) != 0) {
  10770. mg_free((void *)thread_data);
  10771. mg_free((void *)newctx->workerthreadids);
  10772. mg_free((void *)newctx);
  10773. mg_free((void *)conn);
  10774. conn = NULL;
  10775. DEBUG_TRACE("%s",
  10776. "Websocket client connect thread could not be started\r\n");
  10777. }
  10778. #else
  10779. /* Appease "unused parameter" warnings */
  10780. (void)host;
  10781. (void)port;
  10782. (void)use_ssl;
  10783. (void)error_buffer;
  10784. (void)error_buffer_size;
  10785. (void)path;
  10786. (void)origin;
  10787. (void)user_data;
  10788. (void)data_func;
  10789. (void)close_func;
  10790. #endif
  10791. return conn;
  10792. }
  10793. static void
  10794. process_new_connection(struct mg_connection *conn)
  10795. {
  10796. if (conn && conn->ctx) {
  10797. struct mg_request_info *ri = &conn->request_info;
  10798. int keep_alive_enabled, keep_alive, discard_len;
  10799. char ebuf[100];
  10800. const char *hostend;
  10801. int reqerr, uri_type;
  10802. keep_alive_enabled =
  10803. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10804. /* Important: on new connection, reset the receiving buffer. Credit
  10805. * goes to crule42. */
  10806. conn->data_len = 0;
  10807. do {
  10808. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10809. /* The request sent by the client could not be understood by
  10810. * the server, or it was incomplete or a timeout. Send an
  10811. * error message and close the connection. */
  10812. if (reqerr > 0) {
  10813. /*assert(ebuf[0] != '\0');*/
  10814. send_http_error(conn, reqerr, "%s", ebuf);
  10815. }
  10816. } else if (strcmp(ri->http_version, "1.0")
  10817. && strcmp(ri->http_version, "1.1")) {
  10818. mg_snprintf(conn,
  10819. NULL, /* No truncation check for ebuf */
  10820. ebuf,
  10821. sizeof(ebuf),
  10822. "Bad HTTP version: [%s]",
  10823. ri->http_version);
  10824. send_http_error(conn, 505, "%s", ebuf);
  10825. }
  10826. if (ebuf[0] == '\0') {
  10827. uri_type = get_uri_type(conn->request_info.request_uri);
  10828. switch (uri_type) {
  10829. case 1:
  10830. /* Asterisk */
  10831. conn->request_info.local_uri = NULL;
  10832. break;
  10833. case 2:
  10834. /* relative uri */
  10835. conn->request_info.local_uri =
  10836. conn->request_info.request_uri;
  10837. break;
  10838. case 3:
  10839. case 4:
  10840. /* absolute uri (with/without port) */
  10841. hostend = get_rel_url_at_current_server(
  10842. conn->request_info.request_uri, conn);
  10843. if (hostend) {
  10844. conn->request_info.local_uri = hostend;
  10845. } else {
  10846. conn->request_info.local_uri = NULL;
  10847. }
  10848. break;
  10849. default:
  10850. mg_snprintf(conn,
  10851. NULL, /* No truncation check for ebuf */
  10852. ebuf,
  10853. sizeof(ebuf),
  10854. "Invalid URI: [%s]",
  10855. ri->request_uri);
  10856. send_http_error(conn, 400, "%s", ebuf);
  10857. break;
  10858. }
  10859. /* TODO: cleanup uri, local_uri and request_uri */
  10860. conn->request_info.uri = conn->request_info.local_uri;
  10861. }
  10862. if (ebuf[0] == '\0') {
  10863. if (conn->request_info.local_uri) {
  10864. /* handle request to local server */
  10865. handle_request(conn);
  10866. if (conn->ctx->callbacks.end_request != NULL) {
  10867. conn->ctx->callbacks.end_request(conn,
  10868. conn->status_code);
  10869. }
  10870. log_access(conn);
  10871. } else {
  10872. /* TODO: handle non-local request (PROXY) */
  10873. conn->must_close = 1;
  10874. }
  10875. } else {
  10876. conn->must_close = 1;
  10877. }
  10878. if (ri->remote_user != NULL) {
  10879. mg_free((void *)ri->remote_user);
  10880. /* Important! When having connections with and without auth
  10881. * would cause double free and then crash */
  10882. ri->remote_user = NULL;
  10883. }
  10884. /* NOTE(lsm): order is important here. should_keep_alive() call
  10885. * is
  10886. * using parsed request, which will be invalid after memmove's
  10887. * below.
  10888. * Therefore, memorize should_keep_alive() result now for later
  10889. * use
  10890. * in loop exit condition. */
  10891. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10892. && conn->content_len >= 0 && should_keep_alive(conn);
  10893. /* Discard all buffered data for this request */
  10894. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  10895. && ((conn->request_len + conn->content_len)
  10896. < (int64_t)conn->data_len))
  10897. ? (int)(conn->request_len + conn->content_len)
  10898. : conn->data_len;
  10899. /*assert(discard_len >= 0);*/
  10900. if (discard_len < 0)
  10901. break;
  10902. conn->data_len -= discard_len;
  10903. if (conn->data_len > 0) {
  10904. memmove(conn->buf,
  10905. conn->buf + discard_len,
  10906. (size_t)conn->data_len);
  10907. }
  10908. /* assert(conn->data_len >= 0); */
  10909. /* assert(conn->data_len <= conn->buf_size); */
  10910. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10911. break;
  10912. }
  10913. } while (keep_alive);
  10914. }
  10915. }
  10916. #if defined(ALTERNATIVE_QUEUE)
  10917. static void
  10918. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10919. {
  10920. unsigned int i;
  10921. for (;;) {
  10922. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10923. /* find a free worker slot and signal it */
  10924. if (ctx->client_socks[i].in_use == 0) {
  10925. ctx->client_socks[i] = *sp;
  10926. ctx->client_socks[i].in_use = 1;
  10927. event_signal(ctx->client_wait_events[i]);
  10928. return;
  10929. }
  10930. }
  10931. /* queue is full */
  10932. mg_sleep(1);
  10933. }
  10934. }
  10935. static int
  10936. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  10937. {
  10938. ctx->client_socks[thread_index].in_use = 0;
  10939. event_wait(ctx->client_wait_events[thread_index]);
  10940. *sp = ctx->client_socks[thread_index];
  10941. return !ctx->stop_flag;
  10942. }
  10943. #else /* ALTERNATIVE_QUEUE */
  10944. /* Worker threads take accepted socket from the queue */
  10945. static int
  10946. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  10947. {
  10948. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10949. (void)thread_index;
  10950. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10951. DEBUG_TRACE("%s", "going idle");
  10952. /* If the queue is empty, wait. We're idle at this point. */
  10953. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10954. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10955. }
  10956. /* If we're stopping, sq_head may be equal to sq_tail. */
  10957. if (ctx->sq_head > ctx->sq_tail) {
  10958. /* Copy socket from the queue and increment tail */
  10959. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10960. ctx->sq_tail++;
  10961. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10962. /* Wrap pointers if needed */
  10963. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10964. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10965. ctx->sq_head -= QUEUE_SIZE(ctx);
  10966. }
  10967. }
  10968. (void)pthread_cond_signal(&ctx->sq_empty);
  10969. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10970. return !ctx->stop_flag;
  10971. #undef QUEUE_SIZE
  10972. }
  10973. /* Master thread adds accepted socket to a queue */
  10974. static void
  10975. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10976. {
  10977. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10978. if (!ctx) {
  10979. return;
  10980. }
  10981. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10982. /* If the queue is full, wait */
  10983. while (ctx->stop_flag == 0
  10984. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10985. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10986. }
  10987. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10988. /* Copy socket to the queue and increment head */
  10989. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10990. ctx->sq_head++;
  10991. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10992. }
  10993. (void)pthread_cond_signal(&ctx->sq_full);
  10994. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10995. #undef QUEUE_SIZE
  10996. }
  10997. #endif /* ALTERNATIVE_QUEUE */
  10998. struct worker_thread_args {
  10999. struct mg_context *ctx;
  11000. int index;
  11001. };
  11002. static void *
  11003. worker_thread_run(struct worker_thread_args *thread_args)
  11004. {
  11005. struct mg_context *ctx = thread_args->ctx;
  11006. struct mg_connection *conn;
  11007. struct mg_workerTLS tls;
  11008. #if defined(MG_LEGACY_INTERFACE)
  11009. uint32_t addr;
  11010. #endif
  11011. mg_set_thread_name("worker");
  11012. tls.is_master = 0;
  11013. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11014. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11015. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11016. #endif
  11017. if (ctx->callbacks.init_thread) {
  11018. /* call init_thread for a worker thread (type 1) */
  11019. ctx->callbacks.init_thread(ctx, 1);
  11020. }
  11021. conn =
  11022. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11023. if (conn == NULL) {
  11024. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11025. } else {
  11026. pthread_setspecific(sTlsKey, &tls);
  11027. conn->buf_size = MAX_REQUEST_SIZE;
  11028. conn->buf = (char *)(conn + 1);
  11029. conn->ctx = ctx;
  11030. conn->thread_index = thread_args->index;
  11031. conn->request_info.user_data = ctx->user_data;
  11032. /* Allocate a mutex for this connection to allow communication both
  11033. * within the request handler and from elsewhere in the application
  11034. */
  11035. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11036. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11037. * signal sq_empty condvar to wake up the master waiting in
  11038. * produce_socket() */
  11039. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11040. conn->conn_birth_time = time(NULL);
  11041. /* Fill in IP, port info early so even if SSL setup below fails,
  11042. * error handler would have the corresponding info.
  11043. * Thanks to Johannes Winkelmann for the patch.
  11044. */
  11045. #if defined(USE_IPV6)
  11046. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11047. conn->request_info.remote_port =
  11048. ntohs(conn->client.rsa.sin6.sin6_port);
  11049. } else
  11050. #endif
  11051. {
  11052. conn->request_info.remote_port =
  11053. ntohs(conn->client.rsa.sin.sin_port);
  11054. }
  11055. sockaddr_to_string(conn->request_info.remote_addr,
  11056. sizeof(conn->request_info.remote_addr),
  11057. &conn->client.rsa);
  11058. #if defined(MG_LEGACY_INTERFACE)
  11059. /* This legacy interface only works for the IPv4 case */
  11060. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11061. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11062. #endif
  11063. conn->request_info.is_ssl = conn->client.is_ssl;
  11064. if (!conn->client.is_ssl
  11065. #ifndef NO_SSL
  11066. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  11067. #endif
  11068. ) {
  11069. process_new_connection(conn);
  11070. }
  11071. close_connection(conn);
  11072. }
  11073. }
  11074. pthread_setspecific(sTlsKey, NULL);
  11075. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11076. CloseHandle(tls.pthread_cond_helper_mutex);
  11077. #endif
  11078. pthread_mutex_destroy(&conn->mutex);
  11079. mg_free(conn);
  11080. DEBUG_TRACE("%s", "exiting");
  11081. return NULL;
  11082. }
  11083. /* Threads have different return types on Windows and Unix. */
  11084. #ifdef _WIN32
  11085. static unsigned __stdcall worker_thread(void *thread_func_param)
  11086. {
  11087. struct worker_thread_args *pwta =
  11088. (struct worker_thread_args *)thread_func_param;
  11089. worker_thread_run(pwta);
  11090. mg_free(thread_func_param);
  11091. return 0;
  11092. }
  11093. #else
  11094. static void *
  11095. worker_thread(void *thread_func_param)
  11096. {
  11097. struct worker_thread_args *pwta =
  11098. (struct worker_thread_args *)thread_func_param;
  11099. worker_thread_run(pwta);
  11100. mg_free(thread_func_param);
  11101. return NULL;
  11102. }
  11103. #endif /* _WIN32 */
  11104. static void
  11105. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11106. {
  11107. struct socket so;
  11108. char src_addr[IP_ADDR_STR_LEN];
  11109. socklen_t len = sizeof(so.rsa);
  11110. int on = 1;
  11111. int timeout;
  11112. if (!listener) {
  11113. return;
  11114. }
  11115. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11116. == INVALID_SOCKET) {
  11117. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11118. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11119. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11120. closesocket(so.sock);
  11121. so.sock = INVALID_SOCKET;
  11122. } else {
  11123. /* Put so socket structure into the queue */
  11124. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11125. set_close_on_exec(so.sock, fc(ctx));
  11126. so.is_ssl = listener->is_ssl;
  11127. so.ssl_redir = listener->ssl_redir;
  11128. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11129. mg_cry(fc(ctx),
  11130. "%s: getsockname() failed: %s",
  11131. __func__,
  11132. strerror(ERRNO));
  11133. }
  11134. /* Set TCP keep-alive. This is needed because if HTTP-level
  11135. * keep-alive
  11136. * is enabled, and client resets the connection, server won't get
  11137. * TCP FIN or RST and will keep the connection open forever. With
  11138. * TCP keep-alive, next keep-alive handshake will figure out that
  11139. * the client is down and will close the server end.
  11140. * Thanks to Igor Klopov who suggested the patch. */
  11141. if (setsockopt(so.sock,
  11142. SOL_SOCKET,
  11143. SO_KEEPALIVE,
  11144. (SOCK_OPT_TYPE)&on,
  11145. sizeof(on)) != 0) {
  11146. mg_cry(fc(ctx),
  11147. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11148. __func__,
  11149. strerror(ERRNO));
  11150. }
  11151. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11152. * to effectively fill up the underlying IP packet payload and
  11153. * reduce the overhead of sending lots of small buffers. However
  11154. * this hurts the server's throughput (ie. operations per second)
  11155. * when HTTP 1.1 persistent connections are used and the responses
  11156. * are relatively small (eg. less than 1400 bytes).
  11157. */
  11158. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11159. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11160. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11161. mg_cry(fc(ctx),
  11162. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11163. __func__,
  11164. strerror(ERRNO));
  11165. }
  11166. }
  11167. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11168. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11169. } else {
  11170. timeout = -1;
  11171. }
  11172. if (timeout > 0) {
  11173. set_sock_timeout(so.sock, timeout);
  11174. }
  11175. produce_socket(ctx, &so);
  11176. }
  11177. }
  11178. static void
  11179. master_thread_run(void *thread_func_param)
  11180. {
  11181. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11182. struct mg_workerTLS tls;
  11183. struct pollfd *pfd;
  11184. unsigned int i;
  11185. unsigned int workerthreadcount;
  11186. if (!ctx) {
  11187. return;
  11188. }
  11189. mg_set_thread_name("master");
  11190. /* Increase priority of the master thread */
  11191. #if defined(_WIN32)
  11192. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11193. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11194. int min_prio = sched_get_priority_min(SCHED_RR);
  11195. int max_prio = sched_get_priority_max(SCHED_RR);
  11196. if ((min_prio >= 0) && (max_prio >= 0)
  11197. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11198. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11199. struct sched_param sched_param = {0};
  11200. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11201. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11202. }
  11203. #endif
  11204. /* Initialize thread local storage */
  11205. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11206. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11207. #endif
  11208. tls.is_master = 1;
  11209. pthread_setspecific(sTlsKey, &tls);
  11210. if (ctx->callbacks.init_thread) {
  11211. /* Callback for the master thread (type 0) */
  11212. ctx->callbacks.init_thread(ctx, 0);
  11213. }
  11214. /* Server starts *now* */
  11215. ctx->start_time = time(NULL);
  11216. /* Start the server */
  11217. pfd = ctx->listening_socket_fds;
  11218. while (ctx->stop_flag == 0) {
  11219. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11220. pfd[i].fd = ctx->listening_sockets[i].sock;
  11221. pfd[i].events = POLLIN;
  11222. }
  11223. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11224. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11225. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11226. * successful poll, and POLLIN is defined as
  11227. * (POLLRDNORM | POLLRDBAND)
  11228. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11229. * pfd[i].revents == POLLIN. */
  11230. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11231. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11232. }
  11233. }
  11234. }
  11235. }
  11236. /* Here stop_flag is 1 - Initiate shutdown. */
  11237. DEBUG_TRACE("%s", "stopping workers");
  11238. /* Stop signal received: somebody called mg_stop. Quit. */
  11239. close_all_listening_sockets(ctx);
  11240. /* Wakeup workers that are waiting for connections to handle. */
  11241. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11242. #if defined(ALTERNATIVE_QUEUE)
  11243. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11244. event_signal(ctx->client_wait_events[i]);
  11245. /* Since we know all sockets, we can shutdown the connections. */
  11246. if (ctx->client_socks[i].in_use) {
  11247. shutdown(ctx->client_socks[i].sock, SD_BOTH);
  11248. }
  11249. }
  11250. #else
  11251. pthread_cond_broadcast(&ctx->sq_full);
  11252. #endif
  11253. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11254. /* Join all worker threads to avoid leaking threads. */
  11255. workerthreadcount = ctx->cfg_worker_threads;
  11256. for (i = 0; i < workerthreadcount; i++) {
  11257. if (ctx->workerthreadids[i] != 0) {
  11258. mg_join_thread(ctx->workerthreadids[i]);
  11259. }
  11260. }
  11261. #if !defined(NO_SSL)
  11262. if (ctx->ssl_ctx != NULL) {
  11263. uninitialize_ssl(ctx);
  11264. }
  11265. #endif
  11266. DEBUG_TRACE("%s", "exiting");
  11267. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11268. CloseHandle(tls.pthread_cond_helper_mutex);
  11269. #endif
  11270. pthread_setspecific(sTlsKey, NULL);
  11271. /* Signal mg_stop() that we're done.
  11272. * WARNING: This must be the very last thing this
  11273. * thread does, as ctx becomes invalid after this line. */
  11274. ctx->stop_flag = 2;
  11275. }
  11276. /* Threads have different return types on Windows and Unix. */
  11277. #ifdef _WIN32
  11278. static unsigned __stdcall master_thread(void *thread_func_param)
  11279. {
  11280. master_thread_run(thread_func_param);
  11281. return 0;
  11282. }
  11283. #else
  11284. static void *
  11285. master_thread(void *thread_func_param)
  11286. {
  11287. master_thread_run(thread_func_param);
  11288. return NULL;
  11289. }
  11290. #endif /* _WIN32 */
  11291. static void
  11292. free_context(struct mg_context *ctx)
  11293. {
  11294. int i;
  11295. struct mg_handler_info *tmp_rh;
  11296. if (ctx == NULL) {
  11297. return;
  11298. }
  11299. if (ctx->callbacks.exit_context) {
  11300. ctx->callbacks.exit_context(ctx);
  11301. }
  11302. /* All threads exited, no sync is needed. Destroy thread mutex and
  11303. * condvars
  11304. */
  11305. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11306. #if defined(ALTERNATIVE_QUEUE)
  11307. mg_free(ctx->client_socks);
  11308. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11309. event_destroy(ctx->client_wait_events[i]);
  11310. }
  11311. mg_free(ctx->client_wait_events);
  11312. #else
  11313. (void)pthread_cond_destroy(&ctx->sq_empty);
  11314. (void)pthread_cond_destroy(&ctx->sq_full);
  11315. #endif
  11316. /* Destroy other context global data structures mutex */
  11317. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11318. #if defined(USE_TIMERS)
  11319. timers_exit(ctx);
  11320. #endif
  11321. /* Deallocate config parameters */
  11322. for (i = 0; i < NUM_OPTIONS; i++) {
  11323. if (ctx->config[i] != NULL) {
  11324. #if defined(_MSC_VER)
  11325. #pragma warning(suppress : 6001)
  11326. #endif
  11327. mg_free(ctx->config[i]);
  11328. }
  11329. }
  11330. /* Deallocate request handlers */
  11331. while (ctx->handlers) {
  11332. tmp_rh = ctx->handlers;
  11333. ctx->handlers = tmp_rh->next;
  11334. mg_free(tmp_rh->uri);
  11335. mg_free(tmp_rh);
  11336. }
  11337. #ifndef NO_SSL
  11338. /* Deallocate SSL context */
  11339. if (ctx->ssl_ctx != NULL) {
  11340. SSL_CTX_free(ctx->ssl_ctx);
  11341. }
  11342. #endif /* !NO_SSL */
  11343. /* Deallocate worker thread ID array */
  11344. if (ctx->workerthreadids != NULL) {
  11345. mg_free(ctx->workerthreadids);
  11346. }
  11347. /* Deallocate the tls variable */
  11348. if (mg_atomic_dec(&sTlsInit) == 0) {
  11349. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11350. DeleteCriticalSection(&global_log_file_lock);
  11351. #endif /* _WIN32 && !__SYMBIAN32__ */
  11352. #if !defined(_WIN32)
  11353. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11354. #endif
  11355. pthread_key_delete(sTlsKey);
  11356. }
  11357. /* deallocate system name string */
  11358. mg_free(ctx->systemName);
  11359. /* Deallocate context itself */
  11360. mg_free(ctx);
  11361. }
  11362. void
  11363. mg_stop(struct mg_context *ctx)
  11364. {
  11365. pthread_t mt;
  11366. if (!ctx) {
  11367. return;
  11368. }
  11369. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11370. * two threads is not allowed. */
  11371. mt = ctx->masterthreadid;
  11372. if (mt == 0) {
  11373. return;
  11374. }
  11375. ctx->masterthreadid = 0;
  11376. /* Set stop flag, so all threads know they have to exit. */
  11377. ctx->stop_flag = 1;
  11378. /* Wait until everything has stopped. */
  11379. while (ctx->stop_flag != 2) {
  11380. (void)mg_sleep(10);
  11381. }
  11382. mg_join_thread(mt);
  11383. free_context(ctx);
  11384. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11385. (void)WSACleanup();
  11386. #endif /* _WIN32 && !__SYMBIAN32__ */
  11387. }
  11388. static void
  11389. get_system_name(char **sysName)
  11390. {
  11391. #if defined(_WIN32)
  11392. #if !defined(__SYMBIAN32__)
  11393. #if defined(_WIN32_WCE)
  11394. *sysName = mg_strdup("WinCE");
  11395. #else
  11396. char name[128];
  11397. DWORD dwVersion = 0;
  11398. DWORD dwMajorVersion = 0;
  11399. DWORD dwMinorVersion = 0;
  11400. DWORD dwBuild = 0;
  11401. #ifdef _MSC_VER
  11402. #pragma warning(push)
  11403. // GetVersion was declared deprecated
  11404. #pragma warning(disable : 4996)
  11405. #endif
  11406. dwVersion = GetVersion();
  11407. #ifdef _MSC_VER
  11408. #pragma warning(pop)
  11409. #endif
  11410. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11411. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11412. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11413. (void)dwBuild;
  11414. sprintf(name,
  11415. "Windows %u.%u",
  11416. (unsigned)dwMajorVersion,
  11417. (unsigned)dwMinorVersion);
  11418. *sysName = mg_strdup(name);
  11419. #endif
  11420. #else
  11421. *sysName = mg_strdup("Symbian");
  11422. #endif
  11423. #else
  11424. struct utsname name;
  11425. memset(&name, 0, sizeof(name));
  11426. uname(&name);
  11427. *sysName = mg_strdup(name.sysname);
  11428. #endif
  11429. }
  11430. struct mg_context *
  11431. mg_start(const struct mg_callbacks *callbacks,
  11432. void *user_data,
  11433. const char **options)
  11434. {
  11435. struct mg_context *ctx;
  11436. const char *name, *value, *default_value;
  11437. int idx, ok, workerthreadcount;
  11438. unsigned int i;
  11439. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11440. struct mg_workerTLS tls;
  11441. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11442. WSADATA data;
  11443. WSAStartup(MAKEWORD(2, 2), &data);
  11444. #endif /* _WIN32 && !__SYMBIAN32__ */
  11445. /* Allocate context and initialize reasonable general case defaults. */
  11446. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11447. return NULL;
  11448. }
  11449. /* Random number generator will initialize at the first call */
  11450. ctx->auth_nonce_mask =
  11451. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11452. if (mg_atomic_inc(&sTlsInit) == 1) {
  11453. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11454. InitializeCriticalSection(&global_log_file_lock);
  11455. #endif /* _WIN32 && !__SYMBIAN32__ */
  11456. #if !defined(_WIN32)
  11457. pthread_mutexattr_init(&pthread_mutex_attr);
  11458. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11459. #endif
  11460. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11461. /* Fatal error - abort start. However, this situation should
  11462. * never
  11463. * occur in practice. */
  11464. mg_atomic_dec(&sTlsInit);
  11465. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11466. mg_free(ctx);
  11467. return NULL;
  11468. }
  11469. } else {
  11470. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11471. * initialized. */
  11472. mg_sleep(1);
  11473. }
  11474. tls.is_master = -1;
  11475. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11476. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11477. tls.pthread_cond_helper_mutex = NULL;
  11478. #endif
  11479. pthread_setspecific(sTlsKey, &tls);
  11480. #if defined(USE_LUA)
  11481. lua_init_optional_libraries();
  11482. #endif
  11483. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11484. #if !defined(ALTERNATIVE_QUEUE)
  11485. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11486. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11487. #endif
  11488. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11489. if (!ok) {
  11490. /* Fatal error - abort start. However, this situation should never
  11491. * occur in practice. */
  11492. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11493. mg_free(ctx);
  11494. pthread_setspecific(sTlsKey, NULL);
  11495. return NULL;
  11496. }
  11497. if (callbacks) {
  11498. ctx->callbacks = *callbacks;
  11499. exit_callback = callbacks->exit_context;
  11500. ctx->callbacks.exit_context = 0;
  11501. }
  11502. ctx->user_data = user_data;
  11503. ctx->handlers = NULL;
  11504. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11505. ctx->shared_lua_websockets = 0;
  11506. #endif
  11507. while (options && (name = *options++) != NULL) {
  11508. if ((idx = get_option_index(name)) == -1) {
  11509. mg_cry(fc(ctx), "Invalid option: %s", name);
  11510. free_context(ctx);
  11511. pthread_setspecific(sTlsKey, NULL);
  11512. return NULL;
  11513. } else if ((value = *options++) == NULL) {
  11514. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11515. free_context(ctx);
  11516. pthread_setspecific(sTlsKey, NULL);
  11517. return NULL;
  11518. }
  11519. if (ctx->config[idx] != NULL) {
  11520. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11521. mg_free(ctx->config[idx]);
  11522. }
  11523. ctx->config[idx] = mg_strdup(value);
  11524. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11525. }
  11526. /* Set default value if needed */
  11527. for (i = 0; config_options[i].name != NULL; i++) {
  11528. default_value = config_options[i].default_value;
  11529. if (ctx->config[i] == NULL && default_value != NULL) {
  11530. ctx->config[i] = mg_strdup(default_value);
  11531. }
  11532. }
  11533. #if defined(NO_FILES)
  11534. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11535. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11536. free_context(ctx);
  11537. pthread_setspecific(sTlsKey, NULL);
  11538. return NULL;
  11539. }
  11540. #endif
  11541. get_system_name(&ctx->systemName);
  11542. /* NOTE(lsm): order is important here. SSL certificates must
  11543. * be initialized before listening ports. UID must be set last. */
  11544. if (!set_gpass_option(ctx) ||
  11545. #if !defined(NO_SSL)
  11546. !set_ssl_option(ctx) ||
  11547. #endif
  11548. !set_ports_option(ctx) ||
  11549. #if !defined(_WIN32)
  11550. !set_uid_option(ctx) ||
  11551. #endif
  11552. !set_acl_option(ctx)) {
  11553. free_context(ctx);
  11554. pthread_setspecific(sTlsKey, NULL);
  11555. return NULL;
  11556. }
  11557. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11558. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11559. * won't kill the whole process. */
  11560. (void)signal(SIGPIPE, SIG_IGN);
  11561. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11562. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11563. if (workerthreadcount > MAX_WORKER_THREADS) {
  11564. mg_cry(fc(ctx), "Too many worker threads");
  11565. free_context(ctx);
  11566. pthread_setspecific(sTlsKey, NULL);
  11567. return NULL;
  11568. }
  11569. if (workerthreadcount > 0) {
  11570. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11571. ctx->workerthreadids =
  11572. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11573. if (ctx->workerthreadids == NULL) {
  11574. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11575. free_context(ctx);
  11576. pthread_setspecific(sTlsKey, NULL);
  11577. return NULL;
  11578. }
  11579. #if defined(ALTERNATIVE_QUEUE)
  11580. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11581. ctx->cfg_worker_threads);
  11582. if (ctx->client_wait_events == NULL) {
  11583. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11584. mg_free(ctx->workerthreadids);
  11585. free_context(ctx);
  11586. pthread_setspecific(sTlsKey, NULL);
  11587. return NULL;
  11588. }
  11589. ctx->client_socks =
  11590. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11591. if (ctx->client_wait_events == NULL) {
  11592. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11593. mg_free(ctx->client_socks);
  11594. mg_free(ctx->workerthreadids);
  11595. free_context(ctx);
  11596. pthread_setspecific(sTlsKey, NULL);
  11597. return NULL;
  11598. }
  11599. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11600. ctx->client_wait_events[i] = event_create();
  11601. if (ctx->client_wait_events[i] == 0) {
  11602. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11603. /* TODO: clean all and exit */
  11604. }
  11605. }
  11606. #endif
  11607. }
  11608. #if defined(USE_TIMERS)
  11609. if (timers_init(ctx) != 0) {
  11610. mg_cry(fc(ctx), "Error creating timers");
  11611. free_context(ctx);
  11612. pthread_setspecific(sTlsKey, NULL);
  11613. return NULL;
  11614. }
  11615. #endif
  11616. /* Context has been created - init user libraries */
  11617. if (ctx->callbacks.init_context) {
  11618. ctx->callbacks.init_context(ctx);
  11619. }
  11620. ctx->callbacks.exit_context = exit_callback;
  11621. ctx->context_type = 1; /* server context */
  11622. /* Start master (listening) thread */
  11623. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11624. /* Start worker threads */
  11625. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11626. struct worker_thread_args *wta =
  11627. mg_malloc(sizeof(struct worker_thread_args));
  11628. if (wta) {
  11629. wta->ctx = ctx;
  11630. wta->index = (int)i;
  11631. }
  11632. if ((wta == NULL)
  11633. || (mg_start_thread_with_id(worker_thread,
  11634. wta,
  11635. &ctx->workerthreadids[i]) != 0)) {
  11636. /* thread was not created */
  11637. if (wta != NULL) {
  11638. mg_free(wta);
  11639. }
  11640. if (i > 0) {
  11641. mg_cry(fc(ctx),
  11642. "Cannot start worker thread %i: error %ld",
  11643. i + 1,
  11644. (long)ERRNO);
  11645. } else {
  11646. mg_cry(fc(ctx),
  11647. "Cannot create threads: error %ld",
  11648. (long)ERRNO);
  11649. free_context(ctx);
  11650. pthread_setspecific(sTlsKey, NULL);
  11651. return NULL;
  11652. }
  11653. break;
  11654. }
  11655. }
  11656. pthread_setspecific(sTlsKey, NULL);
  11657. return ctx;
  11658. }
  11659. /* Feature check API function */
  11660. unsigned
  11661. mg_check_feature(unsigned feature)
  11662. {
  11663. static const unsigned feature_set = 0
  11664. /* Set bits for available features according to API documentation.
  11665. * This bit mask is created at compile time, according to the active
  11666. * preprocessor defines. It is a single const value at runtime. */
  11667. #if !defined(NO_FILES)
  11668. | 0x0001u
  11669. #endif
  11670. #if !defined(NO_SSL)
  11671. | 0x0002u
  11672. #endif
  11673. #if !defined(NO_CGI)
  11674. | 0x0004u
  11675. #endif
  11676. #if defined(USE_IPV6)
  11677. | 0x0008u
  11678. #endif
  11679. #if defined(USE_WEBSOCKET)
  11680. | 0x0010u
  11681. #endif
  11682. #if defined(USE_LUA)
  11683. | 0x0020u
  11684. #endif
  11685. #if defined(USE_DUKTAPE)
  11686. | 0x0040u
  11687. #endif
  11688. #if !defined(NO_CACHING)
  11689. | 0x0080u
  11690. #endif
  11691. /* Set some extra bits not defined in the API documentation.
  11692. * These bits may change without further notice. */
  11693. #if defined(MG_LEGACY_INTERFACE)
  11694. | 0x8000u
  11695. #endif
  11696. #if defined(MEMORY_DEBUGGING)
  11697. | 0x0100u
  11698. #endif
  11699. #if defined(USE_TIMERS)
  11700. | 0x0200u
  11701. #endif
  11702. #if !defined(NO_NONCE_CHECK)
  11703. | 0x0400u
  11704. #endif
  11705. #if !defined(NO_POPEN)
  11706. | 0x0800u
  11707. #endif
  11708. ;
  11709. return (feature & feature_set);
  11710. }