civetweb.c 351 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627
  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. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __MACH__
  114. #define CLOCK_MONOTONIC (1)
  115. #define CLOCK_REALTIME (2)
  116. #include <sys/time.h>
  117. #include <mach/clock.h>
  118. #include <mach/mach.h>
  119. #include <mach/mach_time.h>
  120. #include <assert.h>
  121. /* clock_gettime is not implemented on OSX */
  122. int clock_gettime(int clk_id, struct timespec *t);
  123. int
  124. clock_gettime(int clk_id, struct timespec *t)
  125. {
  126. memset(t, 0, sizeof(*t));
  127. if (clk_id == CLOCK_REALTIME) {
  128. struct timeval now;
  129. int rv = gettimeofday(&now, NULL);
  130. if (rv) {
  131. return rv;
  132. }
  133. t->tv_sec = now.tv_sec;
  134. t->tv_nsec = now.tv_usec * 1000;
  135. return 0;
  136. } else if (clk_id == CLOCK_MONOTONIC) {
  137. static uint64_t clock_start_time = 0;
  138. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  139. uint64_t now = mach_absolute_time();
  140. if (clock_start_time == 0) {
  141. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  142. #if defined(DEBUG)
  143. assert(mach_status == KERN_SUCCESS);
  144. #else
  145. /* appease "unused variable" warning for release builds */
  146. (void)mach_status;
  147. #endif
  148. clock_start_time = now;
  149. }
  150. now = (uint64_t)((double)(now - clock_start_time)
  151. * (double)timebase_ifo.numer
  152. / (double)timebase_ifo.denom);
  153. t->tv_sec = now / 1000000000;
  154. t->tv_nsec = now % 1000000000;
  155. return 0;
  156. }
  157. return -1; /* EINVAL - Clock ID is unknown */
  158. }
  159. #endif
  160. #include <time.h>
  161. #include <stdlib.h>
  162. #include <stdarg.h>
  163. #include <assert.h>
  164. #include <string.h>
  165. #include <ctype.h>
  166. #include <limits.h>
  167. #include <stddef.h>
  168. #include <stdio.h>
  169. #ifndef MAX_WORKER_THREADS
  170. #define MAX_WORKER_THREADS (1024 * 64)
  171. #endif
  172. #define SHUTDOWN_RD (0)
  173. #define SHUTDOWN_WR (1)
  174. #define SHUTDOWN_BOTH (2)
  175. mg_static_assert(MAX_WORKER_THREADS >= 1,
  176. "worker threads must be a positive number");
  177. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  178. "size_t data type size check");
  179. #if defined(_WIN32) \
  180. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  181. #include <windows.h>
  182. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  183. #include <ws2tcpip.h>
  184. typedef const char *SOCK_OPT_TYPE;
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (MAX_PATH)
  187. #endif
  188. #if !defined(PATH_MAX)
  189. #define PATH_MAX (4096)
  190. #endif
  191. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  192. #ifndef _IN_PORT_T
  193. #ifndef in_port_t
  194. #define in_port_t u_short
  195. #endif
  196. #endif
  197. #ifndef _WIN32_WCE
  198. #include <process.h>
  199. #include <direct.h>
  200. #include <io.h>
  201. #else /* _WIN32_WCE */
  202. #define NO_CGI /* WinCE has no pipes */
  203. #define NO_POPEN /* WinCE has no popen */
  204. typedef long off_t;
  205. #define errno ((int)(GetLastError()))
  206. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  207. #endif /* _WIN32_WCE */
  208. #define MAKEUQUAD(lo, hi) \
  209. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  210. #define RATE_DIFF (10000000) /* 100 nsecs */
  211. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  212. #define SYS2UNIX_TIME(lo, hi) \
  213. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  214. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  215. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  216. * Also use _strtoui64 on modern M$ compilers */
  217. #if defined(_MSC_VER)
  218. #if (_MSC_VER < 1300)
  219. #define STRX(x) #x
  220. #define STR(x) STRX(x)
  221. #define __func__ __FILE__ ":" STR(__LINE__)
  222. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  223. #define strtoll(x, y, z) (_atoi64(x))
  224. #else
  225. #define __func__ __FUNCTION__
  226. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  227. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  228. #endif
  229. #endif /* _MSC_VER */
  230. #define ERRNO ((int)(GetLastError()))
  231. #define NO_SOCKLEN_T
  232. #if defined(_WIN64) || defined(__MINGW64__)
  233. #define SSL_LIB "ssleay64.dll"
  234. #define CRYPTO_LIB "libeay64.dll"
  235. #else
  236. #define SSL_LIB "ssleay32.dll"
  237. #define CRYPTO_LIB "libeay32.dll"
  238. #endif
  239. #define O_NONBLOCK (0)
  240. #ifndef W_OK
  241. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  242. #endif
  243. #if !defined(EWOULDBLOCK)
  244. #define EWOULDBLOCK WSAEWOULDBLOCK
  245. #endif /* !EWOULDBLOCK */
  246. #define _POSIX_
  247. #define INT64_FMT "I64d"
  248. #define UINT64_FMT "I64u"
  249. #define WINCDECL __cdecl
  250. #define 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. void **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. #if defined(ALTERNATIVE_QUEUE)
  1363. static void *
  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 (void *)ret;
  1373. }
  1374. static int
  1375. event_wait(void *eventhdl)
  1376. {
  1377. uint64_t u;
  1378. int s = (int)read((int)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(void *eventhdl)
  1388. {
  1389. uint64_t u = 1;
  1390. int s = (int)write((int)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(void *eventhdl)
  1399. {
  1400. close((int)eventhdl);
  1401. }
  1402. #endif
  1403. #endif
  1404. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1405. struct posix_event {
  1406. pthread_mutex_t mutex;
  1407. pthread_cond_t cond;
  1408. };
  1409. static void *
  1410. event_create(void)
  1411. {
  1412. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1413. if (ret == 0) {
  1414. /* out of memory */
  1415. return 0;
  1416. }
  1417. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1418. /* pthread mutex not available */
  1419. mg_free(ret);
  1420. return 0;
  1421. }
  1422. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1423. /* pthread cond not available */
  1424. pthread_mutex_destroy(&(ret->mutex));
  1425. mg_free(ret);
  1426. return 0;
  1427. }
  1428. return (void *)ret;
  1429. }
  1430. static int
  1431. event_wait(void *eventhdl)
  1432. {
  1433. struct posix_event *ev = (struct posix_event *)eventhdl;
  1434. pthread_mutex_lock(&(ev->mutex));
  1435. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1436. pthread_mutex_unlock(&(ev->mutex));
  1437. return 1;
  1438. }
  1439. static int
  1440. event_signal(void *eventhdl)
  1441. {
  1442. struct posix_event *ev = (struct posix_event *)eventhdl;
  1443. pthread_mutex_lock(&(ev->mutex));
  1444. pthread_cond_signal(&(ev->cond));
  1445. pthread_mutex_unlock(&(ev->mutex));
  1446. return 1;
  1447. }
  1448. static void
  1449. event_destroy(void *eventhdl)
  1450. {
  1451. struct posix_event *ev = (struct posix_event *)eventhdl;
  1452. pthread_cond_destroy(&(ev->cond));
  1453. pthread_mutex_destroy(&(ev->mutex));
  1454. mg_free(ev);
  1455. }
  1456. #endif
  1457. static void
  1458. mg_set_thread_name(const char *name)
  1459. {
  1460. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1461. mg_snprintf(
  1462. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1463. #if defined(_WIN32)
  1464. #if defined(_MSC_VER)
  1465. /* Windows and Visual Studio Compiler */
  1466. __try
  1467. {
  1468. THREADNAME_INFO info;
  1469. info.dwType = 0x1000;
  1470. info.szName = threadName;
  1471. info.dwThreadID = ~0U;
  1472. info.dwFlags = 0;
  1473. RaiseException(0x406D1388,
  1474. 0,
  1475. sizeof(info) / sizeof(ULONG_PTR),
  1476. (ULONG_PTR *)&info);
  1477. }
  1478. __except(EXCEPTION_EXECUTE_HANDLER)
  1479. {
  1480. }
  1481. #elif defined(__MINGW32__)
  1482. /* No option known to set thread name for MinGW */
  1483. #endif
  1484. #elif defined(__GLIBC__) \
  1485. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1486. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1487. (void)pthread_setname_np(pthread_self(), threadName);
  1488. #elif defined(__linux__)
  1489. /* on linux we can use the old prctl function */
  1490. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1491. #endif
  1492. }
  1493. #else /* !defined(NO_THREAD_NAME) */
  1494. void
  1495. mg_set_thread_name(const char *threadName)
  1496. {
  1497. }
  1498. #endif
  1499. #if defined(MG_LEGACY_INTERFACE)
  1500. const char **
  1501. mg_get_valid_option_names(void)
  1502. {
  1503. /* This function is deprecated. Use mg_get_valid_options instead. */
  1504. static const char *
  1505. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1506. int i;
  1507. for (i = 0; config_options[i].name != NULL; i++) {
  1508. data[i * 2] = config_options[i].name;
  1509. data[i * 2 + 1] = config_options[i].default_value;
  1510. }
  1511. return data;
  1512. }
  1513. #endif
  1514. const struct mg_option *
  1515. mg_get_valid_options(void)
  1516. {
  1517. return config_options;
  1518. }
  1519. static int
  1520. is_file_in_memory(const struct mg_connection *conn,
  1521. const char *path,
  1522. struct file *filep)
  1523. {
  1524. size_t size = 0;
  1525. if (!conn || !filep) {
  1526. return 0;
  1527. }
  1528. if (conn->ctx->callbacks.open_file) {
  1529. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1530. if (filep->membuf != NULL) {
  1531. /* NOTE: override filep->size only on success. Otherwise, it might
  1532. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1533. filep->size = size;
  1534. }
  1535. }
  1536. return filep->membuf != NULL;
  1537. }
  1538. static int
  1539. is_file_opened(const struct file *filep)
  1540. {
  1541. if (!filep) {
  1542. return 0;
  1543. }
  1544. return filep->membuf != NULL || filep->fp != NULL;
  1545. }
  1546. /* mg_fopen will open a file either in memory or on the disk.
  1547. * The input parameter path is a string in UTF-8 encoding.
  1548. * The input parameter mode is the same as for fopen.
  1549. * Either fp or membuf will be set in the output struct filep.
  1550. * The function returns 1 on success, 0 on error. */
  1551. static int
  1552. mg_fopen(const struct mg_connection *conn,
  1553. const char *path,
  1554. const char *mode,
  1555. struct file *filep)
  1556. {
  1557. struct stat st;
  1558. if (!filep) {
  1559. return 0;
  1560. }
  1561. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1562. * only get the file status. They should not work on different members of
  1563. * the same structure (bad cohesion). */
  1564. memset(filep, 0, sizeof(*filep));
  1565. if (stat(path, &st) == 0) {
  1566. filep->size = (uint64_t)(st.st_size);
  1567. }
  1568. if (!is_file_in_memory(conn, path, filep)) {
  1569. #ifdef _WIN32
  1570. wchar_t wbuf[PATH_MAX], wmode[20];
  1571. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1572. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1573. filep->fp = _wfopen(wbuf, wmode);
  1574. #else
  1575. /* Linux et al already use unicode. No need to convert. */
  1576. filep->fp = fopen(path, mode);
  1577. #endif
  1578. }
  1579. return is_file_opened(filep);
  1580. }
  1581. static void
  1582. mg_fclose(struct file *filep)
  1583. {
  1584. if (filep != NULL && filep->fp != NULL) {
  1585. fclose(filep->fp);
  1586. }
  1587. }
  1588. static void
  1589. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1590. {
  1591. for (; *src != '\0' && n > 1; n--) {
  1592. *dst++ = *src++;
  1593. }
  1594. *dst = '\0';
  1595. }
  1596. static int
  1597. lowercase(const char *s)
  1598. {
  1599. return tolower(*(const unsigned char *)s);
  1600. }
  1601. int
  1602. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1603. {
  1604. int diff = 0;
  1605. if (len > 0) {
  1606. do {
  1607. diff = lowercase(s1++) - lowercase(s2++);
  1608. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1609. }
  1610. return diff;
  1611. }
  1612. int
  1613. mg_strcasecmp(const char *s1, const char *s2)
  1614. {
  1615. int diff;
  1616. do {
  1617. diff = lowercase(s1++) - lowercase(s2++);
  1618. } while (diff == 0 && s1[-1] != '\0');
  1619. return diff;
  1620. }
  1621. static char *
  1622. mg_strndup(const char *ptr, size_t len)
  1623. {
  1624. char *p;
  1625. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1626. mg_strlcpy(p, ptr, len + 1);
  1627. }
  1628. return p;
  1629. }
  1630. static char *
  1631. mg_strdup(const char *str)
  1632. {
  1633. return mg_strndup(str, strlen(str));
  1634. }
  1635. static const char *
  1636. mg_strcasestr(const char *big_str, const char *small_str)
  1637. {
  1638. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1639. if (big_len >= small_len) {
  1640. for (i = 0; i <= (big_len - small_len); i++) {
  1641. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1642. return big_str + i;
  1643. }
  1644. }
  1645. }
  1646. return NULL;
  1647. }
  1648. /* Return null terminated string of given maximum length.
  1649. * Report errors if length is exceeded. */
  1650. static void
  1651. mg_vsnprintf(const struct mg_connection *conn,
  1652. int *truncated,
  1653. char *buf,
  1654. size_t buflen,
  1655. const char *fmt,
  1656. va_list ap)
  1657. {
  1658. int n, ok;
  1659. if (buflen == 0) {
  1660. return;
  1661. }
  1662. #ifdef __clang__
  1663. #pragma clang diagnostic push
  1664. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1665. /* Using fmt as a non-literal is intended here, since it is mostly called
  1666. * indirectly by mg_snprintf */
  1667. #endif
  1668. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1669. ok = (n >= 0) && ((size_t)n < buflen);
  1670. #ifdef __clang__
  1671. #pragma clang diagnostic pop
  1672. #endif
  1673. if (ok) {
  1674. if (truncated) {
  1675. *truncated = 0;
  1676. }
  1677. } else {
  1678. if (truncated) {
  1679. *truncated = 1;
  1680. }
  1681. mg_cry(conn,
  1682. "truncating vsnprintf buffer: [%.*s]",
  1683. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1684. buf);
  1685. n = (int)buflen - 1;
  1686. }
  1687. buf[n] = '\0';
  1688. }
  1689. static void
  1690. mg_snprintf(const struct mg_connection *conn,
  1691. int *truncated,
  1692. char *buf,
  1693. size_t buflen,
  1694. const char *fmt,
  1695. ...)
  1696. {
  1697. va_list ap;
  1698. va_start(ap, fmt);
  1699. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1700. va_end(ap);
  1701. }
  1702. static int
  1703. get_option_index(const char *name)
  1704. {
  1705. int i;
  1706. for (i = 0; config_options[i].name != NULL; i++) {
  1707. if (strcmp(config_options[i].name, name) == 0) {
  1708. return i;
  1709. }
  1710. }
  1711. return -1;
  1712. }
  1713. const char *
  1714. mg_get_option(const struct mg_context *ctx, const char *name)
  1715. {
  1716. int i;
  1717. if ((i = get_option_index(name)) == -1) {
  1718. return NULL;
  1719. } else if (!ctx || ctx->config[i] == NULL) {
  1720. return "";
  1721. } else {
  1722. return ctx->config[i];
  1723. }
  1724. }
  1725. struct mg_context *
  1726. mg_get_context(const struct mg_connection *conn)
  1727. {
  1728. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1729. }
  1730. void *
  1731. mg_get_user_data(const struct mg_context *ctx)
  1732. {
  1733. return (ctx == NULL) ? NULL : ctx->user_data;
  1734. }
  1735. void
  1736. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1737. {
  1738. if (conn != NULL) {
  1739. conn->request_info.conn_data = data;
  1740. }
  1741. }
  1742. void *
  1743. mg_get_user_connection_data(const struct mg_connection *conn)
  1744. {
  1745. if (conn != NULL) {
  1746. return conn->request_info.conn_data;
  1747. }
  1748. return NULL;
  1749. }
  1750. size_t
  1751. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1752. {
  1753. size_t i;
  1754. if (!ctx) {
  1755. return 0;
  1756. }
  1757. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1758. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1759. ports[i] =
  1760. #if defined(USE_IPV6)
  1761. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1762. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1763. :
  1764. #endif
  1765. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1766. }
  1767. return i;
  1768. }
  1769. int
  1770. mg_get_server_ports(const struct mg_context *ctx,
  1771. int size,
  1772. struct mg_server_ports *ports)
  1773. {
  1774. int i, cnt = 0;
  1775. if (size <= 0) {
  1776. return -1;
  1777. }
  1778. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1779. if (!ctx) {
  1780. return -1;
  1781. }
  1782. if (!ctx->listening_sockets) {
  1783. return -1;
  1784. }
  1785. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1786. ports[cnt].port =
  1787. #if defined(USE_IPV6)
  1788. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1789. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1790. :
  1791. #endif
  1792. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1793. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1794. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1795. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1796. /* IPv4 */
  1797. ports[cnt].protocol = 1;
  1798. cnt++;
  1799. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1800. /* IPv6 */
  1801. ports[cnt].protocol = 3;
  1802. cnt++;
  1803. }
  1804. }
  1805. return cnt;
  1806. }
  1807. static void
  1808. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1809. {
  1810. buf[0] = '\0';
  1811. if (!usa) {
  1812. return;
  1813. }
  1814. if (usa->sa.sa_family == AF_INET) {
  1815. getnameinfo(&usa->sa,
  1816. sizeof(usa->sin),
  1817. buf,
  1818. (unsigned)len,
  1819. NULL,
  1820. 0,
  1821. NI_NUMERICHOST);
  1822. }
  1823. #if defined(USE_IPV6)
  1824. else if (usa->sa.sa_family == AF_INET6) {
  1825. getnameinfo(&usa->sa,
  1826. sizeof(usa->sin6),
  1827. buf,
  1828. (unsigned)len,
  1829. NULL,
  1830. 0,
  1831. NI_NUMERICHOST);
  1832. }
  1833. #endif
  1834. }
  1835. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1836. * included in all responses other than 100, 101, 5xx. */
  1837. static void
  1838. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1839. {
  1840. struct tm *tm;
  1841. tm = ((t != NULL) ? gmtime(t) : NULL);
  1842. if (tm != NULL) {
  1843. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1844. } else {
  1845. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1846. buf[buf_len - 1] = '\0';
  1847. }
  1848. }
  1849. /* difftime for struct timespec. Return value is in seconds. */
  1850. static double
  1851. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1852. {
  1853. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1854. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1855. }
  1856. /* Print error message to the opened error log stream. */
  1857. void
  1858. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1859. {
  1860. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1861. va_list ap;
  1862. struct file fi;
  1863. time_t timestamp;
  1864. va_start(ap, fmt);
  1865. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1866. va_end(ap);
  1867. buf[sizeof(buf) - 1] = 0;
  1868. if (!conn) {
  1869. puts(buf);
  1870. return;
  1871. }
  1872. /* Do not lock when getting the callback value, here and below.
  1873. * I suppose this is fine, since function cannot disappear in the
  1874. * same way string option can. */
  1875. if ((conn->ctx->callbacks.log_message == NULL)
  1876. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1877. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1878. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1879. == 0) {
  1880. fi.fp = NULL;
  1881. }
  1882. } else {
  1883. fi.fp = NULL;
  1884. }
  1885. if (fi.fp != NULL) {
  1886. flockfile(fi.fp);
  1887. timestamp = time(NULL);
  1888. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1889. fprintf(fi.fp,
  1890. "[%010lu] [error] [client %s] ",
  1891. (unsigned long)timestamp,
  1892. src_addr);
  1893. if (conn->request_info.request_method != NULL) {
  1894. fprintf(fi.fp,
  1895. "%s %s: ",
  1896. conn->request_info.request_method,
  1897. conn->request_info.request_uri);
  1898. }
  1899. fprintf(fi.fp, "%s", buf);
  1900. fputc('\n', fi.fp);
  1901. fflush(fi.fp);
  1902. funlockfile(fi.fp);
  1903. mg_fclose(&fi);
  1904. }
  1905. }
  1906. }
  1907. /* Return fake connection structure. Used for logging, if connection
  1908. * is not applicable at the moment of logging. */
  1909. static struct mg_connection *
  1910. fc(struct mg_context *ctx)
  1911. {
  1912. static struct mg_connection fake_connection;
  1913. fake_connection.ctx = ctx;
  1914. return &fake_connection;
  1915. }
  1916. const char *
  1917. mg_version(void)
  1918. {
  1919. return CIVETWEB_VERSION;
  1920. }
  1921. const struct mg_request_info *
  1922. mg_get_request_info(const struct mg_connection *conn)
  1923. {
  1924. if (!conn) {
  1925. return NULL;
  1926. }
  1927. return &conn->request_info;
  1928. }
  1929. /* Skip the characters until one of the delimiters characters found.
  1930. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1931. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1932. * Delimiters can be quoted with quotechar. */
  1933. static char *
  1934. skip_quoted(char **buf,
  1935. const char *delimiters,
  1936. const char *whitespace,
  1937. char quotechar)
  1938. {
  1939. char *p, *begin_word, *end_word, *end_whitespace;
  1940. begin_word = *buf;
  1941. end_word = begin_word + strcspn(begin_word, delimiters);
  1942. /* Check for quotechar */
  1943. if (end_word > begin_word) {
  1944. p = end_word - 1;
  1945. while (*p == quotechar) {
  1946. /* While the delimiter is quoted, look for the next delimiter. */
  1947. /* This happens, e.g., in calls from parse_auth_header,
  1948. * if the user name contains a " character. */
  1949. /* If there is anything beyond end_word, copy it. */
  1950. if (*end_word != '\0') {
  1951. size_t end_off = strcspn(end_word + 1, delimiters);
  1952. memmove(p, end_word, end_off + 1);
  1953. p += end_off; /* p must correspond to end_word - 1 */
  1954. end_word += end_off + 1;
  1955. } else {
  1956. *p = '\0';
  1957. break;
  1958. }
  1959. }
  1960. for (p++; p < end_word; p++) {
  1961. *p = '\0';
  1962. }
  1963. }
  1964. if (*end_word == '\0') {
  1965. *buf = end_word;
  1966. } else {
  1967. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1968. for (p = end_word; p < end_whitespace; p++) {
  1969. *p = '\0';
  1970. }
  1971. *buf = end_whitespace;
  1972. }
  1973. return begin_word;
  1974. }
  1975. /* Simplified version of skip_quoted without quote char
  1976. * and whitespace == delimiters */
  1977. static char *
  1978. skip(char **buf, const char *delimiters)
  1979. {
  1980. return skip_quoted(buf, delimiters, delimiters, 0);
  1981. }
  1982. /* Return HTTP header value, or NULL if not found. */
  1983. static const char *
  1984. get_header(const struct mg_request_info *ri, const char *name)
  1985. {
  1986. int i;
  1987. if (ri) {
  1988. for (i = 0; i < ri->num_headers; i++) {
  1989. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1990. return ri->http_headers[i].value;
  1991. }
  1992. }
  1993. }
  1994. return NULL;
  1995. }
  1996. const char *
  1997. mg_get_header(const struct mg_connection *conn, const char *name)
  1998. {
  1999. if (!conn) {
  2000. return NULL;
  2001. }
  2002. return get_header(&conn->request_info, name);
  2003. }
  2004. /* A helper function for traversing a comma separated list of values.
  2005. * It returns a list pointer shifted to the next value, or NULL if the end
  2006. * of the list found.
  2007. * Value is stored in val vector. If value has form "x=y", then eq_val
  2008. * vector is initialized to point to the "y" part, and val vector length
  2009. * is adjusted to point only to "x". */
  2010. static const char *
  2011. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2012. {
  2013. int end;
  2014. reparse:
  2015. if (val == NULL || list == NULL || *list == '\0') {
  2016. /* End of the list */
  2017. list = NULL;
  2018. } else {
  2019. /* Skip over leading LWS */
  2020. while (*list == ' ' || *list == '\t')
  2021. list++;
  2022. val->ptr = list;
  2023. if ((list = strchr(val->ptr, ',')) != NULL) {
  2024. /* Comma found. Store length and shift the list ptr */
  2025. val->len = ((size_t)(list - val->ptr));
  2026. list++;
  2027. } else {
  2028. /* This value is the last one */
  2029. list = val->ptr + strlen(val->ptr);
  2030. val->len = ((size_t)(list - val->ptr));
  2031. }
  2032. /* Adjust length for trailing LWS */
  2033. end = (int)val->len - 1;
  2034. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2035. end--;
  2036. val->len = (size_t)(end + 1);
  2037. if (val->len == 0) {
  2038. /* Ignore any empty entries. */
  2039. goto reparse;
  2040. }
  2041. if (eq_val != NULL) {
  2042. /* Value has form "x=y", adjust pointers and lengths
  2043. * so that val points to "x", and eq_val points to "y". */
  2044. eq_val->len = 0;
  2045. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2046. if (eq_val->ptr != NULL) {
  2047. eq_val->ptr++; /* Skip over '=' character */
  2048. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2049. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2050. }
  2051. }
  2052. }
  2053. return list;
  2054. }
  2055. /* A helper function for checking if a comma separated list of values contains
  2056. * the given option (case insensitvely).
  2057. * 'header' can be NULL, in which case false is returned. */
  2058. static int
  2059. header_has_option(const char *header, const char *option)
  2060. {
  2061. struct vec opt_vec;
  2062. struct vec eq_vec;
  2063. assert(option != NULL);
  2064. assert(option[0] != '\0');
  2065. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2066. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2067. return 1;
  2068. }
  2069. return 0;
  2070. }
  2071. /* Perform case-insensitive match of string against pattern */
  2072. static int
  2073. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2074. {
  2075. const char *or_str;
  2076. size_t i;
  2077. int j, len, res;
  2078. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2079. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2080. return (res > 0) ? res : match_prefix(or_str + 1,
  2081. (size_t)((pattern + pattern_len)
  2082. - (or_str + 1)),
  2083. str);
  2084. }
  2085. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2086. if (pattern[i] == '?' && str[j] != '\0') {
  2087. continue;
  2088. } else if (pattern[i] == '$') {
  2089. return (str[j] == '\0') ? j : -1;
  2090. } else if (pattern[i] == '*') {
  2091. i++;
  2092. if (pattern[i] == '*') {
  2093. i++;
  2094. len = (int)strlen(str + j);
  2095. } else {
  2096. len = (int)strcspn(str + j, "/");
  2097. }
  2098. if (i == pattern_len) {
  2099. return j + len;
  2100. }
  2101. do {
  2102. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2103. } while (res == -1 && len-- > 0);
  2104. return (res == -1) ? -1 : j + res + len;
  2105. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2106. return -1;
  2107. }
  2108. }
  2109. return j;
  2110. }
  2111. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2112. * This function must tolerate situations when connection info is not
  2113. * set up, for example if request parsing failed. */
  2114. static int
  2115. should_keep_alive(const struct mg_connection *conn)
  2116. {
  2117. if (conn != NULL) {
  2118. const char *http_version = conn->request_info.http_version;
  2119. const char *header = mg_get_header(conn, "Connection");
  2120. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2121. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2122. || (header != NULL && !header_has_option(header, "keep-alive"))
  2123. || (header == NULL && http_version
  2124. && 0 != strcmp(http_version, "1.1"))) {
  2125. return 0;
  2126. }
  2127. return 1;
  2128. }
  2129. return 0;
  2130. }
  2131. static int
  2132. should_decode_url(const struct mg_connection *conn)
  2133. {
  2134. if (!conn || !conn->ctx) {
  2135. return 0;
  2136. }
  2137. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2138. }
  2139. static const char *
  2140. suggest_connection_header(const struct mg_connection *conn)
  2141. {
  2142. return should_keep_alive(conn) ? "keep-alive" : "close";
  2143. }
  2144. static int
  2145. send_no_cache_header(struct mg_connection *conn)
  2146. {
  2147. /* Send all current and obsolete cache opt-out directives. */
  2148. return mg_printf(conn,
  2149. "Cache-Control: no-cache, no-store, "
  2150. "must-revalidate, private, max-age=0\r\n"
  2151. "Pragma: no-cache\r\n"
  2152. "Expires: 0\r\n");
  2153. }
  2154. static int
  2155. send_static_cache_header(struct mg_connection *conn)
  2156. {
  2157. #if !defined(NO_CACHING)
  2158. /* Read the server config to check how long a file may be cached.
  2159. * The configuration is in seconds. */
  2160. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2161. if (max_age <= 0) {
  2162. /* 0 means "do not cache". All values <0 are reserved
  2163. * and may be used differently in the future. */
  2164. /* If a file should not be cached, do not only send
  2165. * max-age=0, but also pragmas and Expires headers. */
  2166. return send_no_cache_header(conn);
  2167. }
  2168. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2169. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2170. /* See also https://www.mnot.net/cache_docs/ */
  2171. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2172. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2173. * year to 31622400 seconds. For the moment, we just send whatever has
  2174. * been configured, still the behavior for >1 year should be considered
  2175. * as undefined. */
  2176. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2177. #else /* NO_CACHING */
  2178. return send_no_cache_header(conn);
  2179. #endif /* !NO_CACHING */
  2180. }
  2181. static void handle_file_based_request(struct mg_connection *conn,
  2182. const char *path,
  2183. struct file *filep);
  2184. static int
  2185. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2186. const char *
  2187. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2188. {
  2189. /* See IANA HTTP status code assignment:
  2190. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2191. */
  2192. switch (response_code) {
  2193. /* RFC2616 Section 10.1 - Informational 1xx */
  2194. case 100:
  2195. return "Continue"; /* RFC2616 Section 10.1.1 */
  2196. case 101:
  2197. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2198. case 102:
  2199. return "Processing"; /* RFC2518 Section 10.1 */
  2200. /* RFC2616 Section 10.2 - Successful 2xx */
  2201. case 200:
  2202. return "OK"; /* RFC2616 Section 10.2.1 */
  2203. case 201:
  2204. return "Created"; /* RFC2616 Section 10.2.2 */
  2205. case 202:
  2206. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2207. case 203:
  2208. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2209. case 204:
  2210. return "No Content"; /* RFC2616 Section 10.2.5 */
  2211. case 205:
  2212. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2213. case 206:
  2214. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2215. case 207:
  2216. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2217. case 208:
  2218. return "Already Reported"; /* RFC5842 Section 7.1 */
  2219. case 226:
  2220. return "IM used"; /* RFC3229 Section 10.4.1 */
  2221. /* RFC2616 Section 10.3 - Redirection 3xx */
  2222. case 300:
  2223. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2224. case 301:
  2225. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2226. case 302:
  2227. return "Found"; /* RFC2616 Section 10.3.3 */
  2228. case 303:
  2229. return "See Other"; /* RFC2616 Section 10.3.4 */
  2230. case 304:
  2231. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2232. case 305:
  2233. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2234. case 307:
  2235. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2236. case 308:
  2237. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2238. /* RFC2616 Section 10.4 - Client Error 4xx */
  2239. case 400:
  2240. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2241. case 401:
  2242. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2243. case 402:
  2244. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2245. case 403:
  2246. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2247. case 404:
  2248. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2249. case 405:
  2250. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2251. case 406:
  2252. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2253. case 407:
  2254. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2255. case 408:
  2256. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2257. case 409:
  2258. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2259. case 410:
  2260. return "Gone"; /* RFC2616 Section 10.4.11 */
  2261. case 411:
  2262. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2263. case 412:
  2264. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2265. case 413:
  2266. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2267. case 414:
  2268. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2269. case 415:
  2270. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2271. case 416:
  2272. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2273. case 417:
  2274. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2275. case 421:
  2276. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2277. case 422:
  2278. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2279. * Section 11.2 */
  2280. case 423:
  2281. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2282. case 424:
  2283. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2284. * Section 11.4 */
  2285. case 426:
  2286. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2287. case 428:
  2288. return "Precondition Required"; /* RFC 6585, Section 3 */
  2289. case 429:
  2290. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2291. case 431:
  2292. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2293. case 451:
  2294. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2295. * Section 3 */
  2296. /* RFC2616 Section 10.5 - Server Error 5xx */
  2297. case 500:
  2298. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2299. case 501:
  2300. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2301. case 502:
  2302. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2303. case 503:
  2304. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2305. case 504:
  2306. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2307. case 505:
  2308. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2309. case 506:
  2310. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2311. case 507:
  2312. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2313. * Section 11.5 */
  2314. case 508:
  2315. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2316. case 510:
  2317. return "Not Extended"; /* RFC 2774, Section 7 */
  2318. case 511:
  2319. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2320. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2321. * E.g., "de facto" standards due to common use, ... */
  2322. case 418:
  2323. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2324. case 419:
  2325. return "Authentication Timeout"; /* common use */
  2326. case 420:
  2327. return "Enhance Your Calm"; /* common use */
  2328. case 440:
  2329. return "Login Timeout"; /* common use */
  2330. case 509:
  2331. return "Bandwidth Limit Exceeded"; /* common use */
  2332. default:
  2333. /* This error code is unknown. This should not happen. */
  2334. if (conn) {
  2335. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2336. }
  2337. /* Return at least a category according to RFC 2616 Section 10. */
  2338. if (response_code >= 100 && response_code < 200) {
  2339. /* Unknown informational status code */
  2340. return "Information";
  2341. }
  2342. if (response_code >= 200 && response_code < 300) {
  2343. /* Unknown success code */
  2344. return "Success";
  2345. }
  2346. if (response_code >= 300 && response_code < 400) {
  2347. /* Unknown redirection code */
  2348. return "Redirection";
  2349. }
  2350. if (response_code >= 400 && response_code < 500) {
  2351. /* Unknown request error code */
  2352. return "Client Error";
  2353. }
  2354. if (response_code >= 500 && response_code < 600) {
  2355. /* Unknown server error code */
  2356. return "Server Error";
  2357. }
  2358. /* Response code not even within reasonable range */
  2359. return "";
  2360. }
  2361. }
  2362. static void send_http_error(struct mg_connection *,
  2363. int,
  2364. PRINTF_FORMAT_STRING(const char *fmt),
  2365. ...) PRINTF_ARGS(3, 4);
  2366. static void
  2367. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2368. {
  2369. char buf[MG_BUF_LEN];
  2370. va_list ap;
  2371. int len, i, page_handler_found, scope, truncated;
  2372. char date[64];
  2373. time_t curtime = time(NULL);
  2374. const char *error_handler = NULL;
  2375. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2376. const char *error_page_file_ext, *tstr;
  2377. const char *status_text = mg_get_response_code_text(conn, status);
  2378. if (conn == NULL) {
  2379. return;
  2380. }
  2381. conn->status_code = status;
  2382. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2383. || conn->ctx->callbacks.http_error(conn, status)) {
  2384. if (!conn->in_error_handler) {
  2385. /* Send user defined error pages, if defined */
  2386. error_handler = conn->ctx->config[ERROR_PAGES];
  2387. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2388. page_handler_found = 0;
  2389. if (error_handler != NULL) {
  2390. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2391. switch (scope) {
  2392. case 1: /* Handler for specific error, e.g. 404 error */
  2393. mg_snprintf(conn,
  2394. &truncated,
  2395. buf,
  2396. sizeof(buf) - 32,
  2397. "%serror%03u.",
  2398. error_handler,
  2399. status);
  2400. break;
  2401. case 2: /* Handler for error group, e.g., 5xx error handler
  2402. * for all server errors (500-599) */
  2403. mg_snprintf(conn,
  2404. &truncated,
  2405. buf,
  2406. sizeof(buf) - 32,
  2407. "%serror%01uxx.",
  2408. error_handler,
  2409. status / 100);
  2410. break;
  2411. default: /* Handler for all errors */
  2412. mg_snprintf(conn,
  2413. &truncated,
  2414. buf,
  2415. sizeof(buf) - 32,
  2416. "%serror.",
  2417. error_handler);
  2418. break;
  2419. }
  2420. /* String truncation in buf may only occur if error_handler
  2421. * is too long. This string is from the config, not from a
  2422. * client. */
  2423. (void)truncated;
  2424. len = (int)strlen(buf);
  2425. tstr = strchr(error_page_file_ext, '.');
  2426. while (tstr) {
  2427. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2428. i++)
  2429. buf[len + i - 1] = tstr[i];
  2430. buf[len + i - 1] = 0;
  2431. if (mg_stat(conn, buf, &error_page_file)) {
  2432. page_handler_found = 1;
  2433. break;
  2434. }
  2435. tstr = strchr(tstr + i, '.');
  2436. }
  2437. }
  2438. }
  2439. if (page_handler_found) {
  2440. conn->in_error_handler = 1;
  2441. handle_file_based_request(conn, buf, &error_page_file);
  2442. conn->in_error_handler = 0;
  2443. return;
  2444. }
  2445. }
  2446. /* No custom error page. Send default error page. */
  2447. gmt_time_string(date, sizeof(date), &curtime);
  2448. conn->must_close = 1;
  2449. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2450. send_no_cache_header(conn);
  2451. mg_printf(conn,
  2452. "Date: %s\r\n"
  2453. "Connection: close\r\n\r\n",
  2454. date);
  2455. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2456. if (status > 199 && status != 204 && status != 304) {
  2457. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2458. if (fmt != NULL) {
  2459. va_start(ap, fmt);
  2460. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2461. va_end(ap);
  2462. mg_write(conn, buf, strlen(buf));
  2463. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2464. }
  2465. } else {
  2466. /* No body allowed. Close the connection. */
  2467. DEBUG_TRACE("Error %i", status);
  2468. }
  2469. }
  2470. }
  2471. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2472. /* Create substitutes for POSIX functions in Win32. */
  2473. #if defined(__MINGW32__)
  2474. /* Show no warning in case system functions are not used. */
  2475. #pragma GCC diagnostic push
  2476. #pragma GCC diagnostic ignored "-Wunused-function"
  2477. #endif
  2478. static int
  2479. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2480. {
  2481. (void)unused;
  2482. *mutex = CreateMutex(NULL, FALSE, NULL);
  2483. return (*mutex == NULL) ? -1 : 0;
  2484. }
  2485. static int
  2486. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2487. {
  2488. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2489. }
  2490. static int
  2491. pthread_mutex_lock(pthread_mutex_t *mutex)
  2492. {
  2493. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2494. }
  2495. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2496. static int
  2497. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2498. {
  2499. switch (WaitForSingleObject(*mutex, 0)) {
  2500. case WAIT_OBJECT_0:
  2501. return 0;
  2502. case WAIT_TIMEOUT:
  2503. return -2; /* EBUSY */
  2504. }
  2505. return -1;
  2506. }
  2507. #endif
  2508. static int
  2509. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2510. {
  2511. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2512. }
  2513. #ifndef WIN_PTHREADS_TIME_H
  2514. static int
  2515. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2516. {
  2517. FILETIME ft;
  2518. ULARGE_INTEGER li;
  2519. BOOL ok = FALSE;
  2520. double d;
  2521. static double perfcnt_per_sec = 0.0;
  2522. if (tp) {
  2523. memset(tp, 0, sizeof(*tp));
  2524. if (clk_id == CLOCK_REALTIME) {
  2525. GetSystemTimeAsFileTime(&ft);
  2526. li.LowPart = ft.dwLowDateTime;
  2527. li.HighPart = ft.dwHighDateTime;
  2528. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2529. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2530. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2531. ok = TRUE;
  2532. } else if (clk_id == CLOCK_MONOTONIC) {
  2533. if (perfcnt_per_sec == 0.0) {
  2534. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2535. perfcnt_per_sec = 1.0 / li.QuadPart;
  2536. }
  2537. if (perfcnt_per_sec != 0.0) {
  2538. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2539. d = li.QuadPart * perfcnt_per_sec;
  2540. tp->tv_sec = (time_t)d;
  2541. d -= tp->tv_sec;
  2542. tp->tv_nsec = (long)(d * 1.0E9);
  2543. ok = TRUE;
  2544. }
  2545. }
  2546. }
  2547. return ok ? 0 : -1;
  2548. }
  2549. #endif
  2550. static int
  2551. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2552. {
  2553. (void)unused;
  2554. InitializeCriticalSection(&cv->threadIdSec);
  2555. cv->waiting_thread = NULL;
  2556. return 0;
  2557. }
  2558. static int
  2559. pthread_cond_timedwait(pthread_cond_t *cv,
  2560. pthread_mutex_t *mutex,
  2561. const struct timespec *abstime)
  2562. {
  2563. struct mg_workerTLS **ptls,
  2564. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2565. int ok;
  2566. struct timespec tsnow;
  2567. int64_t nsnow, nswaitabs, nswaitrel;
  2568. DWORD mswaitrel;
  2569. EnterCriticalSection(&cv->threadIdSec);
  2570. /* Add this thread to cv's waiting list */
  2571. ptls = &cv->waiting_thread;
  2572. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2573. ;
  2574. tls->next_waiting_thread = NULL;
  2575. *ptls = tls;
  2576. LeaveCriticalSection(&cv->threadIdSec);
  2577. if (abstime) {
  2578. clock_gettime(CLOCK_REALTIME, &tsnow);
  2579. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2580. nswaitabs =
  2581. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2582. nswaitrel = nswaitabs - nsnow;
  2583. if (nswaitrel < 0) {
  2584. nswaitrel = 0;
  2585. }
  2586. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2587. } else {
  2588. mswaitrel = INFINITE;
  2589. }
  2590. pthread_mutex_unlock(mutex);
  2591. ok = (WAIT_OBJECT_0
  2592. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2593. if (!ok) {
  2594. ok = 1;
  2595. EnterCriticalSection(&cv->threadIdSec);
  2596. ptls = &cv->waiting_thread;
  2597. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2598. if (*ptls == tls) {
  2599. *ptls = tls->next_waiting_thread;
  2600. ok = 0;
  2601. break;
  2602. }
  2603. }
  2604. LeaveCriticalSection(&cv->threadIdSec);
  2605. if (ok) {
  2606. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2607. }
  2608. }
  2609. /* This thread has been removed from cv's waiting list */
  2610. pthread_mutex_lock(mutex);
  2611. return ok ? 0 : -1;
  2612. }
  2613. static int
  2614. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2615. {
  2616. return pthread_cond_timedwait(cv, mutex, NULL);
  2617. }
  2618. static int
  2619. pthread_cond_signal(pthread_cond_t *cv)
  2620. {
  2621. HANDLE wkup = NULL;
  2622. BOOL ok = FALSE;
  2623. EnterCriticalSection(&cv->threadIdSec);
  2624. if (cv->waiting_thread) {
  2625. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2626. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2627. ok = SetEvent(wkup);
  2628. assert(ok);
  2629. }
  2630. LeaveCriticalSection(&cv->threadIdSec);
  2631. return ok ? 0 : 1;
  2632. }
  2633. static int
  2634. pthread_cond_broadcast(pthread_cond_t *cv)
  2635. {
  2636. EnterCriticalSection(&cv->threadIdSec);
  2637. while (cv->waiting_thread) {
  2638. pthread_cond_signal(cv);
  2639. }
  2640. LeaveCriticalSection(&cv->threadIdSec);
  2641. return 0;
  2642. }
  2643. static int
  2644. pthread_cond_destroy(pthread_cond_t *cv)
  2645. {
  2646. EnterCriticalSection(&cv->threadIdSec);
  2647. assert(cv->waiting_thread == NULL);
  2648. LeaveCriticalSection(&cv->threadIdSec);
  2649. DeleteCriticalSection(&cv->threadIdSec);
  2650. return 0;
  2651. }
  2652. #ifdef ALTERNATIVE_QUEUE
  2653. static void *
  2654. event_create(void)
  2655. {
  2656. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2657. }
  2658. static int
  2659. event_wait(void *eventhdl)
  2660. {
  2661. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2662. return (res == WAIT_OBJECT_0);
  2663. }
  2664. static int
  2665. event_signal(void *eventhdl)
  2666. {
  2667. return (int)SetEvent((HANDLE)eventhdl);
  2668. }
  2669. static void
  2670. event_destroy(void *eventhdl)
  2671. {
  2672. CloseHandle((HANDLE)eventhdl);
  2673. }
  2674. #endif
  2675. #if defined(__MINGW32__)
  2676. /* Enable unused function warning again */
  2677. #pragma GCC diagnostic pop
  2678. #endif
  2679. /* For Windows, change all slashes to backslashes in path names. */
  2680. static void
  2681. change_slashes_to_backslashes(char *path)
  2682. {
  2683. int i;
  2684. for (i = 0; path[i] != '\0'; i++) {
  2685. if (path[i] == '/') {
  2686. path[i] = '\\';
  2687. }
  2688. /* remove double backslash (check i > 0 to preserve UNC paths,
  2689. * like \\server\file.txt) */
  2690. if ((path[i] == '\\') && (i > 0)) {
  2691. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2692. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2693. }
  2694. }
  2695. }
  2696. }
  2697. static int
  2698. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2699. {
  2700. int diff;
  2701. do {
  2702. diff = tolower(*s1) - tolower(*s2);
  2703. s1++;
  2704. s2++;
  2705. } while (diff == 0 && s1[-1] != '\0');
  2706. return diff;
  2707. }
  2708. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2709. * wbuf and wbuf_len is a target buffer and its length. */
  2710. static void
  2711. path_to_unicode(const struct mg_connection *conn,
  2712. const char *path,
  2713. wchar_t *wbuf,
  2714. size_t wbuf_len)
  2715. {
  2716. char buf[PATH_MAX], buf2[PATH_MAX];
  2717. wchar_t wbuf2[MAX_PATH + 1];
  2718. DWORD long_len, err;
  2719. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2720. mg_strlcpy(buf, path, sizeof(buf));
  2721. change_slashes_to_backslashes(buf);
  2722. /* Convert to Unicode and back. If doubly-converted string does not
  2723. * match the original, something is fishy, reject. */
  2724. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2725. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2726. WideCharToMultiByte(
  2727. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2728. if (strcmp(buf, buf2) != 0) {
  2729. wbuf[0] = L'\0';
  2730. }
  2731. /* TODO: Add a configuration to switch between case sensitive and
  2732. * case insensitive URIs for Windows server. */
  2733. /*
  2734. if (conn) {
  2735. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2736. fcompare = wcscmp;
  2737. }
  2738. }
  2739. */
  2740. (void)conn; /* conn is currently unused */
  2741. #if !defined(_WIN32_WCE)
  2742. /* Only accept a full file path, not a Windows short (8.3) path. */
  2743. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2744. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2745. if (long_len == 0) {
  2746. err = GetLastError();
  2747. if (err == ERROR_FILE_NOT_FOUND) {
  2748. /* File does not exist. This is not always a problem here. */
  2749. return;
  2750. }
  2751. }
  2752. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2753. /* Short name is used. */
  2754. wbuf[0] = L'\0';
  2755. }
  2756. #else
  2757. (void)long_len;
  2758. (void)wbuf2;
  2759. (void)err;
  2760. if (strchr(path, '~')) {
  2761. wbuf[0] = L'\0';
  2762. }
  2763. #endif
  2764. }
  2765. /* Windows happily opens files with some garbage at the end of file name.
  2766. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2767. * "a.cgi", despite one would expect an error back.
  2768. * This function returns non-0 if path ends with some garbage. */
  2769. static int
  2770. path_cannot_disclose_cgi(const char *path)
  2771. {
  2772. static const char *allowed_last_characters = "_-";
  2773. int last = path[strlen(path) - 1];
  2774. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2775. }
  2776. static int
  2777. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2778. {
  2779. wchar_t wbuf[PATH_MAX];
  2780. WIN32_FILE_ATTRIBUTE_DATA info;
  2781. time_t creation_time;
  2782. if (!filep) {
  2783. return 0;
  2784. }
  2785. memset(filep, 0, sizeof(*filep));
  2786. if (conn && is_file_in_memory(conn, path, filep)) {
  2787. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2788. * memset */
  2789. filep->last_modified = time(NULL);
  2790. /* last_modified = now ... assumes the file may change during runtime,
  2791. * so every mg_fopen call may return different data */
  2792. /* last_modified = conn->ctx.start_time;
  2793. * May be used it the data does not change during runtime. This allows
  2794. * browser caching. Since we do not know, we have to assume the file
  2795. * in memory may change. */
  2796. return 1;
  2797. }
  2798. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2799. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2800. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2801. filep->last_modified =
  2802. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2803. info.ftLastWriteTime.dwHighDateTime);
  2804. /* On Windows, the file creation time can be higher than the
  2805. * modification time, e.g. when a file is copied.
  2806. * Since the Last-Modified timestamp is used for caching
  2807. * it should be based on the most recent timestamp. */
  2808. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2809. info.ftCreationTime.dwHighDateTime);
  2810. if (creation_time > filep->last_modified) {
  2811. filep->last_modified = creation_time;
  2812. }
  2813. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2814. /* If file name is fishy, reset the file structure and return
  2815. * error.
  2816. * Note it is important to reset, not just return the error, cause
  2817. * functions like is_file_opened() check the struct. */
  2818. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2819. memset(filep, 0, sizeof(*filep));
  2820. return 0;
  2821. }
  2822. return 1;
  2823. }
  2824. return 0;
  2825. }
  2826. static int
  2827. mg_remove(const struct mg_connection *conn, const char *path)
  2828. {
  2829. wchar_t wbuf[PATH_MAX];
  2830. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2831. return DeleteFileW(wbuf) ? 0 : -1;
  2832. }
  2833. static int
  2834. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2835. {
  2836. wchar_t wbuf[PATH_MAX];
  2837. (void)mode;
  2838. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2839. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2840. }
  2841. /* Create substitutes for POSIX functions in Win32. */
  2842. #if defined(__MINGW32__)
  2843. /* Show no warning in case system functions are not used. */
  2844. #pragma GCC diagnostic push
  2845. #pragma GCC diagnostic ignored "-Wunused-function"
  2846. #endif
  2847. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2848. static DIR *
  2849. mg_opendir(const struct mg_connection *conn, const char *name)
  2850. {
  2851. DIR *dir = NULL;
  2852. wchar_t wpath[PATH_MAX];
  2853. DWORD attrs;
  2854. if (name == NULL) {
  2855. SetLastError(ERROR_BAD_ARGUMENTS);
  2856. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2857. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2858. } else {
  2859. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2860. attrs = GetFileAttributesW(wpath);
  2861. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2862. == FILE_ATTRIBUTE_DIRECTORY)) {
  2863. (void)wcscat(wpath, L"\\*");
  2864. dir->handle = FindFirstFileW(wpath, &dir->info);
  2865. dir->result.d_name[0] = '\0';
  2866. } else {
  2867. mg_free(dir);
  2868. dir = NULL;
  2869. }
  2870. }
  2871. return dir;
  2872. }
  2873. static int
  2874. mg_closedir(DIR *dir)
  2875. {
  2876. int result = 0;
  2877. if (dir != NULL) {
  2878. if (dir->handle != INVALID_HANDLE_VALUE)
  2879. result = FindClose(dir->handle) ? 0 : -1;
  2880. mg_free(dir);
  2881. } else {
  2882. result = -1;
  2883. SetLastError(ERROR_BAD_ARGUMENTS);
  2884. }
  2885. return result;
  2886. }
  2887. static struct dirent *
  2888. mg_readdir(DIR *dir)
  2889. {
  2890. struct dirent *result = 0;
  2891. if (dir) {
  2892. if (dir->handle != INVALID_HANDLE_VALUE) {
  2893. result = &dir->result;
  2894. (void)WideCharToMultiByte(CP_UTF8,
  2895. 0,
  2896. dir->info.cFileName,
  2897. -1,
  2898. result->d_name,
  2899. sizeof(result->d_name),
  2900. NULL,
  2901. NULL);
  2902. if (!FindNextFileW(dir->handle, &dir->info)) {
  2903. (void)FindClose(dir->handle);
  2904. dir->handle = INVALID_HANDLE_VALUE;
  2905. }
  2906. } else {
  2907. SetLastError(ERROR_FILE_NOT_FOUND);
  2908. }
  2909. } else {
  2910. SetLastError(ERROR_BAD_ARGUMENTS);
  2911. }
  2912. return result;
  2913. }
  2914. #ifndef HAVE_POLL
  2915. static int
  2916. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2917. {
  2918. struct timeval tv;
  2919. fd_set set;
  2920. unsigned int i;
  2921. int result;
  2922. SOCKET maxfd = 0;
  2923. memset(&tv, 0, sizeof(tv));
  2924. tv.tv_sec = milliseconds / 1000;
  2925. tv.tv_usec = (milliseconds % 1000) * 1000;
  2926. FD_ZERO(&set);
  2927. for (i = 0; i < n; i++) {
  2928. FD_SET((SOCKET)pfd[i].fd, &set);
  2929. pfd[i].revents = 0;
  2930. if (pfd[i].fd > maxfd) {
  2931. maxfd = pfd[i].fd;
  2932. }
  2933. }
  2934. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2935. for (i = 0; i < n; i++) {
  2936. if (FD_ISSET(pfd[i].fd, &set)) {
  2937. pfd[i].revents = POLLIN;
  2938. }
  2939. }
  2940. }
  2941. return result;
  2942. }
  2943. #endif /* HAVE_POLL */
  2944. #if defined(__MINGW32__)
  2945. /* Enable unused function warning again */
  2946. #pragma GCC diagnostic pop
  2947. #endif
  2948. static void
  2949. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2950. {
  2951. (void)conn; /* Unused. */
  2952. #if defined(_WIN32_WCE)
  2953. (void)sock;
  2954. #else
  2955. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2956. #endif
  2957. }
  2958. int
  2959. mg_start_thread(mg_thread_func_t f, void *p)
  2960. {
  2961. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2962. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2963. */
  2964. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2965. == ((uintptr_t)(-1L)))
  2966. ? -1
  2967. : 0);
  2968. #else
  2969. return (
  2970. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2971. ? -1
  2972. : 0);
  2973. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2974. }
  2975. /* Start a thread storing the thread context. */
  2976. static int
  2977. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2978. void *p,
  2979. pthread_t *threadidptr)
  2980. {
  2981. uintptr_t uip;
  2982. HANDLE threadhandle;
  2983. int result = -1;
  2984. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2985. threadhandle = (HANDLE)uip;
  2986. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2987. *threadidptr = threadhandle;
  2988. result = 0;
  2989. }
  2990. return result;
  2991. }
  2992. /* Wait for a thread to finish. */
  2993. static int
  2994. mg_join_thread(pthread_t threadid)
  2995. {
  2996. int result;
  2997. DWORD dwevent;
  2998. result = -1;
  2999. dwevent = WaitForSingleObject(threadid, INFINITE);
  3000. if (dwevent == WAIT_FAILED) {
  3001. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3002. } else {
  3003. if (dwevent == WAIT_OBJECT_0) {
  3004. CloseHandle(threadid);
  3005. result = 0;
  3006. }
  3007. }
  3008. return result;
  3009. }
  3010. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3011. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3012. /* Create substitutes for POSIX functions in Win32. */
  3013. #if defined(__MINGW32__)
  3014. /* Show no warning in case system functions are not used. */
  3015. #pragma GCC diagnostic push
  3016. #pragma GCC diagnostic ignored "-Wunused-function"
  3017. #endif
  3018. static HANDLE
  3019. dlopen(const char *dll_name, int flags)
  3020. {
  3021. wchar_t wbuf[PATH_MAX];
  3022. (void)flags;
  3023. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3024. return LoadLibraryW(wbuf);
  3025. }
  3026. static int
  3027. dlclose(void *handle)
  3028. {
  3029. int result;
  3030. if (FreeLibrary((HMODULE)handle) != 0) {
  3031. result = 0;
  3032. } else {
  3033. result = -1;
  3034. }
  3035. return result;
  3036. }
  3037. #if defined(__MINGW32__)
  3038. /* Enable unused function warning again */
  3039. #pragma GCC diagnostic pop
  3040. #endif
  3041. #endif
  3042. #if !defined(NO_CGI)
  3043. #define SIGKILL (0)
  3044. static int
  3045. kill(pid_t pid, int sig_num)
  3046. {
  3047. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3048. (void)CloseHandle((HANDLE)pid);
  3049. return 0;
  3050. }
  3051. static void
  3052. trim_trailing_whitespaces(char *s)
  3053. {
  3054. char *e = s + strlen(s) - 1;
  3055. while (e > s && isspace(*(unsigned char *)e)) {
  3056. *e-- = '\0';
  3057. }
  3058. }
  3059. static pid_t
  3060. spawn_process(struct mg_connection *conn,
  3061. const char *prog,
  3062. char *envblk,
  3063. char *envp[],
  3064. int fdin[2],
  3065. int fdout[2],
  3066. int fderr[2],
  3067. const char *dir)
  3068. {
  3069. HANDLE me;
  3070. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3071. cmdline[PATH_MAX], buf[PATH_MAX];
  3072. int truncated;
  3073. struct file file = STRUCT_FILE_INITIALIZER;
  3074. STARTUPINFOA si;
  3075. PROCESS_INFORMATION pi = {0};
  3076. (void)envp;
  3077. memset(&si, 0, sizeof(si));
  3078. si.cb = sizeof(si);
  3079. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3080. si.wShowWindow = SW_HIDE;
  3081. me = GetCurrentProcess();
  3082. DuplicateHandle(me,
  3083. (HANDLE)_get_osfhandle(fdin[0]),
  3084. me,
  3085. &si.hStdInput,
  3086. 0,
  3087. TRUE,
  3088. DUPLICATE_SAME_ACCESS);
  3089. DuplicateHandle(me,
  3090. (HANDLE)_get_osfhandle(fdout[1]),
  3091. me,
  3092. &si.hStdOutput,
  3093. 0,
  3094. TRUE,
  3095. DUPLICATE_SAME_ACCESS);
  3096. DuplicateHandle(me,
  3097. (HANDLE)_get_osfhandle(fderr[1]),
  3098. me,
  3099. &si.hStdError,
  3100. 0,
  3101. TRUE,
  3102. DUPLICATE_SAME_ACCESS);
  3103. /* Mark handles that should not be inherited. See
  3104. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3105. */
  3106. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3107. HANDLE_FLAG_INHERIT,
  3108. 0);
  3109. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3110. HANDLE_FLAG_INHERIT,
  3111. 0);
  3112. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3113. HANDLE_FLAG_INHERIT,
  3114. 0);
  3115. /* If CGI file is a script, try to read the interpreter line */
  3116. interp = conn->ctx->config[CGI_INTERPRETER];
  3117. if (interp == NULL) {
  3118. buf[0] = buf[1] = '\0';
  3119. /* Read the first line of the script into the buffer */
  3120. mg_snprintf(
  3121. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3122. if (truncated) {
  3123. pi.hProcess = (pid_t)-1;
  3124. goto spawn_cleanup;
  3125. }
  3126. if (mg_fopen(conn, cmdline, "r", &file)) {
  3127. p = (char *)file.membuf;
  3128. mg_fgets(buf, sizeof(buf), &file, &p);
  3129. mg_fclose(&file);
  3130. buf[sizeof(buf) - 1] = '\0';
  3131. }
  3132. if (buf[0] == '#' && buf[1] == '!') {
  3133. trim_trailing_whitespaces(buf + 2);
  3134. } else {
  3135. buf[2] = '\0';
  3136. }
  3137. interp = buf + 2;
  3138. }
  3139. if (interp[0] != '\0') {
  3140. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3141. interp = full_interp;
  3142. }
  3143. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3144. if (interp[0] != '\0') {
  3145. mg_snprintf(conn,
  3146. &truncated,
  3147. cmdline,
  3148. sizeof(cmdline),
  3149. "\"%s\" \"%s\\%s\"",
  3150. interp,
  3151. full_dir,
  3152. prog);
  3153. } else {
  3154. mg_snprintf(conn,
  3155. &truncated,
  3156. cmdline,
  3157. sizeof(cmdline),
  3158. "\"%s\\%s\"",
  3159. full_dir,
  3160. prog);
  3161. }
  3162. if (truncated) {
  3163. pi.hProcess = (pid_t)-1;
  3164. goto spawn_cleanup;
  3165. }
  3166. DEBUG_TRACE("Running [%s]", cmdline);
  3167. if (CreateProcessA(NULL,
  3168. cmdline,
  3169. NULL,
  3170. NULL,
  3171. TRUE,
  3172. CREATE_NEW_PROCESS_GROUP,
  3173. envblk,
  3174. NULL,
  3175. &si,
  3176. &pi) == 0) {
  3177. mg_cry(
  3178. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3179. pi.hProcess = (pid_t)-1;
  3180. /* goto spawn_cleanup; */
  3181. }
  3182. spawn_cleanup:
  3183. (void)CloseHandle(si.hStdOutput);
  3184. (void)CloseHandle(si.hStdError);
  3185. (void)CloseHandle(si.hStdInput);
  3186. if (pi.hThread != NULL) {
  3187. (void)CloseHandle(pi.hThread);
  3188. }
  3189. return (pid_t)pi.hProcess;
  3190. }
  3191. #endif /* !NO_CGI */
  3192. static int
  3193. set_non_blocking_mode(SOCKET sock)
  3194. {
  3195. unsigned long on = 1;
  3196. return ioctlsocket(sock, (long)FIONBIO, &on);
  3197. }
  3198. #else
  3199. static int
  3200. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3201. {
  3202. struct stat st;
  3203. if (!filep) {
  3204. return 0;
  3205. }
  3206. memset(filep, 0, sizeof(*filep));
  3207. if (conn && is_file_in_memory(conn, path, filep)) {
  3208. return 1;
  3209. }
  3210. if (0 == stat(path, &st)) {
  3211. filep->size = (uint64_t)(st.st_size);
  3212. filep->last_modified = st.st_mtime;
  3213. filep->is_directory = S_ISDIR(st.st_mode);
  3214. return 1;
  3215. }
  3216. return 0;
  3217. }
  3218. static void
  3219. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3220. {
  3221. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3222. if (conn) {
  3223. mg_cry(conn,
  3224. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3225. __func__,
  3226. strerror(ERRNO));
  3227. }
  3228. }
  3229. }
  3230. int
  3231. mg_start_thread(mg_thread_func_t func, void *param)
  3232. {
  3233. pthread_t thread_id;
  3234. pthread_attr_t attr;
  3235. int result;
  3236. (void)pthread_attr_init(&attr);
  3237. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3238. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3239. /* Compile-time option to control stack size,
  3240. * e.g. -DUSE_STACK_SIZE=16384 */
  3241. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3242. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3243. result = pthread_create(&thread_id, &attr, func, param);
  3244. pthread_attr_destroy(&attr);
  3245. return result;
  3246. }
  3247. /* Start a thread storing the thread context. */
  3248. static int
  3249. mg_start_thread_with_id(mg_thread_func_t func,
  3250. void *param,
  3251. pthread_t *threadidptr)
  3252. {
  3253. pthread_t thread_id;
  3254. pthread_attr_t attr;
  3255. int result;
  3256. (void)pthread_attr_init(&attr);
  3257. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3258. /* Compile-time option to control stack size,
  3259. * e.g. -DUSE_STACK_SIZE=16384 */
  3260. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3261. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3262. result = pthread_create(&thread_id, &attr, func, param);
  3263. pthread_attr_destroy(&attr);
  3264. if ((result == 0) && (threadidptr != NULL)) {
  3265. *threadidptr = thread_id;
  3266. }
  3267. return result;
  3268. }
  3269. /* Wait for a thread to finish. */
  3270. static int
  3271. mg_join_thread(pthread_t threadid)
  3272. {
  3273. int result;
  3274. result = pthread_join(threadid, NULL);
  3275. return result;
  3276. }
  3277. #ifndef NO_CGI
  3278. static pid_t
  3279. spawn_process(struct mg_connection *conn,
  3280. const char *prog,
  3281. char *envblk,
  3282. char *envp[],
  3283. int fdin[2],
  3284. int fdout[2],
  3285. int fderr[2],
  3286. const char *dir)
  3287. {
  3288. pid_t pid;
  3289. const char *interp;
  3290. (void)envblk;
  3291. if (conn == NULL) {
  3292. return 0;
  3293. }
  3294. if ((pid = fork()) == -1) {
  3295. /* Parent */
  3296. send_http_error(conn,
  3297. 500,
  3298. "Error: Creating CGI process\nfork(): %s",
  3299. strerror(ERRNO));
  3300. } else if (pid == 0) {
  3301. /* Child */
  3302. if (chdir(dir) != 0) {
  3303. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3304. } else if (dup2(fdin[0], 0) == -1) {
  3305. mg_cry(conn,
  3306. "%s: dup2(%d, 0): %s",
  3307. __func__,
  3308. fdin[0],
  3309. strerror(ERRNO));
  3310. } else if (dup2(fdout[1], 1) == -1) {
  3311. mg_cry(conn,
  3312. "%s: dup2(%d, 1): %s",
  3313. __func__,
  3314. fdout[1],
  3315. strerror(ERRNO));
  3316. } else if (dup2(fderr[1], 2) == -1) {
  3317. mg_cry(conn,
  3318. "%s: dup2(%d, 2): %s",
  3319. __func__,
  3320. fderr[1],
  3321. strerror(ERRNO));
  3322. } else {
  3323. /* Keep stderr and stdout in two different pipes.
  3324. * Stdout will be sent back to the client,
  3325. * stderr should go into a server error log. */
  3326. (void)close(fdin[0]);
  3327. (void)close(fdout[1]);
  3328. (void)close(fderr[1]);
  3329. /* Close write end fdin and read end fdout and fderr */
  3330. (void)close(fdin[1]);
  3331. (void)close(fdout[0]);
  3332. (void)close(fderr[0]);
  3333. /* After exec, all signal handlers are restored to their default
  3334. * values, with one exception of SIGCHLD. According to
  3335. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3336. * leave unchanged after exec if it was set to be ignored. Restore
  3337. * it to default action. */
  3338. signal(SIGCHLD, SIG_DFL);
  3339. interp = conn->ctx->config[CGI_INTERPRETER];
  3340. if (interp == NULL) {
  3341. (void)execle(prog, prog, NULL, envp);
  3342. mg_cry(conn,
  3343. "%s: execle(%s): %s",
  3344. __func__,
  3345. prog,
  3346. strerror(ERRNO));
  3347. } else {
  3348. (void)execle(interp, interp, prog, NULL, envp);
  3349. mg_cry(conn,
  3350. "%s: execle(%s %s): %s",
  3351. __func__,
  3352. interp,
  3353. prog,
  3354. strerror(ERRNO));
  3355. }
  3356. }
  3357. exit(EXIT_FAILURE);
  3358. }
  3359. return pid;
  3360. }
  3361. #endif /* !NO_CGI */
  3362. static int
  3363. set_non_blocking_mode(SOCKET sock)
  3364. {
  3365. int flags;
  3366. flags = fcntl(sock, F_GETFL, 0);
  3367. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3368. return 0;
  3369. }
  3370. #endif /* _WIN32 */
  3371. /* End of initial operating system specific define block. */
  3372. /* Get a random number (independent of C rand function) */
  3373. static uint64_t
  3374. get_random(void)
  3375. {
  3376. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3377. static uint64_t lcg = 0; /* Linear congruential generator */
  3378. struct timespec now;
  3379. memset(&now, 0, sizeof(now));
  3380. clock_gettime(CLOCK_MONOTONIC, &now);
  3381. if (lfsr == 0) {
  3382. /* lfsr will be only 0 if has not been initialized,
  3383. * so this code is called only once. */
  3384. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3385. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3386. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3387. + (uint64_t)(ptrdiff_t)&now;
  3388. } else {
  3389. /* Get the next step of both random number generators. */
  3390. lfsr = (lfsr >> 1)
  3391. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3392. << 63);
  3393. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3394. }
  3395. /* Combining two pseudo-random number generators and a high resolution part
  3396. * of the current server time will make it hard (impossible?) to guess the
  3397. * next number. */
  3398. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3399. }
  3400. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3401. * descriptor. Return number of bytes written. */
  3402. static int
  3403. push(struct mg_context *ctx,
  3404. FILE *fp,
  3405. SOCKET sock,
  3406. SSL *ssl,
  3407. const char *buf,
  3408. int len,
  3409. double timeout)
  3410. {
  3411. struct timespec start, now;
  3412. int n, err;
  3413. #ifdef _WIN32
  3414. typedef int len_t;
  3415. #else
  3416. typedef size_t len_t;
  3417. #endif
  3418. if (timeout > 0) {
  3419. memset(&start, 0, sizeof(start));
  3420. memset(&now, 0, sizeof(now));
  3421. clock_gettime(CLOCK_MONOTONIC, &start);
  3422. }
  3423. if (ctx == NULL) {
  3424. return -1;
  3425. }
  3426. #ifdef NO_SSL
  3427. if (ssl) {
  3428. return -1;
  3429. }
  3430. #endif
  3431. do {
  3432. #ifndef NO_SSL
  3433. if (ssl != NULL) {
  3434. n = SSL_write(ssl, buf, len);
  3435. if (n <= 0) {
  3436. err = SSL_get_error(ssl, n);
  3437. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3438. err = ERRNO;
  3439. } else if ((err == SSL_ERROR_WANT_READ)
  3440. || (err == SSL_ERROR_WANT_WRITE)) {
  3441. n = 0;
  3442. } else {
  3443. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3444. return -1;
  3445. }
  3446. } else {
  3447. err = 0;
  3448. }
  3449. } else
  3450. #endif
  3451. if (fp != NULL) {
  3452. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3453. if (ferror(fp)) {
  3454. n = -1;
  3455. err = ERRNO;
  3456. } else {
  3457. err = 0;
  3458. }
  3459. } else {
  3460. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3461. err = (n < 0) ? ERRNO : 0;
  3462. if (n == 0) {
  3463. /* shutdown of the socket at client side */
  3464. return -1;
  3465. }
  3466. }
  3467. if (ctx->stop_flag) {
  3468. return -1;
  3469. }
  3470. if ((n > 0) || (n == 0 && len == 0)) {
  3471. /* some data has been read, or no data was requested */
  3472. return n;
  3473. }
  3474. if (n < 0) {
  3475. /* socket error - check errno */
  3476. DEBUG_TRACE("send() failed, error %d", err);
  3477. /* TODO: error handling depending on the error code.
  3478. * These codes are different between Windows and Linux.
  3479. */
  3480. return -1;
  3481. }
  3482. /* This code is not reached in the moment.
  3483. * ==> Fix the TODOs above first. */
  3484. if (timeout > 0) {
  3485. clock_gettime(CLOCK_MONOTONIC, &now);
  3486. }
  3487. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3488. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3489. used */
  3490. return -1;
  3491. }
  3492. static int64_t
  3493. push_all(struct mg_context *ctx,
  3494. FILE *fp,
  3495. SOCKET sock,
  3496. SSL *ssl,
  3497. const char *buf,
  3498. int64_t len)
  3499. {
  3500. double timeout = -1.0;
  3501. int64_t n, nwritten = 0;
  3502. if (ctx == NULL) {
  3503. return -1;
  3504. }
  3505. if (ctx->config[REQUEST_TIMEOUT]) {
  3506. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3507. }
  3508. while (len > 0 && ctx->stop_flag == 0) {
  3509. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3510. if (n < 0) {
  3511. if (nwritten == 0) {
  3512. nwritten = n; /* Propagate the error */
  3513. }
  3514. break;
  3515. } else if (n == 0) {
  3516. break; /* No more data to write */
  3517. } else {
  3518. nwritten += n;
  3519. len -= n;
  3520. }
  3521. }
  3522. return nwritten;
  3523. }
  3524. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3525. * Return negative value on error, or number of bytes read on success. */
  3526. static int
  3527. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3528. {
  3529. int nread, err;
  3530. struct timespec start, now;
  3531. #ifdef _WIN32
  3532. typedef int len_t;
  3533. #else
  3534. typedef size_t len_t;
  3535. #endif
  3536. if (timeout > 0) {
  3537. memset(&start, 0, sizeof(start));
  3538. memset(&now, 0, sizeof(now));
  3539. clock_gettime(CLOCK_MONOTONIC, &start);
  3540. }
  3541. do {
  3542. if (fp != NULL) {
  3543. #if !defined(_WIN32_WCE)
  3544. /* Use read() instead of fread(), because if we're reading from the
  3545. * CGI pipe, fread() may block until IO buffer is filled up. We
  3546. * cannot afford to block and must pass all read bytes immediately
  3547. * to the client. */
  3548. nread = (int)read(fileno(fp), buf, (size_t)len);
  3549. #else
  3550. /* WinCE does not support CGI pipes */
  3551. nread = (int)fread(buf, 1, (size_t)len, fp);
  3552. #endif
  3553. err = (nread < 0) ? ERRNO : 0;
  3554. #ifndef NO_SSL
  3555. } else if (conn->ssl != NULL) {
  3556. nread = SSL_read(conn->ssl, buf, len);
  3557. if (nread <= 0) {
  3558. err = SSL_get_error(conn->ssl, nread);
  3559. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3560. err = ERRNO;
  3561. } else if ((err == SSL_ERROR_WANT_READ)
  3562. || (err == SSL_ERROR_WANT_WRITE)) {
  3563. nread = 0;
  3564. } else {
  3565. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3566. return -1;
  3567. }
  3568. } else {
  3569. err = 0;
  3570. }
  3571. #endif
  3572. } else {
  3573. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3574. err = (nread < 0) ? ERRNO : 0;
  3575. if (nread == 0) {
  3576. /* shutdown of the socket at client side */
  3577. return -1;
  3578. }
  3579. }
  3580. if (conn->ctx->stop_flag) {
  3581. return -1;
  3582. }
  3583. if ((nread > 0) || (nread == 0 && len == 0)) {
  3584. /* some data has been read, or no data was requested */
  3585. return nread;
  3586. }
  3587. if (nread < 0) {
  3588. /* socket error - check errno */
  3589. #ifdef _WIN32
  3590. if (err == WSAEWOULDBLOCK) {
  3591. /* standard case if called from close_socket_gracefully */
  3592. return -1;
  3593. } else if (err == WSAETIMEDOUT) {
  3594. /* timeout is handled by the while loop */
  3595. } else {
  3596. DEBUG_TRACE("recv() failed, error %d", err);
  3597. return -1;
  3598. }
  3599. #else
  3600. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3601. * if the timeout is reached and if the socket was set to non-
  3602. * blocking in close_socket_gracefully, so we can not distinguish
  3603. * here. We have to wait for the timeout in both cases for now.
  3604. */
  3605. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3606. /* EAGAIN/EWOULDBLOCK:
  3607. * standard case if called from close_socket_gracefully
  3608. * => should return -1 */
  3609. /* or timeout occured
  3610. * => the code must stay in the while loop */
  3611. /* EINTR can be generated on a socket with a timeout set even
  3612. * when SA_RESTART is effective for all relevant signals
  3613. * (see signal(7)).
  3614. * => stay in the while loop */
  3615. } else {
  3616. DEBUG_TRACE("recv() failed, error %d", err);
  3617. return -1;
  3618. }
  3619. #endif
  3620. }
  3621. if (timeout > 0) {
  3622. clock_gettime(CLOCK_MONOTONIC, &now);
  3623. }
  3624. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3625. /* Timeout occured, but no data available. */
  3626. return -1;
  3627. }
  3628. static int
  3629. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3630. {
  3631. int n, nread = 0;
  3632. double timeout = -1.0;
  3633. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3634. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3635. }
  3636. while (len > 0 && conn->ctx->stop_flag == 0) {
  3637. n = pull(fp, conn, buf + nread, len, timeout);
  3638. if (n < 0) {
  3639. if (nread == 0) {
  3640. nread = n; /* Propagate the error */
  3641. }
  3642. break;
  3643. } else if (n == 0) {
  3644. break; /* No more data to read */
  3645. } else {
  3646. conn->consumed_content += n;
  3647. nread += n;
  3648. len -= n;
  3649. }
  3650. }
  3651. return nread;
  3652. }
  3653. static void
  3654. discard_unread_request_data(struct mg_connection *conn)
  3655. {
  3656. char buf[MG_BUF_LEN];
  3657. size_t to_read;
  3658. int nread;
  3659. if (conn == NULL) {
  3660. return;
  3661. }
  3662. to_read = sizeof(buf);
  3663. if (conn->is_chunked) {
  3664. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3665. * completely */
  3666. while (conn->is_chunked == 1) {
  3667. nread = mg_read(conn, buf, to_read);
  3668. if (nread <= 0) {
  3669. break;
  3670. }
  3671. }
  3672. } else {
  3673. /* Not chunked: content length is known */
  3674. while (conn->consumed_content < conn->content_len) {
  3675. if (to_read
  3676. > (size_t)(conn->content_len - conn->consumed_content)) {
  3677. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3678. }
  3679. nread = mg_read(conn, buf, to_read);
  3680. if (nread <= 0) {
  3681. break;
  3682. }
  3683. }
  3684. }
  3685. }
  3686. static int
  3687. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3688. {
  3689. int64_t n, buffered_len, nread;
  3690. int64_t len64 =
  3691. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3692. * int, we may not read more
  3693. * bytes */
  3694. const char *body;
  3695. if (conn == NULL) {
  3696. return 0;
  3697. }
  3698. /* If Content-Length is not set for a PUT or POST request, read until
  3699. * socket is closed */
  3700. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3701. conn->content_len = INT64_MAX;
  3702. conn->must_close = 1;
  3703. }
  3704. nread = 0;
  3705. if (conn->consumed_content < conn->content_len) {
  3706. /* Adjust number of bytes to read. */
  3707. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3708. if (left_to_read < len64) {
  3709. /* Do not read more than the total content length of the request.
  3710. */
  3711. len64 = left_to_read;
  3712. }
  3713. /* Return buffered data */
  3714. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3715. - conn->consumed_content;
  3716. if (buffered_len > 0) {
  3717. if (len64 < buffered_len) {
  3718. buffered_len = len64;
  3719. }
  3720. body = conn->buf + conn->request_len + conn->consumed_content;
  3721. memcpy(buf, body, (size_t)buffered_len);
  3722. len64 -= buffered_len;
  3723. conn->consumed_content += buffered_len;
  3724. nread += buffered_len;
  3725. buf = (char *)buf + buffered_len;
  3726. }
  3727. /* We have returned all buffered data. Read new data from the remote
  3728. * socket.
  3729. */
  3730. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3731. nread += n;
  3732. } else {
  3733. nread = ((nread > 0) ? nread : n);
  3734. }
  3735. }
  3736. return (int)nread;
  3737. }
  3738. static char
  3739. mg_getc(struct mg_connection *conn)
  3740. {
  3741. char c;
  3742. if (conn == NULL) {
  3743. return 0;
  3744. }
  3745. conn->content_len++;
  3746. if (mg_read_inner(conn, &c, 1) <= 0) {
  3747. return (char)0;
  3748. }
  3749. return c;
  3750. }
  3751. int
  3752. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3753. {
  3754. if (len > INT_MAX) {
  3755. len = INT_MAX;
  3756. }
  3757. if (conn == NULL) {
  3758. return 0;
  3759. }
  3760. if (conn->is_chunked) {
  3761. size_t all_read = 0;
  3762. while (len > 0) {
  3763. if (conn->is_chunked == 2) {
  3764. /* No more data left to read */
  3765. return 0;
  3766. }
  3767. if (conn->chunk_remainder) {
  3768. /* copy from the remainder of the last received chunk */
  3769. long read_ret;
  3770. size_t read_now =
  3771. ((conn->chunk_remainder > len) ? (len)
  3772. : (conn->chunk_remainder));
  3773. conn->content_len += (int)read_now;
  3774. read_ret =
  3775. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3776. all_read += (size_t)read_ret;
  3777. conn->chunk_remainder -= read_now;
  3778. len -= read_now;
  3779. if (conn->chunk_remainder == 0) {
  3780. /* the rest of the data in the current chunk has been read
  3781. */
  3782. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3783. /* Protocol violation */
  3784. return -1;
  3785. }
  3786. }
  3787. } else {
  3788. /* fetch a new chunk */
  3789. int i = 0;
  3790. char lenbuf[64];
  3791. char *end = 0;
  3792. unsigned long chunkSize = 0;
  3793. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3794. lenbuf[i] = mg_getc(conn);
  3795. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3796. continue;
  3797. }
  3798. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3799. lenbuf[i + 1] = 0;
  3800. chunkSize = strtoul(lenbuf, &end, 16);
  3801. if (chunkSize == 0) {
  3802. /* regular end of content */
  3803. conn->is_chunked = 2;
  3804. }
  3805. break;
  3806. }
  3807. if (!isalnum(lenbuf[i])) {
  3808. /* illegal character for chunk length */
  3809. return -1;
  3810. }
  3811. }
  3812. if ((end == NULL) || (*end != '\r')) {
  3813. /* chunksize not set correctly */
  3814. return -1;
  3815. }
  3816. if (chunkSize == 0) {
  3817. break;
  3818. }
  3819. conn->chunk_remainder = chunkSize;
  3820. }
  3821. }
  3822. return (int)all_read;
  3823. }
  3824. return mg_read_inner(conn, buf, len);
  3825. }
  3826. int
  3827. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3828. {
  3829. time_t now;
  3830. int64_t n, total, allowed;
  3831. if (conn == NULL) {
  3832. return 0;
  3833. }
  3834. if (conn->throttle > 0) {
  3835. if ((now = time(NULL)) != conn->last_throttle_time) {
  3836. conn->last_throttle_time = now;
  3837. conn->last_throttle_bytes = 0;
  3838. }
  3839. allowed = conn->throttle - conn->last_throttle_bytes;
  3840. if (allowed > (int64_t)len) {
  3841. allowed = (int64_t)len;
  3842. }
  3843. if ((total = push_all(conn->ctx,
  3844. NULL,
  3845. conn->client.sock,
  3846. conn->ssl,
  3847. (const char *)buf,
  3848. (int64_t)allowed)) == allowed) {
  3849. buf = (const char *)buf + total;
  3850. conn->last_throttle_bytes += total;
  3851. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3852. allowed = (conn->throttle > ((int64_t)len - total))
  3853. ? (int64_t)len - total
  3854. : conn->throttle;
  3855. if ((n = push_all(conn->ctx,
  3856. NULL,
  3857. conn->client.sock,
  3858. conn->ssl,
  3859. (const char *)buf,
  3860. (int64_t)allowed)) != allowed) {
  3861. break;
  3862. }
  3863. sleep(1);
  3864. conn->last_throttle_bytes = allowed;
  3865. conn->last_throttle_time = time(NULL);
  3866. buf = (const char *)buf + n;
  3867. total += n;
  3868. }
  3869. }
  3870. } else {
  3871. total = push_all(conn->ctx,
  3872. NULL,
  3873. conn->client.sock,
  3874. conn->ssl,
  3875. (const char *)buf,
  3876. (int64_t)len);
  3877. }
  3878. return (int)total;
  3879. }
  3880. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3881. static int
  3882. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3883. {
  3884. va_list ap_copy;
  3885. size_t size = MG_BUF_LEN / 4;
  3886. int len = -1;
  3887. *buf = NULL;
  3888. while (len < 0) {
  3889. if (*buf) {
  3890. mg_free(*buf);
  3891. }
  3892. size *= 4;
  3893. *buf = (char *)mg_malloc(size);
  3894. if (!*buf) {
  3895. break;
  3896. }
  3897. va_copy(ap_copy, ap);
  3898. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3899. va_end(ap_copy);
  3900. (*buf)[size - 1] = 0;
  3901. }
  3902. return len;
  3903. }
  3904. /* Print message to buffer. If buffer is large enough to hold the message,
  3905. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3906. * and return allocated buffer. */
  3907. static int
  3908. alloc_vprintf(char **out_buf,
  3909. char *prealloc_buf,
  3910. size_t prealloc_size,
  3911. const char *fmt,
  3912. va_list ap)
  3913. {
  3914. va_list ap_copy;
  3915. int len;
  3916. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3917. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3918. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3919. * Therefore, we make two passes: on first pass, get required message
  3920. * length.
  3921. * On second pass, actually print the message. */
  3922. va_copy(ap_copy, ap);
  3923. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3924. va_end(ap_copy);
  3925. if (len < 0) {
  3926. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3927. * Switch to alternative code path that uses incremental allocations.
  3928. */
  3929. va_copy(ap_copy, ap);
  3930. len = alloc_vprintf2(out_buf, fmt, ap);
  3931. va_end(ap_copy);
  3932. } else if ((size_t)(len) >= prealloc_size) {
  3933. /* The pre-allocated buffer not large enough. */
  3934. /* Allocate a new buffer. */
  3935. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3936. if (!*out_buf) {
  3937. /* Allocation failed. Return -1 as "out of memory" error. */
  3938. return -1;
  3939. }
  3940. /* Buffer allocation successful. Store the string there. */
  3941. va_copy(ap_copy, ap);
  3942. IGNORE_UNUSED_RESULT(
  3943. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3944. va_end(ap_copy);
  3945. } else {
  3946. /* The pre-allocated buffer is large enough.
  3947. * Use it to store the string and return the address. */
  3948. va_copy(ap_copy, ap);
  3949. IGNORE_UNUSED_RESULT(
  3950. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3951. va_end(ap_copy);
  3952. *out_buf = prealloc_buf;
  3953. }
  3954. return len;
  3955. }
  3956. static int
  3957. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3958. {
  3959. char mem[MG_BUF_LEN];
  3960. char *buf = NULL;
  3961. int len;
  3962. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3963. len = mg_write(conn, buf, (size_t)len);
  3964. }
  3965. if (buf != mem && buf != NULL) {
  3966. mg_free(buf);
  3967. }
  3968. return len;
  3969. }
  3970. int
  3971. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3972. {
  3973. va_list ap;
  3974. int result;
  3975. va_start(ap, fmt);
  3976. result = mg_vprintf(conn, fmt, ap);
  3977. va_end(ap);
  3978. return result;
  3979. }
  3980. int
  3981. mg_url_decode(const char *src,
  3982. int src_len,
  3983. char *dst,
  3984. int dst_len,
  3985. int is_form_url_encoded)
  3986. {
  3987. int i, j, a, b;
  3988. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  3989. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  3990. if (i < src_len - 2 && src[i] == '%'
  3991. && isxdigit(*(const unsigned char *)(src + i + 1))
  3992. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3993. a = tolower(*(const unsigned char *)(src + i + 1));
  3994. b = tolower(*(const unsigned char *)(src + i + 2));
  3995. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3996. i += 2;
  3997. } else if (is_form_url_encoded && src[i] == '+') {
  3998. dst[j] = ' ';
  3999. } else {
  4000. dst[j] = src[i];
  4001. }
  4002. }
  4003. dst[j] = '\0'; /* Null-terminate the destination */
  4004. return (i >= src_len) ? j : -1;
  4005. }
  4006. int
  4007. mg_get_var(const char *data,
  4008. size_t data_len,
  4009. const char *name,
  4010. char *dst,
  4011. size_t dst_len)
  4012. {
  4013. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4014. }
  4015. int
  4016. mg_get_var2(const char *data,
  4017. size_t data_len,
  4018. const char *name,
  4019. char *dst,
  4020. size_t dst_len,
  4021. size_t occurrence)
  4022. {
  4023. const char *p, *e, *s;
  4024. size_t name_len;
  4025. int len;
  4026. if (dst == NULL || dst_len == 0) {
  4027. len = -2;
  4028. } else if (data == NULL || name == NULL || data_len == 0) {
  4029. len = -1;
  4030. dst[0] = '\0';
  4031. } else {
  4032. name_len = strlen(name);
  4033. e = data + data_len;
  4034. len = -1;
  4035. dst[0] = '\0';
  4036. /* data is "var1=val1&var2=val2...". Find variable first */
  4037. for (p = data; p + name_len < e; p++) {
  4038. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4039. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4040. /* Point p to variable value */
  4041. p += name_len + 1;
  4042. /* Point s to the end of the value */
  4043. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4044. if (s == NULL) {
  4045. s = e;
  4046. }
  4047. /* assert(s >= p); */
  4048. if (s < p) {
  4049. return -3;
  4050. }
  4051. /* Decode variable into destination buffer */
  4052. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4053. /* Redirect error code from -1 to -2 (destination buffer too
  4054. * small). */
  4055. if (len == -1) {
  4056. len = -2;
  4057. }
  4058. break;
  4059. }
  4060. }
  4061. }
  4062. return len;
  4063. }
  4064. int
  4065. mg_get_cookie(const char *cookie_header,
  4066. const char *var_name,
  4067. char *dst,
  4068. size_t dst_size)
  4069. {
  4070. const char *s, *p, *end;
  4071. int name_len, len = -1;
  4072. if (dst == NULL || dst_size == 0) {
  4073. len = -2;
  4074. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  4075. len = -1;
  4076. dst[0] = '\0';
  4077. } else {
  4078. name_len = (int)strlen(var_name);
  4079. end = s + strlen(s);
  4080. dst[0] = '\0';
  4081. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4082. if (s[name_len] == '=') {
  4083. s += name_len + 1;
  4084. if ((p = strchr(s, ' ')) == NULL) {
  4085. p = end;
  4086. }
  4087. if (p[-1] == ';') {
  4088. p--;
  4089. }
  4090. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4091. s++;
  4092. p--;
  4093. }
  4094. if ((size_t)(p - s) < dst_size) {
  4095. len = (int)(p - s);
  4096. mg_strlcpy(dst, s, (size_t)len + 1);
  4097. } else {
  4098. len = -3;
  4099. }
  4100. break;
  4101. }
  4102. }
  4103. }
  4104. return len;
  4105. }
  4106. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4107. static void
  4108. base64_encode(const unsigned char *src, int src_len, char *dst)
  4109. {
  4110. static const char *b64 =
  4111. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4112. int i, j, a, b, c;
  4113. for (i = j = 0; i < src_len; i += 3) {
  4114. a = src[i];
  4115. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4116. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4117. dst[j++] = b64[a >> 2];
  4118. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4119. if (i + 1 < src_len) {
  4120. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4121. }
  4122. if (i + 2 < src_len) {
  4123. dst[j++] = b64[c & 63];
  4124. }
  4125. }
  4126. while (j % 4 != 0) {
  4127. dst[j++] = '=';
  4128. }
  4129. dst[j++] = '\0';
  4130. }
  4131. #endif
  4132. #if defined(USE_LUA)
  4133. static unsigned char
  4134. b64reverse(char letter)
  4135. {
  4136. if (letter >= 'A' && letter <= 'Z') {
  4137. return letter - 'A';
  4138. }
  4139. if (letter >= 'a' && letter <= 'z') {
  4140. return letter - 'a' + 26;
  4141. }
  4142. if (letter >= '0' && letter <= '9') {
  4143. return letter - '0' + 52;
  4144. }
  4145. if (letter == '+') {
  4146. return 62;
  4147. }
  4148. if (letter == '/') {
  4149. return 63;
  4150. }
  4151. if (letter == '=') {
  4152. return 255; /* normal end */
  4153. }
  4154. return 254; /* error */
  4155. }
  4156. static int
  4157. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4158. {
  4159. int i;
  4160. unsigned char a, b, c, d;
  4161. *dst_len = 0;
  4162. for (i = 0; i < src_len; i += 4) {
  4163. a = b64reverse(src[i]);
  4164. if (a >= 254) {
  4165. return i;
  4166. }
  4167. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4168. if (b >= 254) {
  4169. return i + 1;
  4170. }
  4171. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4172. if (c == 254) {
  4173. return i + 2;
  4174. }
  4175. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4176. if (d == 254) {
  4177. return i + 3;
  4178. }
  4179. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4180. if (c != 255) {
  4181. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4182. if (d != 255) {
  4183. dst[(*dst_len)++] = (c << 6) + d;
  4184. }
  4185. }
  4186. }
  4187. return -1;
  4188. }
  4189. #endif
  4190. static int
  4191. is_put_or_delete_method(const struct mg_connection *conn)
  4192. {
  4193. if (conn) {
  4194. const char *s = conn->request_info.request_method;
  4195. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4196. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4197. }
  4198. return 0;
  4199. }
  4200. static void
  4201. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4202. char *filename, /* out: filename */
  4203. size_t filename_buf_len, /* in: size of filename buffer */
  4204. struct file *filep, /* out: file structure */
  4205. int *is_found, /* out: file is found (directly) */
  4206. int *is_script_resource, /* out: handled by a script? */
  4207. int *is_websocket_request, /* out: websocket connetion? */
  4208. int *is_put_or_delete_request /* out: put/delete a file? */
  4209. )
  4210. {
  4211. /* TODO (high): Restructure this function */
  4212. #if !defined(NO_FILES)
  4213. const char *uri = conn->request_info.local_uri;
  4214. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4215. const char *rewrite;
  4216. struct vec a, b;
  4217. int match_len;
  4218. char gz_path[PATH_MAX];
  4219. char const *accept_encoding;
  4220. int truncated;
  4221. #if !defined(NO_CGI) || defined(USE_LUA)
  4222. char *p;
  4223. #endif
  4224. #else
  4225. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4226. #endif
  4227. memset(filep, 0, sizeof(*filep));
  4228. *filename = 0;
  4229. *is_found = 0;
  4230. *is_script_resource = 0;
  4231. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4232. #if defined(USE_WEBSOCKET)
  4233. *is_websocket_request = is_websocket_protocol(conn);
  4234. #if !defined(NO_FILES)
  4235. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4236. root = conn->ctx->config[WEBSOCKET_ROOT];
  4237. }
  4238. #endif /* !NO_FILES */
  4239. #else /* USE_WEBSOCKET */
  4240. *is_websocket_request = 0;
  4241. #endif /* USE_WEBSOCKET */
  4242. #if !defined(NO_FILES)
  4243. /* Note that root == NULL is a regular use case here. This occurs,
  4244. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4245. * config is not required. */
  4246. if (root == NULL) {
  4247. /* all file related outputs have already been set to 0, just return
  4248. */
  4249. return;
  4250. }
  4251. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4252. * of the path one byte on the right.
  4253. * If document_root is NULL, leave the file empty. */
  4254. mg_snprintf(
  4255. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4256. if (truncated) {
  4257. goto interpret_cleanup;
  4258. }
  4259. rewrite = conn->ctx->config[REWRITE];
  4260. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4261. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4262. mg_snprintf(conn,
  4263. &truncated,
  4264. filename,
  4265. filename_buf_len - 1,
  4266. "%.*s%s",
  4267. (int)b.len,
  4268. b.ptr,
  4269. uri + match_len);
  4270. break;
  4271. }
  4272. }
  4273. if (truncated) {
  4274. goto interpret_cleanup;
  4275. }
  4276. /* Local file path and name, corresponding to requested URI
  4277. * is now stored in "filename" variable. */
  4278. if (mg_stat(conn, filename, filep)) {
  4279. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4280. /* File exists. Check if it is a script type. */
  4281. if (0
  4282. #if !defined(NO_CGI)
  4283. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4284. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4285. filename) > 0
  4286. #endif
  4287. #if defined(USE_LUA)
  4288. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4289. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4290. filename) > 0
  4291. #endif
  4292. #if defined(USE_DUKTAPE)
  4293. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4294. strlen(
  4295. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4296. filename) > 0
  4297. #endif
  4298. ) {
  4299. /* The request addresses a CGI script or a Lua script. The URI
  4300. * corresponds to the script itself (like /path/script.cgi),
  4301. * and there is no additional resource path
  4302. * (like /path/script.cgi/something).
  4303. * Requests that modify (replace or delete) a resource, like
  4304. * PUT and DELETE requests, should replace/delete the script
  4305. * file.
  4306. * Requests that read or write from/to a resource, like GET and
  4307. * POST requests, should call the script and return the
  4308. * generated response. */
  4309. *is_script_resource = !*is_put_or_delete_request;
  4310. }
  4311. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4312. *is_found = 1;
  4313. return;
  4314. }
  4315. /* If we can't find the actual file, look for the file
  4316. * with the same name but a .gz extension. If we find it,
  4317. * use that and set the gzipped flag in the file struct
  4318. * to indicate that the response need to have the content-
  4319. * encoding: gzip header.
  4320. * We can only do this if the browser declares support. */
  4321. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4322. if (strstr(accept_encoding, "gzip") != NULL) {
  4323. mg_snprintf(
  4324. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4325. if (truncated) {
  4326. goto interpret_cleanup;
  4327. }
  4328. if (mg_stat(conn, gz_path, filep)) {
  4329. if (filep) {
  4330. filep->gzipped = 1;
  4331. *is_found = 1;
  4332. }
  4333. /* Currently gz files can not be scripts. */
  4334. return;
  4335. }
  4336. }
  4337. }
  4338. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4339. /* Support PATH_INFO for CGI scripts. */
  4340. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4341. if (*p == '/') {
  4342. *p = '\0';
  4343. if ((0
  4344. #if !defined(NO_CGI)
  4345. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4346. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4347. filename) > 0
  4348. #endif
  4349. #if defined(USE_LUA)
  4350. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4351. strlen(
  4352. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4353. filename) > 0
  4354. #endif
  4355. #if defined(USE_DUKTAPE)
  4356. || match_prefix(
  4357. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4358. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4359. filename) > 0
  4360. #endif
  4361. ) && mg_stat(conn, filename, filep)) {
  4362. /* Shift PATH_INFO block one character right, e.g.
  4363. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4364. * conn->path_info is pointing to the local variable "path"
  4365. * declared in handle_request(), so PATH_INFO is not valid
  4366. * after handle_request returns. */
  4367. conn->path_info = p + 1;
  4368. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4369. * trailing \0 */
  4370. p[1] = '/';
  4371. *is_script_resource = 1;
  4372. break;
  4373. } else {
  4374. *p = '/';
  4375. }
  4376. }
  4377. }
  4378. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4379. #endif /* !defined(NO_FILES) */
  4380. return;
  4381. #if !defined(NO_FILES)
  4382. /* Reset all outputs */
  4383. interpret_cleanup:
  4384. memset(filep, 0, sizeof(*filep));
  4385. *filename = 0;
  4386. *is_found = 0;
  4387. *is_script_resource = 0;
  4388. *is_websocket_request = 0;
  4389. *is_put_or_delete_request = 0;
  4390. #endif /* !defined(NO_FILES) */
  4391. }
  4392. /* Check whether full request is buffered. Return:
  4393. * -1 if request is malformed
  4394. * 0 if request is not yet fully buffered
  4395. * >0 actual request length, including last \r\n\r\n */
  4396. static int
  4397. get_request_len(const char *buf, int buflen)
  4398. {
  4399. const char *s, *e;
  4400. int len = 0;
  4401. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4402. /* Control characters are not allowed but >=128 is. */
  4403. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4404. && *(const unsigned char *)s < 128) {
  4405. len = -1;
  4406. break; /* [i_a] abort scan as soon as one malformed character is
  4407. * found; */
  4408. /* don't let subsequent \r\n\r\n win us over anyhow */
  4409. } else if (s[0] == '\n' && s[1] == '\n') {
  4410. len = (int)(s - buf) + 2;
  4411. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4412. len = (int)(s - buf) + 3;
  4413. }
  4414. return len;
  4415. }
  4416. #if !defined(NO_CACHING)
  4417. /* Convert month to the month number. Return -1 on error, or month number */
  4418. static int
  4419. get_month_index(const char *s)
  4420. {
  4421. size_t i;
  4422. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4423. if (!strcmp(s, month_names[i])) {
  4424. return (int)i;
  4425. }
  4426. }
  4427. return -1;
  4428. }
  4429. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4430. static time_t
  4431. parse_date_string(const char *datetime)
  4432. {
  4433. char month_str[32] = {0};
  4434. int second, minute, hour, day, month, year;
  4435. time_t result = (time_t)0;
  4436. struct tm tm;
  4437. if ((sscanf(datetime,
  4438. "%d/%3s/%d %d:%d:%d",
  4439. &day,
  4440. month_str,
  4441. &year,
  4442. &hour,
  4443. &minute,
  4444. &second) == 6) || (sscanf(datetime,
  4445. "%d %3s %d %d:%d:%d",
  4446. &day,
  4447. month_str,
  4448. &year,
  4449. &hour,
  4450. &minute,
  4451. &second) == 6)
  4452. || (sscanf(datetime,
  4453. "%*3s, %d %3s %d %d:%d:%d",
  4454. &day,
  4455. month_str,
  4456. &year,
  4457. &hour,
  4458. &minute,
  4459. &second) == 6) || (sscanf(datetime,
  4460. "%d-%3s-%d %d:%d:%d",
  4461. &day,
  4462. month_str,
  4463. &year,
  4464. &hour,
  4465. &minute,
  4466. &second) == 6)) {
  4467. month = get_month_index(month_str);
  4468. if ((month >= 0) && (year >= 1970)) {
  4469. memset(&tm, 0, sizeof(tm));
  4470. tm.tm_year = year - 1900;
  4471. tm.tm_mon = month;
  4472. tm.tm_mday = day;
  4473. tm.tm_hour = hour;
  4474. tm.tm_min = minute;
  4475. tm.tm_sec = second;
  4476. result = timegm(&tm);
  4477. }
  4478. }
  4479. return result;
  4480. }
  4481. #endif /* !NO_CACHING */
  4482. /* Protect against directory disclosure attack by removing '..',
  4483. * excessive '/' and '\' characters */
  4484. static void
  4485. remove_double_dots_and_double_slashes(char *s)
  4486. {
  4487. char *p = s;
  4488. while (*s != '\0') {
  4489. *p++ = *s++;
  4490. if (s[-1] == '/' || s[-1] == '\\') {
  4491. /* Skip all following slashes, backslashes and double-dots */
  4492. while (s[0] != '\0') {
  4493. if (s[0] == '/' || s[0] == '\\') {
  4494. s++;
  4495. } else if (s[0] == '.' && s[1] == '.') {
  4496. s += 2;
  4497. } else {
  4498. break;
  4499. }
  4500. }
  4501. }
  4502. }
  4503. *p = '\0';
  4504. }
  4505. static const struct {
  4506. const char *extension;
  4507. size_t ext_len;
  4508. const char *mime_type;
  4509. } builtin_mime_types[] = {
  4510. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4511. * application types */
  4512. {".doc", 4, "application/msword"},
  4513. {".eps", 4, "application/postscript"},
  4514. {".exe", 4, "application/octet-stream"},
  4515. {".js", 3, "application/javascript"},
  4516. {".json", 5, "application/json"},
  4517. {".pdf", 4, "application/pdf"},
  4518. {".ps", 3, "application/postscript"},
  4519. {".rtf", 4, "application/rtf"},
  4520. {".xhtml", 6, "application/xhtml+xml"},
  4521. {".xsl", 4, "application/xml"},
  4522. {".xslt", 5, "application/xml"},
  4523. /* fonts */
  4524. {".ttf", 4, "application/font-sfnt"},
  4525. {".cff", 4, "application/font-sfnt"},
  4526. {".otf", 4, "application/font-sfnt"},
  4527. {".aat", 4, "application/font-sfnt"},
  4528. {".sil", 4, "application/font-sfnt"},
  4529. {".pfr", 4, "application/font-tdpfr"},
  4530. {".woff", 5, "application/font-woff"},
  4531. /* audio */
  4532. {".mp3", 4, "audio/mpeg"},
  4533. {".oga", 4, "audio/ogg"},
  4534. {".ogg", 4, "audio/ogg"},
  4535. /* image */
  4536. {".gif", 4, "image/gif"},
  4537. {".ief", 4, "image/ief"},
  4538. {".jpeg", 5, "image/jpeg"},
  4539. {".jpg", 4, "image/jpeg"},
  4540. {".jpm", 4, "image/jpm"},
  4541. {".jpx", 4, "image/jpx"},
  4542. {".png", 4, "image/png"},
  4543. {".svg", 4, "image/svg+xml"},
  4544. {".tif", 4, "image/tiff"},
  4545. {".tiff", 5, "image/tiff"},
  4546. /* model */
  4547. {".wrl", 4, "model/vrml"},
  4548. /* text */
  4549. {".css", 4, "text/css"},
  4550. {".csv", 4, "text/csv"},
  4551. {".htm", 4, "text/html"},
  4552. {".html", 5, "text/html"},
  4553. {".sgm", 4, "text/sgml"},
  4554. {".shtm", 5, "text/html"},
  4555. {".shtml", 6, "text/html"},
  4556. {".txt", 4, "text/plain"},
  4557. {".xml", 4, "text/xml"},
  4558. /* video */
  4559. {".mov", 4, "video/quicktime"},
  4560. {".mp4", 4, "video/mp4"},
  4561. {".mpeg", 5, "video/mpeg"},
  4562. {".mpg", 4, "video/mpeg"},
  4563. {".ogv", 4, "video/ogg"},
  4564. {".qt", 3, "video/quicktime"},
  4565. /* not registered types
  4566. * (http://reference.sitepoint.com/html/mime-types-full,
  4567. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4568. {".arj", 4, "application/x-arj-compressed"},
  4569. {".gz", 3, "application/x-gunzip"},
  4570. {".rar", 4, "application/x-arj-compressed"},
  4571. {".swf", 4, "application/x-shockwave-flash"},
  4572. {".tar", 4, "application/x-tar"},
  4573. {".tgz", 4, "application/x-tar-gz"},
  4574. {".torrent", 8, "application/x-bittorrent"},
  4575. {".ppt", 4, "application/x-mspowerpoint"},
  4576. {".xls", 4, "application/x-msexcel"},
  4577. {".zip", 4, "application/x-zip-compressed"},
  4578. {".aac",
  4579. 4,
  4580. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4581. {".aif", 4, "audio/x-aif"},
  4582. {".m3u", 4, "audio/x-mpegurl"},
  4583. {".mid", 4, "audio/x-midi"},
  4584. {".ra", 3, "audio/x-pn-realaudio"},
  4585. {".ram", 4, "audio/x-pn-realaudio"},
  4586. {".wav", 4, "audio/x-wav"},
  4587. {".bmp", 4, "image/bmp"},
  4588. {".ico", 4, "image/x-icon"},
  4589. {".pct", 4, "image/x-pct"},
  4590. {".pict", 5, "image/pict"},
  4591. {".rgb", 4, "image/x-rgb"},
  4592. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4593. {".asf", 4, "video/x-ms-asf"},
  4594. {".avi", 4, "video/x-msvideo"},
  4595. {".m4v", 4, "video/x-m4v"},
  4596. {NULL, 0, NULL}};
  4597. const char *
  4598. mg_get_builtin_mime_type(const char *path)
  4599. {
  4600. const char *ext;
  4601. size_t i, path_len;
  4602. path_len = strlen(path);
  4603. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4604. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4605. if (path_len > builtin_mime_types[i].ext_len
  4606. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4607. return builtin_mime_types[i].mime_type;
  4608. }
  4609. }
  4610. return "text/plain";
  4611. }
  4612. /* Look at the "path" extension and figure what mime type it has.
  4613. * Store mime type in the vector. */
  4614. static void
  4615. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4616. {
  4617. struct vec ext_vec, mime_vec;
  4618. const char *list, *ext;
  4619. size_t path_len;
  4620. path_len = strlen(path);
  4621. if (ctx == NULL || vec == NULL) {
  4622. return;
  4623. }
  4624. /* Scan user-defined mime types first, in case user wants to
  4625. * override default mime types. */
  4626. list = ctx->config[EXTRA_MIME_TYPES];
  4627. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4628. /* ext now points to the path suffix */
  4629. ext = path + path_len - ext_vec.len;
  4630. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4631. *vec = mime_vec;
  4632. return;
  4633. }
  4634. }
  4635. vec->ptr = mg_get_builtin_mime_type(path);
  4636. vec->len = strlen(vec->ptr);
  4637. }
  4638. /* Stringify binary data. Output buffer must be twice as big as input,
  4639. * because each byte takes 2 bytes in string representation */
  4640. static void
  4641. bin2str(char *to, const unsigned char *p, size_t len)
  4642. {
  4643. static const char *hex = "0123456789abcdef";
  4644. for (; len--; p++) {
  4645. *to++ = hex[p[0] >> 4];
  4646. *to++ = hex[p[0] & 0x0f];
  4647. }
  4648. *to = '\0';
  4649. }
  4650. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4651. char *
  4652. mg_md5(char buf[33], ...)
  4653. {
  4654. md5_byte_t hash[16];
  4655. const char *p;
  4656. va_list ap;
  4657. md5_state_t ctx;
  4658. md5_init(&ctx);
  4659. va_start(ap, buf);
  4660. while ((p = va_arg(ap, const char *)) != NULL) {
  4661. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4662. }
  4663. va_end(ap);
  4664. md5_finish(&ctx, hash);
  4665. bin2str(buf, hash, sizeof(hash));
  4666. return buf;
  4667. }
  4668. /* Check the user's password, return 1 if OK */
  4669. static int
  4670. check_password(const char *method,
  4671. const char *ha1,
  4672. const char *uri,
  4673. const char *nonce,
  4674. const char *nc,
  4675. const char *cnonce,
  4676. const char *qop,
  4677. const char *response)
  4678. {
  4679. char ha2[32 + 1], expected_response[32 + 1];
  4680. /* Some of the parameters may be NULL */
  4681. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4682. || qop == NULL
  4683. || response == NULL) {
  4684. return 0;
  4685. }
  4686. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4687. if (strlen(response) != 32) {
  4688. return 0;
  4689. }
  4690. mg_md5(ha2, method, ":", uri, NULL);
  4691. mg_md5(expected_response,
  4692. ha1,
  4693. ":",
  4694. nonce,
  4695. ":",
  4696. nc,
  4697. ":",
  4698. cnonce,
  4699. ":",
  4700. qop,
  4701. ":",
  4702. ha2,
  4703. NULL);
  4704. return mg_strcasecmp(response, expected_response) == 0;
  4705. }
  4706. /* Use the global passwords file, if specified by auth_gpass option,
  4707. * or search for .htpasswd in the requested directory. */
  4708. static void
  4709. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4710. {
  4711. if (conn != NULL && conn->ctx != NULL) {
  4712. char name[PATH_MAX];
  4713. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4714. struct file file = STRUCT_FILE_INITIALIZER;
  4715. int truncated;
  4716. if (gpass != NULL) {
  4717. /* Use global passwords file */
  4718. if (!mg_fopen(conn, gpass, "r", filep)) {
  4719. #ifdef DEBUG
  4720. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4721. #endif
  4722. }
  4723. /* Important: using local struct file to test path for is_directory
  4724. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4725. * was opened. */
  4726. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4727. mg_snprintf(conn,
  4728. &truncated,
  4729. name,
  4730. sizeof(name),
  4731. "%s/%s",
  4732. path,
  4733. PASSWORDS_FILE_NAME);
  4734. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4735. #ifdef DEBUG
  4736. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4737. #endif
  4738. }
  4739. } else {
  4740. /* Try to find .htpasswd in requested directory. */
  4741. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4742. if (e[0] == '/') {
  4743. break;
  4744. }
  4745. }
  4746. mg_snprintf(conn,
  4747. &truncated,
  4748. name,
  4749. sizeof(name),
  4750. "%.*s/%s",
  4751. (int)(e - p),
  4752. p,
  4753. PASSWORDS_FILE_NAME);
  4754. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4755. #ifdef DEBUG
  4756. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4757. #endif
  4758. }
  4759. }
  4760. }
  4761. }
  4762. /* Parsed Authorization header */
  4763. struct ah {
  4764. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4765. };
  4766. /* Return 1 on success. Always initializes the ah structure. */
  4767. static int
  4768. parse_auth_header(struct mg_connection *conn,
  4769. char *buf,
  4770. size_t buf_size,
  4771. struct ah *ah)
  4772. {
  4773. char *name, *value, *s;
  4774. const char *auth_header;
  4775. uint64_t nonce;
  4776. if (!ah || !conn) {
  4777. return 0;
  4778. }
  4779. (void)memset(ah, 0, sizeof(*ah));
  4780. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4781. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4782. return 0;
  4783. }
  4784. /* Make modifiable copy of the auth header */
  4785. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4786. s = buf;
  4787. /* Parse authorization header */
  4788. for (;;) {
  4789. /* Gobble initial spaces */
  4790. while (isspace(*(unsigned char *)s)) {
  4791. s++;
  4792. }
  4793. name = skip_quoted(&s, "=", " ", 0);
  4794. /* Value is either quote-delimited, or ends at first comma or space. */
  4795. if (s[0] == '\"') {
  4796. s++;
  4797. value = skip_quoted(&s, "\"", " ", '\\');
  4798. if (s[0] == ',') {
  4799. s++;
  4800. }
  4801. } else {
  4802. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4803. * spaces */
  4804. }
  4805. if (*name == '\0') {
  4806. break;
  4807. }
  4808. if (!strcmp(name, "username")) {
  4809. ah->user = value;
  4810. } else if (!strcmp(name, "cnonce")) {
  4811. ah->cnonce = value;
  4812. } else if (!strcmp(name, "response")) {
  4813. ah->response = value;
  4814. } else if (!strcmp(name, "uri")) {
  4815. ah->uri = value;
  4816. } else if (!strcmp(name, "qop")) {
  4817. ah->qop = value;
  4818. } else if (!strcmp(name, "nc")) {
  4819. ah->nc = value;
  4820. } else if (!strcmp(name, "nonce")) {
  4821. ah->nonce = value;
  4822. }
  4823. }
  4824. #ifndef NO_NONCE_CHECK
  4825. /* Read the nonce from the response. */
  4826. if (ah->nonce == NULL) {
  4827. return 0;
  4828. }
  4829. s = NULL;
  4830. nonce = strtoull(ah->nonce, &s, 10);
  4831. if ((s == NULL) || (*s != 0)) {
  4832. return 0;
  4833. }
  4834. /* Convert the nonce from the client to a number. */
  4835. nonce ^= conn->ctx->auth_nonce_mask;
  4836. /* The converted number corresponds to the time the nounce has been
  4837. * created. This should not be earlier than the server start. */
  4838. /* Server side nonce check is valuable in all situations but one:
  4839. * if the server restarts frequently, but the client should not see
  4840. * that, so the server should accept nonces from previous starts. */
  4841. /* However, the reasonable default is to not accept a nonce from a
  4842. * previous start, so if anyone changed the access rights between
  4843. * two restarts, a new login is required. */
  4844. if (nonce < (uint64_t)conn->ctx->start_time) {
  4845. /* nonce is from a previous start of the server and no longer valid
  4846. * (replay attack?) */
  4847. return 0;
  4848. }
  4849. /* Check if the nonce is too high, so it has not (yet) been used by the
  4850. * server. */
  4851. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4852. return 0;
  4853. }
  4854. #else
  4855. (void)nonce;
  4856. #endif
  4857. /* CGI needs it as REMOTE_USER */
  4858. if (ah->user != NULL) {
  4859. conn->request_info.remote_user = mg_strdup(ah->user);
  4860. } else {
  4861. return 0;
  4862. }
  4863. return 1;
  4864. }
  4865. static const char *
  4866. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4867. {
  4868. const char *eof;
  4869. size_t len;
  4870. const char *memend;
  4871. if (!filep) {
  4872. return NULL;
  4873. }
  4874. if (filep->membuf != NULL && *p != NULL) {
  4875. memend = (const char *)&filep->membuf[filep->size];
  4876. /* Search for \n from p till the end of stream */
  4877. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4878. if (eof != NULL) {
  4879. eof += 1; /* Include \n */
  4880. } else {
  4881. eof = memend; /* Copy remaining data */
  4882. }
  4883. len =
  4884. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4885. memcpy(buf, *p, len);
  4886. buf[len] = '\0';
  4887. *p += len;
  4888. return len ? eof : NULL;
  4889. } else if (filep->fp != NULL) {
  4890. return fgets(buf, (int)size, filep->fp);
  4891. } else {
  4892. return NULL;
  4893. }
  4894. }
  4895. struct read_auth_file_struct {
  4896. struct mg_connection *conn;
  4897. struct ah ah;
  4898. char *domain;
  4899. char buf[256 + 256 + 40];
  4900. char *f_user;
  4901. char *f_domain;
  4902. char *f_ha1;
  4903. };
  4904. static int
  4905. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4906. {
  4907. char *p;
  4908. int is_authorized = 0;
  4909. struct file fp;
  4910. size_t l;
  4911. if (!filep || !workdata) {
  4912. return 0;
  4913. }
  4914. /* Loop over passwords file */
  4915. p = (char *)filep->membuf;
  4916. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4917. l = strlen(workdata->buf);
  4918. while (l > 0) {
  4919. if (isspace(workdata->buf[l - 1])
  4920. || iscntrl(workdata->buf[l - 1])) {
  4921. l--;
  4922. workdata->buf[l] = 0;
  4923. } else
  4924. break;
  4925. }
  4926. if (l < 1) {
  4927. continue;
  4928. }
  4929. workdata->f_user = workdata->buf;
  4930. if (workdata->f_user[0] == ':') {
  4931. /* user names may not contain a ':' and may not be empty,
  4932. * so lines starting with ':' may be used for a special purpose */
  4933. if (workdata->f_user[1] == '#') {
  4934. /* :# is a comment */
  4935. continue;
  4936. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4937. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4938. is_authorized = read_auth_file(&fp, workdata);
  4939. mg_fclose(&fp);
  4940. } else {
  4941. mg_cry(workdata->conn,
  4942. "%s: cannot open authorization file: %s",
  4943. __func__,
  4944. workdata->buf);
  4945. }
  4946. continue;
  4947. }
  4948. /* everything is invalid for the moment (might change in the
  4949. * future) */
  4950. mg_cry(workdata->conn,
  4951. "%s: syntax error in authorization file: %s",
  4952. __func__,
  4953. workdata->buf);
  4954. continue;
  4955. }
  4956. workdata->f_domain = strchr(workdata->f_user, ':');
  4957. if (workdata->f_domain == NULL) {
  4958. mg_cry(workdata->conn,
  4959. "%s: syntax error in authorization file: %s",
  4960. __func__,
  4961. workdata->buf);
  4962. continue;
  4963. }
  4964. *(workdata->f_domain) = 0;
  4965. (workdata->f_domain)++;
  4966. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4967. if (workdata->f_ha1 == NULL) {
  4968. mg_cry(workdata->conn,
  4969. "%s: syntax error in authorization file: %s",
  4970. __func__,
  4971. workdata->buf);
  4972. continue;
  4973. }
  4974. *(workdata->f_ha1) = 0;
  4975. (workdata->f_ha1)++;
  4976. if (!strcmp(workdata->ah.user, workdata->f_user)
  4977. && !strcmp(workdata->domain, workdata->f_domain)) {
  4978. return check_password(workdata->conn->request_info.request_method,
  4979. workdata->f_ha1,
  4980. workdata->ah.uri,
  4981. workdata->ah.nonce,
  4982. workdata->ah.nc,
  4983. workdata->ah.cnonce,
  4984. workdata->ah.qop,
  4985. workdata->ah.response);
  4986. }
  4987. }
  4988. return is_authorized;
  4989. }
  4990. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4991. static int
  4992. authorize(struct mg_connection *conn, struct file *filep)
  4993. {
  4994. struct read_auth_file_struct workdata;
  4995. char buf[MG_BUF_LEN];
  4996. if (!conn || !conn->ctx) {
  4997. return 0;
  4998. }
  4999. memset(&workdata, 0, sizeof(workdata));
  5000. workdata.conn = conn;
  5001. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5002. return 0;
  5003. }
  5004. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5005. return read_auth_file(filep, &workdata);
  5006. }
  5007. /* Return 1 if request is authorised, 0 otherwise. */
  5008. static int
  5009. check_authorization(struct mg_connection *conn, const char *path)
  5010. {
  5011. char fname[PATH_MAX];
  5012. struct vec uri_vec, filename_vec;
  5013. const char *list;
  5014. struct file file = STRUCT_FILE_INITIALIZER;
  5015. int authorized = 1, truncated;
  5016. if (!conn || !conn->ctx) {
  5017. return 0;
  5018. }
  5019. list = conn->ctx->config[PROTECT_URI];
  5020. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5021. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5022. mg_snprintf(conn,
  5023. &truncated,
  5024. fname,
  5025. sizeof(fname),
  5026. "%.*s",
  5027. (int)filename_vec.len,
  5028. filename_vec.ptr);
  5029. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5030. mg_cry(conn,
  5031. "%s: cannot open %s: %s",
  5032. __func__,
  5033. fname,
  5034. strerror(errno));
  5035. }
  5036. break;
  5037. }
  5038. }
  5039. if (!is_file_opened(&file)) {
  5040. open_auth_file(conn, path, &file);
  5041. }
  5042. if (is_file_opened(&file)) {
  5043. authorized = authorize(conn, &file);
  5044. mg_fclose(&file);
  5045. }
  5046. return authorized;
  5047. }
  5048. static void
  5049. send_authorization_request(struct mg_connection *conn)
  5050. {
  5051. char date[64];
  5052. time_t curtime = time(NULL);
  5053. if (conn && conn->ctx) {
  5054. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5055. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5056. nonce += conn->ctx->nonce_count;
  5057. ++conn->ctx->nonce_count;
  5058. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5059. nonce ^= conn->ctx->auth_nonce_mask;
  5060. conn->status_code = 401;
  5061. conn->must_close = 1;
  5062. gmt_time_string(date, sizeof(date), &curtime);
  5063. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5064. send_no_cache_header(conn);
  5065. mg_printf(conn,
  5066. "Date: %s\r\n"
  5067. "Connection: %s\r\n"
  5068. "Content-Length: 0\r\n"
  5069. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5070. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5071. date,
  5072. suggest_connection_header(conn),
  5073. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5074. nonce);
  5075. }
  5076. }
  5077. #if !defined(NO_FILES)
  5078. static int
  5079. is_authorized_for_put(struct mg_connection *conn)
  5080. {
  5081. if (conn) {
  5082. struct file file = STRUCT_FILE_INITIALIZER;
  5083. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5084. int ret = 0;
  5085. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5086. ret = authorize(conn, &file);
  5087. mg_fclose(&file);
  5088. }
  5089. return ret;
  5090. }
  5091. return 0;
  5092. }
  5093. #endif
  5094. int
  5095. mg_modify_passwords_file(const char *fname,
  5096. const char *domain,
  5097. const char *user,
  5098. const char *pass)
  5099. {
  5100. int found, i;
  5101. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5102. FILE *fp, *fp2;
  5103. found = 0;
  5104. fp = fp2 = NULL;
  5105. /* Regard empty password as no password - remove user record. */
  5106. if (pass != NULL && pass[0] == '\0') {
  5107. pass = NULL;
  5108. }
  5109. /* Other arguments must not be empty */
  5110. if (fname == NULL || domain == NULL || user == NULL) {
  5111. return 0;
  5112. }
  5113. /* Using the given file format, user name and domain must not contain ':'
  5114. */
  5115. if (strchr(user, ':') != NULL) {
  5116. return 0;
  5117. }
  5118. if (strchr(domain, ':') != NULL) {
  5119. return 0;
  5120. }
  5121. /* Do not allow control characters like newline in user name and domain.
  5122. * Do not allow excessively long names either. */
  5123. for (i = 0; i < 255 && user[i] != 0; i++) {
  5124. if (iscntrl(user[i])) {
  5125. return 0;
  5126. }
  5127. }
  5128. if (user[i]) {
  5129. return 0;
  5130. }
  5131. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5132. if (iscntrl(domain[i])) {
  5133. return 0;
  5134. }
  5135. }
  5136. if (domain[i]) {
  5137. return 0;
  5138. }
  5139. /* The maximum length of the path to the password file is limited */
  5140. if ((strlen(fname) + 4) >= PATH_MAX) {
  5141. return 0;
  5142. }
  5143. /* Create a temporary file name. Length has been checked before. */
  5144. strcpy(tmp, fname);
  5145. strcat(tmp, ".tmp");
  5146. /* Create the file if does not exist */
  5147. /* Use of fopen here is OK, since fname is only ASCII */
  5148. if ((fp = fopen(fname, "a+")) != NULL) {
  5149. (void)fclose(fp);
  5150. }
  5151. /* Open the given file and temporary file */
  5152. if ((fp = fopen(fname, "r")) == NULL) {
  5153. return 0;
  5154. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5155. fclose(fp);
  5156. return 0;
  5157. }
  5158. /* Copy the stuff to temporary file */
  5159. while (fgets(line, sizeof(line), fp) != NULL) {
  5160. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5161. continue;
  5162. }
  5163. u[255] = 0;
  5164. d[255] = 0;
  5165. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5166. found++;
  5167. if (pass != NULL) {
  5168. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5169. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5170. }
  5171. } else {
  5172. fprintf(fp2, "%s", line);
  5173. }
  5174. }
  5175. /* If new user, just add it */
  5176. if (!found && pass != NULL) {
  5177. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5178. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5179. }
  5180. /* Close files */
  5181. fclose(fp);
  5182. fclose(fp2);
  5183. /* Put the temp file in place of real file */
  5184. IGNORE_UNUSED_RESULT(remove(fname));
  5185. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5186. return 1;
  5187. }
  5188. static int
  5189. is_valid_port(unsigned long port)
  5190. {
  5191. return port < 0xffff;
  5192. }
  5193. static int
  5194. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5195. {
  5196. struct addrinfo hints, *res, *ressave;
  5197. int func_ret = 0;
  5198. int gai_ret;
  5199. memset(&hints, 0, sizeof(struct addrinfo));
  5200. hints.ai_family = af;
  5201. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5202. if (gai_ret != 0) {
  5203. /* gai_strerror could be used to convert gai_ret to a string */
  5204. /* POSIX return values: see
  5205. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5206. */
  5207. /* Windows return values: see
  5208. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5209. */
  5210. return 0;
  5211. }
  5212. ressave = res;
  5213. while (res) {
  5214. if (dstlen >= res->ai_addrlen) {
  5215. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5216. func_ret = 1;
  5217. }
  5218. res = res->ai_next;
  5219. }
  5220. freeaddrinfo(ressave);
  5221. return func_ret;
  5222. }
  5223. static int
  5224. connect_socket(struct mg_context *ctx /* may be NULL */,
  5225. const char *host,
  5226. int port,
  5227. int use_ssl,
  5228. char *ebuf,
  5229. size_t ebuf_len,
  5230. SOCKET *sock /* output: socket, must not be NULL */,
  5231. union usa *sa /* output: socket address, must not be NULL */
  5232. )
  5233. {
  5234. int ip_ver = 0;
  5235. *sock = INVALID_SOCKET;
  5236. memset(sa, 0, sizeof(*sa));
  5237. if (ebuf_len > 0) {
  5238. *ebuf = 0;
  5239. }
  5240. if (host == NULL) {
  5241. mg_snprintf(NULL,
  5242. NULL, /* No truncation check for ebuf */
  5243. ebuf,
  5244. ebuf_len,
  5245. "%s",
  5246. "NULL host");
  5247. return 0;
  5248. }
  5249. if (port < 0 || !is_valid_port((unsigned)port)) {
  5250. mg_snprintf(NULL,
  5251. NULL, /* No truncation check for ebuf */
  5252. ebuf,
  5253. ebuf_len,
  5254. "%s",
  5255. "invalid port");
  5256. return 0;
  5257. }
  5258. #if !defined(NO_SSL)
  5259. if (use_ssl && (SSLv23_client_method == NULL)) {
  5260. mg_snprintf(NULL,
  5261. NULL, /* No truncation check for ebuf */
  5262. ebuf,
  5263. ebuf_len,
  5264. "%s",
  5265. "SSL is not initialized");
  5266. return 0;
  5267. }
  5268. #else
  5269. (void)use_ssl;
  5270. #endif
  5271. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5272. sa->sin.sin_port = htons((uint16_t)port);
  5273. ip_ver = 4;
  5274. #ifdef USE_IPV6
  5275. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5276. sa->sin6.sin6_port = htons((uint16_t)port);
  5277. ip_ver = 6;
  5278. } else if (host[0] == '[') {
  5279. /* While getaddrinfo on Windows will work with [::1],
  5280. * getaddrinfo on Linux only works with ::1 (without []). */
  5281. size_t l = strlen(host + 1);
  5282. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5283. if (h) {
  5284. h[l - 1] = 0;
  5285. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5286. sa->sin6.sin6_port = htons((uint16_t)port);
  5287. ip_ver = 6;
  5288. }
  5289. mg_free(h);
  5290. }
  5291. #endif
  5292. }
  5293. if (ip_ver == 0) {
  5294. mg_snprintf(NULL,
  5295. NULL, /* No truncation check for ebuf */
  5296. ebuf,
  5297. ebuf_len,
  5298. "%s",
  5299. "host not found");
  5300. return 0;
  5301. }
  5302. if (ip_ver == 4) {
  5303. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5304. }
  5305. #ifdef USE_IPV6
  5306. else if (ip_ver == 6) {
  5307. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5308. }
  5309. #endif
  5310. if (*sock == INVALID_SOCKET) {
  5311. mg_snprintf(NULL,
  5312. NULL, /* No truncation check for ebuf */
  5313. ebuf,
  5314. ebuf_len,
  5315. "socket(): %s",
  5316. strerror(ERRNO));
  5317. return 0;
  5318. }
  5319. set_close_on_exec(*sock, fc(ctx));
  5320. if ((ip_ver == 4)
  5321. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5322. == 0)) {
  5323. /* connected with IPv4 */
  5324. return 1;
  5325. }
  5326. #ifdef USE_IPV6
  5327. if ((ip_ver == 6)
  5328. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5329. == 0)) {
  5330. /* connected with IPv6 */
  5331. return 1;
  5332. }
  5333. #endif
  5334. /* Not connected */
  5335. mg_snprintf(NULL,
  5336. NULL, /* No truncation check for ebuf */
  5337. ebuf,
  5338. ebuf_len,
  5339. "connect(%s:%d): %s",
  5340. host,
  5341. port,
  5342. strerror(ERRNO));
  5343. closesocket(*sock);
  5344. *sock = INVALID_SOCKET;
  5345. return 0;
  5346. }
  5347. int
  5348. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5349. {
  5350. static const char *dont_escape = "._-$,;~()";
  5351. static const char *hex = "0123456789abcdef";
  5352. char *pos = dst;
  5353. const char *end = dst + dst_len - 1;
  5354. for (; *src != '\0' && pos < end; src++, pos++) {
  5355. if (isalnum(*(const unsigned char *)src)
  5356. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5357. *pos = *src;
  5358. } else if (pos + 2 < end) {
  5359. pos[0] = '%';
  5360. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5361. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5362. pos += 2;
  5363. } else {
  5364. break;
  5365. }
  5366. }
  5367. *pos = '\0';
  5368. return (*src == '\0') ? (int)(pos - dst) : -1;
  5369. }
  5370. static void
  5371. print_dir_entry(struct de *de)
  5372. {
  5373. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5374. struct tm *tm;
  5375. if (de->file.is_directory) {
  5376. mg_snprintf(de->conn,
  5377. NULL, /* Buffer is big enough */
  5378. size,
  5379. sizeof(size),
  5380. "%s",
  5381. "[DIRECTORY]");
  5382. } else {
  5383. /* We use (signed) cast below because MSVC 6 compiler cannot
  5384. * convert unsigned __int64 to double. Sigh. */
  5385. if (de->file.size < 1024) {
  5386. mg_snprintf(de->conn,
  5387. NULL, /* Buffer is big enough */
  5388. size,
  5389. sizeof(size),
  5390. "%d",
  5391. (int)de->file.size);
  5392. } else if (de->file.size < 0x100000) {
  5393. mg_snprintf(de->conn,
  5394. NULL, /* Buffer is big enough */
  5395. size,
  5396. sizeof(size),
  5397. "%.1fk",
  5398. (double)de->file.size / 1024.0);
  5399. } else if (de->file.size < 0x40000000) {
  5400. mg_snprintf(de->conn,
  5401. NULL, /* Buffer is big enough */
  5402. size,
  5403. sizeof(size),
  5404. "%.1fM",
  5405. (double)de->file.size / 1048576);
  5406. } else {
  5407. mg_snprintf(de->conn,
  5408. NULL, /* Buffer is big enough */
  5409. size,
  5410. sizeof(size),
  5411. "%.1fG",
  5412. (double)de->file.size / 1073741824);
  5413. }
  5414. }
  5415. /* Note: mg_snprintf will not cause a buffer overflow above.
  5416. * So, string truncation checks are not required here. */
  5417. tm = localtime(&de->file.last_modified);
  5418. if (tm != NULL) {
  5419. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5420. } else {
  5421. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5422. mod[sizeof(mod) - 1] = '\0';
  5423. }
  5424. mg_url_encode(de->file_name, href, sizeof(href));
  5425. de->conn->num_bytes_sent +=
  5426. mg_printf(de->conn,
  5427. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5428. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5429. de->conn->request_info.local_uri,
  5430. href,
  5431. de->file.is_directory ? "/" : "",
  5432. de->file_name,
  5433. de->file.is_directory ? "/" : "",
  5434. mod,
  5435. size);
  5436. }
  5437. /* This function is called from send_directory() and used for
  5438. * sorting directory entries by size, or name, or modification time.
  5439. * On windows, __cdecl specification is needed in case if project is built
  5440. * with __stdcall convention. qsort always requires __cdels callback. */
  5441. static int WINCDECL
  5442. compare_dir_entries(const void *p1, const void *p2)
  5443. {
  5444. if (p1 && p2) {
  5445. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5446. const char *query_string = a->conn->request_info.query_string;
  5447. int cmp_result = 0;
  5448. if (query_string == NULL) {
  5449. query_string = "na";
  5450. }
  5451. if (a->file.is_directory && !b->file.is_directory) {
  5452. return -1; /* Always put directories on top */
  5453. } else if (!a->file.is_directory && b->file.is_directory) {
  5454. return 1; /* Always put directories on top */
  5455. } else if (*query_string == 'n') {
  5456. cmp_result = strcmp(a->file_name, b->file_name);
  5457. } else if (*query_string == 's') {
  5458. cmp_result = (a->file.size == b->file.size)
  5459. ? 0
  5460. : ((a->file.size > b->file.size) ? 1 : -1);
  5461. } else if (*query_string == 'd') {
  5462. cmp_result =
  5463. (a->file.last_modified == b->file.last_modified)
  5464. ? 0
  5465. : ((a->file.last_modified > b->file.last_modified) ? 1
  5466. : -1);
  5467. }
  5468. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5469. }
  5470. return 0;
  5471. }
  5472. static int
  5473. must_hide_file(struct mg_connection *conn, const char *path)
  5474. {
  5475. if (conn && conn->ctx) {
  5476. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5477. const char *pattern = conn->ctx->config[HIDE_FILES];
  5478. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5479. || (pattern != NULL
  5480. && match_prefix(pattern, strlen(pattern), path) > 0);
  5481. }
  5482. return 0;
  5483. }
  5484. static int
  5485. scan_directory(struct mg_connection *conn,
  5486. const char *dir,
  5487. void *data,
  5488. void (*cb)(struct de *, void *))
  5489. {
  5490. char path[PATH_MAX];
  5491. struct dirent *dp;
  5492. DIR *dirp;
  5493. struct de de;
  5494. int truncated;
  5495. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5496. return 0;
  5497. } else {
  5498. de.conn = conn;
  5499. while ((dp = mg_readdir(dirp)) != NULL) {
  5500. /* Do not show current dir and hidden files */
  5501. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5502. || must_hide_file(conn, dp->d_name)) {
  5503. continue;
  5504. }
  5505. mg_snprintf(
  5506. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5507. /* If we don't memset stat structure to zero, mtime will have
  5508. * garbage and strftime() will segfault later on in
  5509. * print_dir_entry(). memset is required only if mg_stat()
  5510. * fails. For more details, see
  5511. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5512. memset(&de.file, 0, sizeof(de.file));
  5513. if (truncated) {
  5514. /* If the path is not complete, skip processing. */
  5515. continue;
  5516. }
  5517. if (!mg_stat(conn, path, &de.file)) {
  5518. mg_cry(conn,
  5519. "%s: mg_stat(%s) failed: %s",
  5520. __func__,
  5521. path,
  5522. strerror(ERRNO));
  5523. }
  5524. de.file_name = dp->d_name;
  5525. cb(&de, data);
  5526. }
  5527. (void)mg_closedir(dirp);
  5528. }
  5529. return 1;
  5530. }
  5531. #if !defined(NO_FILES)
  5532. static int
  5533. remove_directory(struct mg_connection *conn, const char *dir)
  5534. {
  5535. char path[PATH_MAX];
  5536. struct dirent *dp;
  5537. DIR *dirp;
  5538. struct de de;
  5539. int truncated;
  5540. int ok = 1;
  5541. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5542. return 0;
  5543. } else {
  5544. de.conn = conn;
  5545. while ((dp = mg_readdir(dirp)) != NULL) {
  5546. /* Do not show current dir (but show hidden files as they will
  5547. * also be removed) */
  5548. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5549. continue;
  5550. }
  5551. mg_snprintf(
  5552. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5553. /* If we don't memset stat structure to zero, mtime will have
  5554. * garbage and strftime() will segfault later on in
  5555. * print_dir_entry(). memset is required only if mg_stat()
  5556. * fails. For more details, see
  5557. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5558. memset(&de.file, 0, sizeof(de.file));
  5559. if (truncated) {
  5560. /* Do not delete anything shorter */
  5561. ok = 0;
  5562. continue;
  5563. }
  5564. if (!mg_stat(conn, path, &de.file)) {
  5565. mg_cry(conn,
  5566. "%s: mg_stat(%s) failed: %s",
  5567. __func__,
  5568. path,
  5569. strerror(ERRNO));
  5570. ok = 0;
  5571. }
  5572. if (de.file.membuf == NULL) {
  5573. /* file is not in memory */
  5574. if (de.file.is_directory) {
  5575. if (remove_directory(conn, path) == 0) {
  5576. ok = 0;
  5577. }
  5578. } else {
  5579. if (mg_remove(conn, path) == 0) {
  5580. ok = 0;
  5581. }
  5582. }
  5583. } else {
  5584. /* file is in memory. It can not be deleted. */
  5585. ok = 0;
  5586. }
  5587. }
  5588. (void)mg_closedir(dirp);
  5589. IGNORE_UNUSED_RESULT(rmdir(dir));
  5590. }
  5591. return ok;
  5592. }
  5593. #endif
  5594. struct dir_scan_data {
  5595. struct de *entries;
  5596. unsigned int num_entries;
  5597. unsigned int arr_size;
  5598. };
  5599. /* Behaves like realloc(), but frees original pointer on failure */
  5600. static void *
  5601. realloc2(void *ptr, size_t size)
  5602. {
  5603. void *new_ptr = mg_realloc(ptr, size);
  5604. if (new_ptr == NULL) {
  5605. mg_free(ptr);
  5606. }
  5607. return new_ptr;
  5608. }
  5609. static void
  5610. dir_scan_callback(struct de *de, void *data)
  5611. {
  5612. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5613. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5614. dsd->arr_size *= 2;
  5615. dsd->entries =
  5616. (struct de *)realloc2(dsd->entries,
  5617. dsd->arr_size * sizeof(dsd->entries[0]));
  5618. }
  5619. if (dsd->entries == NULL) {
  5620. /* TODO(lsm, low): propagate an error to the caller */
  5621. dsd->num_entries = 0;
  5622. } else {
  5623. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5624. dsd->entries[dsd->num_entries].file = de->file;
  5625. dsd->entries[dsd->num_entries].conn = de->conn;
  5626. dsd->num_entries++;
  5627. }
  5628. }
  5629. static void
  5630. handle_directory_request(struct mg_connection *conn, const char *dir)
  5631. {
  5632. unsigned int i;
  5633. int sort_direction;
  5634. struct dir_scan_data data = {NULL, 0, 128};
  5635. char date[64];
  5636. time_t curtime = time(NULL);
  5637. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5638. send_http_error(conn,
  5639. 500,
  5640. "Error: Cannot open directory\nopendir(%s): %s",
  5641. dir,
  5642. strerror(ERRNO));
  5643. return;
  5644. }
  5645. gmt_time_string(date, sizeof(date), &curtime);
  5646. if (!conn) {
  5647. return;
  5648. }
  5649. sort_direction = ((conn->request_info.query_string != NULL)
  5650. && (conn->request_info.query_string[1] == 'd'))
  5651. ? 'a'
  5652. : 'd';
  5653. conn->must_close = 1;
  5654. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5655. send_static_cache_header(conn);
  5656. mg_printf(conn,
  5657. "Date: %s\r\n"
  5658. "Connection: close\r\n"
  5659. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5660. date);
  5661. conn->num_bytes_sent +=
  5662. mg_printf(conn,
  5663. "<html><head><title>Index of %s</title>"
  5664. "<style>th {text-align: left;}</style></head>"
  5665. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5666. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5667. "<th><a href=\"?d%c\">Modified</a></th>"
  5668. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5669. "<tr><td colspan=\"3\"><hr></td></tr>",
  5670. conn->request_info.local_uri,
  5671. conn->request_info.local_uri,
  5672. sort_direction,
  5673. sort_direction,
  5674. sort_direction);
  5675. /* Print first entry - link to a parent directory */
  5676. conn->num_bytes_sent +=
  5677. mg_printf(conn,
  5678. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5679. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5680. conn->request_info.local_uri,
  5681. "..",
  5682. "Parent directory",
  5683. "-",
  5684. "-");
  5685. /* Sort and print directory entries */
  5686. if (data.entries != NULL) {
  5687. qsort(data.entries,
  5688. (size_t)data.num_entries,
  5689. sizeof(data.entries[0]),
  5690. compare_dir_entries);
  5691. for (i = 0; i < data.num_entries; i++) {
  5692. print_dir_entry(&data.entries[i]);
  5693. mg_free(data.entries[i].file_name);
  5694. }
  5695. mg_free(data.entries);
  5696. }
  5697. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5698. conn->status_code = 200;
  5699. }
  5700. /* Send len bytes from the opened file to the client. */
  5701. static void
  5702. send_file_data(struct mg_connection *conn,
  5703. struct file *filep,
  5704. int64_t offset,
  5705. int64_t len)
  5706. {
  5707. char buf[MG_BUF_LEN];
  5708. int to_read, num_read, num_written;
  5709. int64_t size;
  5710. if (!filep || !conn) {
  5711. return;
  5712. }
  5713. /* Sanity check the offset */
  5714. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5715. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5716. if (len > 0 && filep->membuf != NULL && size > 0) {
  5717. /* file stored in memory */
  5718. if (len > size - offset) {
  5719. len = size - offset;
  5720. }
  5721. mg_write(conn, filep->membuf + offset, (size_t)len);
  5722. } else if (len > 0 && filep->fp != NULL) {
  5723. /* file stored on disk */
  5724. #if defined(__linux__)
  5725. /* sendfile is only available for Linux */
  5726. if (conn->throttle == 0 && conn->ssl == 0) {
  5727. off_t sf_offs = (off_t)offset;
  5728. ssize_t sf_sent;
  5729. int sf_file = fileno(filep->fp);
  5730. int loop_cnt = 0;
  5731. do {
  5732. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5733. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5734. size_t sf_tosend =
  5735. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5736. sf_sent =
  5737. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5738. if (sf_sent > 0) {
  5739. conn->num_bytes_sent += sf_sent;
  5740. len -= sf_sent;
  5741. offset += sf_sent;
  5742. } else if (loop_cnt == 0) {
  5743. /* This file can not be sent using sendfile.
  5744. * This might be the case for pseudo-files in the
  5745. * /sys/ and /proc/ file system.
  5746. * Use the regular user mode copy code instead. */
  5747. break;
  5748. } else if (sf_sent == 0) {
  5749. /* No error, but 0 bytes sent. May be EOF? */
  5750. return;
  5751. }
  5752. loop_cnt++;
  5753. } while ((len > 0) && (sf_sent >= 0));
  5754. if (sf_sent > 0) {
  5755. return; /* OK */
  5756. }
  5757. /* sf_sent<0 means error, thus fall back to the classic way */
  5758. /* This is always the case, if sf_file is not a "normal" file,
  5759. * e.g., for sending data from the output of a CGI process. */
  5760. offset = (int64_t)sf_offs;
  5761. }
  5762. #endif
  5763. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5764. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5765. send_http_error(
  5766. conn,
  5767. 500,
  5768. "%s",
  5769. "Error: Unable to access file at requested position.");
  5770. } else {
  5771. while (len > 0) {
  5772. /* Calculate how much to read from the file in the buffer */
  5773. to_read = sizeof(buf);
  5774. if ((int64_t)to_read > len) {
  5775. to_read = (int)len;
  5776. }
  5777. /* Read from file, exit the loop on error */
  5778. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5779. <= 0) {
  5780. break;
  5781. }
  5782. /* Send read bytes to the client, exit the loop on error */
  5783. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5784. != num_read) {
  5785. break;
  5786. }
  5787. /* Both read and were successful, adjust counters */
  5788. conn->num_bytes_sent += num_written;
  5789. len -= num_written;
  5790. }
  5791. }
  5792. }
  5793. }
  5794. static int
  5795. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5796. {
  5797. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5798. }
  5799. static void
  5800. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5801. {
  5802. if (filep != NULL && buf != NULL) {
  5803. mg_snprintf(NULL,
  5804. NULL, /* All calls to construct_etag use 64 byte buffer */
  5805. buf,
  5806. buf_len,
  5807. "\"%lx.%" INT64_FMT "\"",
  5808. (unsigned long)filep->last_modified,
  5809. filep->size);
  5810. }
  5811. }
  5812. static void
  5813. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5814. {
  5815. if (filep != NULL && filep->fp != NULL) {
  5816. #ifdef _WIN32
  5817. (void)conn; /* Unused. */
  5818. #else
  5819. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5820. mg_cry(conn,
  5821. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5822. __func__,
  5823. strerror(ERRNO));
  5824. }
  5825. #endif
  5826. }
  5827. }
  5828. static void
  5829. handle_static_file_request(struct mg_connection *conn,
  5830. const char *path,
  5831. struct file *filep,
  5832. const char *mime_type)
  5833. {
  5834. char date[64], lm[64], etag[64];
  5835. char range[128]; /* large enough, so there will be no overflow */
  5836. const char *msg = "OK", *hdr;
  5837. time_t curtime = time(NULL);
  5838. int64_t cl, r1, r2;
  5839. struct vec mime_vec;
  5840. int n, truncated;
  5841. char gz_path[PATH_MAX];
  5842. const char *encoding = "";
  5843. const char *cors1, *cors2, *cors3;
  5844. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5845. return;
  5846. }
  5847. if (mime_type == NULL) {
  5848. get_mime_type(conn->ctx, path, &mime_vec);
  5849. } else {
  5850. mime_vec.ptr = mime_type;
  5851. mime_vec.len = strlen(mime_type);
  5852. }
  5853. if (filep->size > INT64_MAX) {
  5854. send_http_error(conn,
  5855. 500,
  5856. "Error: File size is too large to send\n%" INT64_FMT,
  5857. filep->size);
  5858. }
  5859. cl = (int64_t)filep->size;
  5860. conn->status_code = 200;
  5861. range[0] = '\0';
  5862. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5863. * it's important to rewrite the filename after resolving
  5864. * the mime type from it, to preserve the actual file's type */
  5865. if (filep->gzipped) {
  5866. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5867. if (truncated) {
  5868. send_http_error(conn,
  5869. 500,
  5870. "Error: Path of zipped file too long (%s)",
  5871. path);
  5872. return;
  5873. }
  5874. path = gz_path;
  5875. encoding = "Content-Encoding: gzip\r\n";
  5876. }
  5877. if (!mg_fopen(conn, path, "rb", filep)) {
  5878. send_http_error(conn,
  5879. 500,
  5880. "Error: Cannot open file\nfopen(%s): %s",
  5881. path,
  5882. strerror(ERRNO));
  5883. return;
  5884. }
  5885. fclose_on_exec(filep, conn);
  5886. /* If Range: header specified, act accordingly */
  5887. r1 = r2 = 0;
  5888. hdr = mg_get_header(conn, "Range");
  5889. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5890. && r2 >= 0) {
  5891. /* actually, range requests don't play well with a pre-gzipped
  5892. * file (since the range is specified in the uncompressed space) */
  5893. if (filep->gzipped) {
  5894. send_http_error(
  5895. conn,
  5896. 501,
  5897. "%s",
  5898. "Error: Range requests in gzipped files are not supported");
  5899. mg_fclose(filep);
  5900. return;
  5901. }
  5902. conn->status_code = 206;
  5903. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5904. mg_snprintf(conn,
  5905. NULL, /* range buffer is big enough */
  5906. range,
  5907. sizeof(range),
  5908. "Content-Range: bytes "
  5909. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5910. r1,
  5911. r1 + cl - 1,
  5912. filep->size);
  5913. msg = "Partial Content";
  5914. }
  5915. hdr = mg_get_header(conn, "Origin");
  5916. if (hdr) {
  5917. /* Cross-origin resource sharing (CORS), see
  5918. * http://www.html5rocks.com/en/tutorials/cors/,
  5919. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5920. * preflight is not supported for files. */
  5921. cors1 = "Access-Control-Allow-Origin: ";
  5922. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5923. cors3 = "\r\n";
  5924. } else {
  5925. cors1 = cors2 = cors3 = "";
  5926. }
  5927. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5928. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5929. gmt_time_string(date, sizeof(date), &curtime);
  5930. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5931. construct_etag(etag, sizeof(etag), filep);
  5932. (void)mg_printf(conn,
  5933. "HTTP/1.1 %d %s\r\n"
  5934. "%s%s%s"
  5935. "Date: %s\r\n",
  5936. conn->status_code,
  5937. msg,
  5938. cors1,
  5939. cors2,
  5940. cors3,
  5941. date);
  5942. send_static_cache_header(conn);
  5943. (void)mg_printf(conn,
  5944. "Last-Modified: %s\r\n"
  5945. "Etag: %s\r\n"
  5946. "Content-Type: %.*s\r\n"
  5947. "Content-Length: %" INT64_FMT "\r\n"
  5948. "Connection: %s\r\n"
  5949. "Accept-Ranges: bytes\r\n"
  5950. "%s%s\r\n",
  5951. lm,
  5952. etag,
  5953. (int)mime_vec.len,
  5954. mime_vec.ptr,
  5955. cl,
  5956. suggest_connection_header(conn),
  5957. range,
  5958. encoding);
  5959. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5960. send_file_data(conn, filep, r1, cl);
  5961. }
  5962. mg_fclose(filep);
  5963. }
  5964. #if !defined(NO_CACHING)
  5965. static void
  5966. handle_not_modified_static_file_request(struct mg_connection *conn,
  5967. struct file *filep)
  5968. {
  5969. char date[64], lm[64], etag[64];
  5970. time_t curtime = time(NULL);
  5971. if (conn == NULL || filep == NULL) {
  5972. return;
  5973. }
  5974. conn->status_code = 304;
  5975. gmt_time_string(date, sizeof(date), &curtime);
  5976. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5977. construct_etag(etag, sizeof(etag), filep);
  5978. (void)mg_printf(conn,
  5979. "HTTP/1.1 %d %s\r\n"
  5980. "Date: %s\r\n",
  5981. conn->status_code,
  5982. mg_get_response_code_text(conn, conn->status_code),
  5983. date);
  5984. send_static_cache_header(conn);
  5985. (void)mg_printf(conn,
  5986. "Last-Modified: %s\r\n"
  5987. "Etag: %s\r\n"
  5988. "Connection: %s\r\n"
  5989. "\r\n",
  5990. lm,
  5991. etag,
  5992. suggest_connection_header(conn));
  5993. }
  5994. #endif
  5995. void
  5996. mg_send_file(struct mg_connection *conn, const char *path)
  5997. {
  5998. mg_send_mime_file(conn, path, NULL);
  5999. }
  6000. void
  6001. mg_send_mime_file(struct mg_connection *conn,
  6002. const char *path,
  6003. const char *mime_type)
  6004. {
  6005. struct file file = STRUCT_FILE_INITIALIZER;
  6006. if (mg_stat(conn, path, &file)) {
  6007. if (file.is_directory) {
  6008. if (!conn) {
  6009. return;
  6010. }
  6011. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6012. "yes")) {
  6013. handle_directory_request(conn, path);
  6014. } else {
  6015. send_http_error(conn,
  6016. 403,
  6017. "%s",
  6018. "Error: Directory listing denied");
  6019. }
  6020. } else {
  6021. handle_static_file_request(conn, path, &file, mime_type);
  6022. }
  6023. } else {
  6024. send_http_error(conn, 404, "%s", "Error: File not found");
  6025. }
  6026. }
  6027. /* For a given PUT path, create all intermediate subdirectories.
  6028. * Return 0 if the path itself is a directory.
  6029. * Return 1 if the path leads to a file.
  6030. * Return -1 for if the path is too long.
  6031. * Return -2 if path can not be created.
  6032. */
  6033. static int
  6034. put_dir(struct mg_connection *conn, const char *path)
  6035. {
  6036. char buf[PATH_MAX];
  6037. const char *s, *p;
  6038. struct file file = STRUCT_FILE_INITIALIZER;
  6039. size_t len;
  6040. int res = 1;
  6041. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6042. len = (size_t)(p - path);
  6043. if (len >= sizeof(buf)) {
  6044. /* path too long */
  6045. res = -1;
  6046. break;
  6047. }
  6048. memcpy(buf, path, len);
  6049. buf[len] = '\0';
  6050. /* Try to create intermediate directory */
  6051. DEBUG_TRACE("mkdir(%s)", buf);
  6052. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6053. /* path does not exixt and can not be created */
  6054. res = -2;
  6055. break;
  6056. }
  6057. /* Is path itself a directory? */
  6058. if (p[1] == '\0') {
  6059. res = 0;
  6060. }
  6061. }
  6062. return res;
  6063. }
  6064. static void
  6065. remove_bad_file(const struct mg_connection *conn, const char *path)
  6066. {
  6067. int r = mg_remove(conn, path);
  6068. if (r != 0) {
  6069. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6070. }
  6071. }
  6072. long long
  6073. mg_store_body(struct mg_connection *conn, const char *path)
  6074. {
  6075. char buf[MG_BUF_LEN];
  6076. long long len = 0;
  6077. int ret, n;
  6078. struct file fi;
  6079. if (conn->consumed_content != 0) {
  6080. mg_cry(conn, "%s: Contents already consumed", __func__);
  6081. return -11;
  6082. }
  6083. ret = put_dir(conn, path);
  6084. if (ret < 0) {
  6085. /* -1 for path too long,
  6086. * -2 for path can not be created. */
  6087. return ret;
  6088. }
  6089. if (ret != 1) {
  6090. /* Return 0 means, path itself is a directory. */
  6091. return 0;
  6092. }
  6093. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6094. return -12;
  6095. }
  6096. ret = mg_read(conn, buf, sizeof(buf));
  6097. while (ret > 0) {
  6098. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6099. if (n != ret) {
  6100. mg_fclose(&fi);
  6101. remove_bad_file(conn, path);
  6102. return -13;
  6103. }
  6104. ret = mg_read(conn, buf, sizeof(buf));
  6105. }
  6106. /* TODO: mg_fclose should return an error,
  6107. * and every caller should check and handle it. */
  6108. if (fclose(fi.fp) != 0) {
  6109. remove_bad_file(conn, path);
  6110. return -14;
  6111. }
  6112. return len;
  6113. }
  6114. /* Parse HTTP headers from the given buffer, advance buf pointer
  6115. * to the point where parsing stopped.
  6116. * All parameters must be valid pointers (not NULL).
  6117. * Return <0 on error. */
  6118. static int
  6119. parse_http_headers(char **buf, struct mg_request_info *ri)
  6120. {
  6121. int i;
  6122. ri->num_headers = 0;
  6123. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6124. char *dp = *buf;
  6125. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6126. dp++;
  6127. }
  6128. if (dp == *buf) {
  6129. /* End of headers reached. */
  6130. break;
  6131. }
  6132. if (*dp != ':') {
  6133. /* This is not a valid field. */
  6134. return -1;
  6135. }
  6136. /* End of header key (*dp == ':') */
  6137. /* Truncate here and set the key name */
  6138. *dp = 0;
  6139. ri->http_headers[i].name = *buf;
  6140. do {
  6141. dp++;
  6142. } while (*dp == ' ');
  6143. /* The rest of the line is the value */
  6144. ri->http_headers[i].value = dp;
  6145. *buf = dp + strcspn(dp, "\r\n");
  6146. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6147. *buf = NULL;
  6148. }
  6149. ri->num_headers = i + 1;
  6150. if (*buf) {
  6151. (*buf)[0] = 0;
  6152. (*buf)[1] = 0;
  6153. *buf += 2;
  6154. } else {
  6155. *buf = dp;
  6156. break;
  6157. }
  6158. if ((*buf)[0] == '\r') {
  6159. /* This is the end of the header */
  6160. break;
  6161. }
  6162. }
  6163. return ri->num_headers;
  6164. }
  6165. static int
  6166. is_valid_http_method(const char *method)
  6167. {
  6168. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6169. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6170. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6171. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6172. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6173. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6174. /* TRACE method (RFC 2616) is not supported for security reasons */
  6175. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6176. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6177. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6178. /* Unsupported WEBDAV Methods: */
  6179. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6180. /* + 11 methods from RFC 3253 */
  6181. /* ORDERPATCH (RFC 3648) */
  6182. /* ACL (RFC 3744) */
  6183. /* SEARCH (RFC 5323) */
  6184. /* + MicroSoft extensions
  6185. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6186. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6187. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6188. }
  6189. /* Parse HTTP request, fill in mg_request_info structure.
  6190. * This function modifies the buffer by NUL-terminating
  6191. * HTTP request components, header names and header values.
  6192. * Parameters:
  6193. * buf (in/out): pointer to the HTTP header to parse and split
  6194. * len (in): length of HTTP header buffer
  6195. * re (out): parsed header as mg_request_info
  6196. * buf and ri must be valid pointers (not NULL), len>0.
  6197. * Returns <0 on error. */
  6198. static int
  6199. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6200. {
  6201. int is_request, request_length;
  6202. char *start_line;
  6203. request_length = get_request_len(buf, len);
  6204. if (request_length > 0) {
  6205. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6206. * remote_port */
  6207. ri->remote_user = ri->request_method = ri->request_uri =
  6208. ri->http_version = NULL;
  6209. ri->num_headers = 0;
  6210. buf[request_length - 1] = '\0';
  6211. /* RFC says that all initial whitespaces should be ingored */
  6212. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6213. buf++;
  6214. }
  6215. start_line = skip(&buf, "\r\n");
  6216. ri->request_method = skip(&start_line, " ");
  6217. ri->request_uri = skip(&start_line, " ");
  6218. ri->http_version = start_line;
  6219. /* HTTP message could be either HTTP request:
  6220. * "GET / HTTP/1.0 ..."
  6221. * or a HTTP response:
  6222. * "HTTP/1.0 200 OK ..."
  6223. * otherwise it is invalid.
  6224. */
  6225. is_request = is_valid_http_method(ri->request_method);
  6226. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6227. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6228. /* Not a valid request or response: invalid */
  6229. return -1;
  6230. }
  6231. if (is_request) {
  6232. ri->http_version += 5;
  6233. }
  6234. if (parse_http_headers(&buf, ri) < 0) {
  6235. /* Error while parsing headers */
  6236. return -1;
  6237. }
  6238. }
  6239. return request_length;
  6240. }
  6241. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6242. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6243. * buffer (which marks the end of HTTP request). Buffer buf may already
  6244. * have some data. The length of the data is stored in nread.
  6245. * Upon every read operation, increase nread by the number of bytes read. */
  6246. static int
  6247. read_request(FILE *fp,
  6248. struct mg_connection *conn,
  6249. char *buf,
  6250. int bufsiz,
  6251. int *nread)
  6252. {
  6253. int request_len, n = 0;
  6254. struct timespec last_action_time;
  6255. double request_timeout;
  6256. if (!conn) {
  6257. return 0;
  6258. }
  6259. memset(&last_action_time, 0, sizeof(last_action_time));
  6260. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6261. /* value of request_timeout is in seconds, config in milliseconds */
  6262. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6263. } else {
  6264. request_timeout = -1.0;
  6265. }
  6266. request_len = get_request_len(buf, *nread);
  6267. /* first time reading from this connection */
  6268. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6269. while (
  6270. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6271. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6272. <= request_timeout) || (request_timeout < 0))
  6273. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6274. > 0)) {
  6275. *nread += n;
  6276. /* assert(*nread <= bufsiz); */
  6277. if (*nread > bufsiz) {
  6278. return -2;
  6279. }
  6280. request_len = get_request_len(buf, *nread);
  6281. if (request_timeout > 0.0) {
  6282. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6283. }
  6284. }
  6285. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6286. }
  6287. #if !defined(NO_FILES)
  6288. /* For given directory path, substitute it to valid index file.
  6289. * Return 1 if index file has been found, 0 if not found.
  6290. * If the file is found, it's stats is returned in stp. */
  6291. static int
  6292. substitute_index_file(struct mg_connection *conn,
  6293. char *path,
  6294. size_t path_len,
  6295. struct file *filep)
  6296. {
  6297. if (conn && conn->ctx) {
  6298. const char *list = conn->ctx->config[INDEX_FILES];
  6299. struct file file = STRUCT_FILE_INITIALIZER;
  6300. struct vec filename_vec;
  6301. size_t n = strlen(path);
  6302. int found = 0;
  6303. /* The 'path' given to us points to the directory. Remove all trailing
  6304. * directory separator characters from the end of the path, and
  6305. * then append single directory separator character. */
  6306. while (n > 0 && path[n - 1] == '/') {
  6307. n--;
  6308. }
  6309. path[n] = '/';
  6310. /* Traverse index files list. For each entry, append it to the given
  6311. * path and see if the file exists. If it exists, break the loop */
  6312. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6313. /* Ignore too long entries that may overflow path buffer */
  6314. if (filename_vec.len > path_len - (n + 2)) {
  6315. continue;
  6316. }
  6317. /* Prepare full path to the index file */
  6318. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6319. /* Does it exist? */
  6320. if (mg_stat(conn, path, &file)) {
  6321. /* Yes it does, break the loop */
  6322. *filep = file;
  6323. found = 1;
  6324. break;
  6325. }
  6326. }
  6327. /* If no index file exists, restore directory path */
  6328. if (!found) {
  6329. path[n] = '\0';
  6330. }
  6331. return found;
  6332. }
  6333. return 0;
  6334. }
  6335. #endif
  6336. #if !defined(NO_CACHING)
  6337. /* Return True if we should reply 304 Not Modified. */
  6338. static int
  6339. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6340. {
  6341. char etag[64];
  6342. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6343. const char *inm = mg_get_header(conn, "If-None-Match");
  6344. construct_etag(etag, sizeof(etag), filep);
  6345. if (!filep) {
  6346. return 0;
  6347. }
  6348. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6349. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6350. }
  6351. #endif /* !NO_CACHING */
  6352. #if !defined(NO_CGI) || !defined(NO_FILES)
  6353. static int
  6354. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6355. {
  6356. const char *expect, *body;
  6357. char buf[MG_BUF_LEN];
  6358. int to_read, nread, success = 0;
  6359. int64_t buffered_len;
  6360. double timeout = -1.0;
  6361. if (!conn) {
  6362. return 0;
  6363. }
  6364. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6365. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6366. }
  6367. expect = mg_get_header(conn, "Expect");
  6368. /* assert(fp != NULL); */
  6369. if (!fp) {
  6370. send_http_error(conn, 500, "%s", "Error: NULL File");
  6371. return 0;
  6372. }
  6373. if (conn->content_len == -1 && !conn->is_chunked) {
  6374. /* Content length is not specified by the client. */
  6375. send_http_error(conn,
  6376. 411,
  6377. "%s",
  6378. "Error: Client did not specify content length");
  6379. } else if ((expect != NULL)
  6380. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6381. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6382. send_http_error(conn,
  6383. 417,
  6384. "Error: Can not fulfill expectation %s",
  6385. expect);
  6386. } else {
  6387. if (expect != NULL) {
  6388. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6389. conn->status_code = 100;
  6390. } else {
  6391. conn->status_code = 200;
  6392. }
  6393. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6394. - conn->consumed_content;
  6395. /* assert(buffered_len >= 0); */
  6396. /* assert(conn->consumed_content == 0); */
  6397. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6398. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6399. return 0;
  6400. }
  6401. if (buffered_len > 0) {
  6402. if ((int64_t)buffered_len > conn->content_len) {
  6403. buffered_len = (int)conn->content_len;
  6404. }
  6405. body = conn->buf + conn->request_len + conn->consumed_content;
  6406. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6407. conn->consumed_content += buffered_len;
  6408. }
  6409. nread = 0;
  6410. while (conn->consumed_content < conn->content_len) {
  6411. to_read = sizeof(buf);
  6412. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6413. to_read = (int)(conn->content_len - conn->consumed_content);
  6414. }
  6415. nread = pull(NULL, conn, buf, to_read, timeout);
  6416. if (nread <= 0
  6417. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6418. break;
  6419. }
  6420. conn->consumed_content += nread;
  6421. }
  6422. if (conn->consumed_content == conn->content_len) {
  6423. success = (nread >= 0);
  6424. }
  6425. /* Each error code path in this function must send an error */
  6426. if (!success) {
  6427. /* NOTE: Maybe some data has already been sent. */
  6428. /* TODO (low): If some data has been sent, a correct error
  6429. * reply can no longer be sent, so just close the connection */
  6430. send_http_error(conn, 500, "%s", "");
  6431. }
  6432. }
  6433. return success;
  6434. }
  6435. #endif
  6436. #if !defined(NO_CGI)
  6437. /* This structure helps to create an environment for the spawned CGI program.
  6438. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6439. * last element must be NULL.
  6440. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6441. * strings must reside in a contiguous buffer. The end of the buffer is
  6442. * marked by two '\0' characters.
  6443. * We satisfy both worlds: we create an envp array (which is vars), all
  6444. * entries are actually pointers inside buf. */
  6445. struct cgi_environment {
  6446. struct mg_connection *conn;
  6447. /* Data block */
  6448. char *buf; /* Environment buffer */
  6449. size_t buflen; /* Space available in buf */
  6450. size_t bufused; /* Space taken in buf */
  6451. /* Index block */
  6452. char **var; /* char **envp */
  6453. size_t varlen; /* Number of variables available in var */
  6454. size_t varused; /* Number of variables stored in var */
  6455. };
  6456. static void addenv(struct cgi_environment *env,
  6457. PRINTF_FORMAT_STRING(const char *fmt),
  6458. ...) PRINTF_ARGS(2, 3);
  6459. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6460. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6461. static void
  6462. addenv(struct cgi_environment *env, const char *fmt, ...)
  6463. {
  6464. size_t n, space;
  6465. int truncated;
  6466. char *added;
  6467. va_list ap;
  6468. /* Calculate how much space is left in the buffer */
  6469. space = (env->buflen - env->bufused);
  6470. /* Calculate an estimate for the required space */
  6471. n = strlen(fmt) + 2 + 128;
  6472. do {
  6473. if (space <= n) {
  6474. /* Allocate new buffer */
  6475. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6476. added = (char *)mg_realloc(env->buf, n);
  6477. if (!added) {
  6478. /* Out of memory */
  6479. mg_cry(env->conn,
  6480. "%s: Cannot allocate memory for CGI variable [%s]",
  6481. __func__,
  6482. fmt);
  6483. return;
  6484. }
  6485. env->buf = added;
  6486. env->buflen = n;
  6487. space = (env->buflen - env->bufused);
  6488. }
  6489. /* Make a pointer to the free space int the buffer */
  6490. added = env->buf + env->bufused;
  6491. /* Copy VARIABLE=VALUE\0 string into the free space */
  6492. va_start(ap, fmt);
  6493. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6494. va_end(ap);
  6495. /* Do not add truncated strings to the environment */
  6496. if (truncated) {
  6497. /* Reallocate the buffer */
  6498. space = 0;
  6499. n = 1;
  6500. }
  6501. } while (truncated);
  6502. /* Calculate number of bytes added to the environment */
  6503. n = strlen(added) + 1;
  6504. env->bufused += n;
  6505. /* Now update the variable index */
  6506. space = (env->varlen - env->varused);
  6507. if (space < 2) {
  6508. mg_cry(env->conn,
  6509. "%s: Cannot register CGI variable [%s]",
  6510. __func__,
  6511. fmt);
  6512. return;
  6513. }
  6514. /* Append a pointer to the added string into the envp array */
  6515. env->var[env->varused] = added;
  6516. env->varused++;
  6517. }
  6518. static void
  6519. prepare_cgi_environment(struct mg_connection *conn,
  6520. const char *prog,
  6521. struct cgi_environment *env)
  6522. {
  6523. const char *s;
  6524. struct vec var_vec;
  6525. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6526. int i, truncated;
  6527. if (conn == NULL || prog == NULL || env == NULL) {
  6528. return;
  6529. }
  6530. env->conn = conn;
  6531. env->buflen = CGI_ENVIRONMENT_SIZE;
  6532. env->bufused = 0;
  6533. env->buf = (char *)mg_malloc(env->buflen);
  6534. env->varlen = MAX_CGI_ENVIR_VARS;
  6535. env->varused = 0;
  6536. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6537. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6538. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6539. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6540. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6541. /* Prepare the environment block */
  6542. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6543. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6544. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6545. #if defined(USE_IPV6)
  6546. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6547. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6548. } else
  6549. #endif
  6550. {
  6551. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6552. }
  6553. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6554. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6555. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6556. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6557. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6558. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6559. /* SCRIPT_NAME */
  6560. addenv(env,
  6561. "SCRIPT_NAME=%.*s",
  6562. (int)strlen(conn->request_info.local_uri)
  6563. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6564. conn->request_info.local_uri);
  6565. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6566. if (conn->path_info == NULL) {
  6567. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6568. } else {
  6569. addenv(env,
  6570. "PATH_TRANSLATED=%s%s",
  6571. conn->ctx->config[DOCUMENT_ROOT],
  6572. conn->path_info);
  6573. }
  6574. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6575. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6576. addenv(env, "CONTENT_TYPE=%s", s);
  6577. }
  6578. if (conn->request_info.query_string != NULL) {
  6579. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6580. }
  6581. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6582. addenv(env, "CONTENT_LENGTH=%s", s);
  6583. }
  6584. if ((s = getenv("PATH")) != NULL) {
  6585. addenv(env, "PATH=%s", s);
  6586. }
  6587. if (conn->path_info != NULL) {
  6588. addenv(env, "PATH_INFO=%s", conn->path_info);
  6589. }
  6590. if (conn->status_code > 0) {
  6591. /* CGI error handler should show the status code */
  6592. addenv(env, "STATUS=%d", conn->status_code);
  6593. }
  6594. #if defined(_WIN32)
  6595. if ((s = getenv("COMSPEC")) != NULL) {
  6596. addenv(env, "COMSPEC=%s", s);
  6597. }
  6598. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6599. addenv(env, "SYSTEMROOT=%s", s);
  6600. }
  6601. if ((s = getenv("SystemDrive")) != NULL) {
  6602. addenv(env, "SystemDrive=%s", s);
  6603. }
  6604. if ((s = getenv("ProgramFiles")) != NULL) {
  6605. addenv(env, "ProgramFiles=%s", s);
  6606. }
  6607. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6608. addenv(env, "ProgramFiles(x86)=%s", s);
  6609. }
  6610. #else
  6611. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6612. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6613. }
  6614. #endif /* _WIN32 */
  6615. if ((s = getenv("PERLLIB")) != NULL) {
  6616. addenv(env, "PERLLIB=%s", s);
  6617. }
  6618. if (conn->request_info.remote_user != NULL) {
  6619. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6620. addenv(env, "%s", "AUTH_TYPE=Digest");
  6621. }
  6622. /* Add all headers as HTTP_* variables */
  6623. for (i = 0; i < conn->request_info.num_headers; i++) {
  6624. (void)mg_snprintf(conn,
  6625. &truncated,
  6626. http_var_name,
  6627. sizeof(http_var_name),
  6628. "HTTP_%s",
  6629. conn->request_info.http_headers[i].name);
  6630. if (truncated) {
  6631. mg_cry(conn,
  6632. "%s: HTTP header variable too long [%s]",
  6633. __func__,
  6634. conn->request_info.http_headers[i].name);
  6635. continue;
  6636. }
  6637. /* Convert variable name into uppercase, and change - to _ */
  6638. for (p = http_var_name; *p != '\0'; p++) {
  6639. if (*p == '-') {
  6640. *p = '_';
  6641. }
  6642. *p = (char)toupper(*(unsigned char *)p);
  6643. }
  6644. addenv(env,
  6645. "%s=%s",
  6646. http_var_name,
  6647. conn->request_info.http_headers[i].value);
  6648. }
  6649. /* Add user-specified variables */
  6650. s = conn->ctx->config[CGI_ENVIRONMENT];
  6651. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6652. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6653. }
  6654. env->var[env->varused] = NULL;
  6655. env->buf[env->bufused] = '\0';
  6656. }
  6657. static void
  6658. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6659. {
  6660. char *buf;
  6661. size_t buflen;
  6662. int headers_len, data_len, i, truncated;
  6663. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6664. const char *status, *status_text, *connection_state;
  6665. char *pbuf, dir[PATH_MAX], *p;
  6666. struct mg_request_info ri;
  6667. struct cgi_environment blk;
  6668. FILE *in = NULL, *out = NULL, *err = NULL;
  6669. struct file fout = STRUCT_FILE_INITIALIZER;
  6670. pid_t pid = (pid_t)-1;
  6671. if (conn == NULL) {
  6672. return;
  6673. }
  6674. buf = NULL;
  6675. buflen = 16384;
  6676. prepare_cgi_environment(conn, prog, &blk);
  6677. /* CGI must be executed in its own directory. 'dir' must point to the
  6678. * directory containing executable program, 'p' must point to the
  6679. * executable program name relative to 'dir'. */
  6680. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6681. if (truncated) {
  6682. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6683. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6684. goto done;
  6685. }
  6686. if ((p = strrchr(dir, '/')) != NULL) {
  6687. *p++ = '\0';
  6688. } else {
  6689. dir[0] = '.', dir[1] = '\0';
  6690. p = (char *)prog;
  6691. }
  6692. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6693. status = strerror(ERRNO);
  6694. mg_cry(conn,
  6695. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6696. prog,
  6697. status);
  6698. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6699. goto done;
  6700. }
  6701. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6702. if (pid == (pid_t)-1) {
  6703. status = strerror(ERRNO);
  6704. mg_cry(conn,
  6705. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6706. prog,
  6707. status);
  6708. send_http_error(conn,
  6709. 500,
  6710. "Error: Cannot spawn CGI process [%s]: %s",
  6711. prog,
  6712. status);
  6713. goto done;
  6714. }
  6715. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6716. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6717. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6718. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6719. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6720. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6721. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6722. /* Parent closes only one side of the pipes.
  6723. * If we don't mark them as closed, close() attempt before
  6724. * return from this function throws an exception on Windows.
  6725. * Windows does not like when closed descriptor is closed again. */
  6726. (void)close(fdin[0]);
  6727. (void)close(fdout[1]);
  6728. (void)close(fderr[1]);
  6729. fdin[0] = fdout[1] = fderr[1] = -1;
  6730. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6731. status = strerror(ERRNO);
  6732. mg_cry(conn,
  6733. "Error: CGI program \"%s\": Can not open stdin: %s",
  6734. prog,
  6735. status);
  6736. send_http_error(conn,
  6737. 500,
  6738. "Error: CGI can not open fdin\nfopen: %s",
  6739. status);
  6740. goto done;
  6741. }
  6742. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6743. status = strerror(ERRNO);
  6744. mg_cry(conn,
  6745. "Error: CGI program \"%s\": Can not open stdout: %s",
  6746. prog,
  6747. status);
  6748. send_http_error(conn,
  6749. 500,
  6750. "Error: CGI can not open fdout\nfopen: %s",
  6751. status);
  6752. goto done;
  6753. }
  6754. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6755. status = strerror(ERRNO);
  6756. mg_cry(conn,
  6757. "Error: CGI program \"%s\": Can not open stderr: %s",
  6758. prog,
  6759. status);
  6760. send_http_error(conn,
  6761. 500,
  6762. "Error: CGI can not open fdout\nfopen: %s",
  6763. status);
  6764. goto done;
  6765. }
  6766. setbuf(in, NULL);
  6767. setbuf(out, NULL);
  6768. setbuf(err, NULL);
  6769. fout.fp = out;
  6770. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6771. /* This is a POST/PUT request, or another request with body data. */
  6772. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6773. /* Error sending the body data */
  6774. mg_cry(conn,
  6775. "Error: CGI program \"%s\": Forward body data failed",
  6776. prog);
  6777. goto done;
  6778. }
  6779. }
  6780. /* Close so child gets an EOF. */
  6781. fclose(in);
  6782. in = NULL;
  6783. fdin[1] = -1;
  6784. /* Now read CGI reply into a buffer. We need to set correct
  6785. * status code, thus we need to see all HTTP headers first.
  6786. * Do not send anything back to client, until we buffer in all
  6787. * HTTP headers. */
  6788. data_len = 0;
  6789. buf = (char *)mg_malloc(buflen);
  6790. if (buf == NULL) {
  6791. send_http_error(conn,
  6792. 500,
  6793. "Error: Not enough memory for CGI buffer (%u bytes)",
  6794. (unsigned int)buflen);
  6795. mg_cry(conn,
  6796. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6797. "bytes)",
  6798. prog,
  6799. (unsigned int)buflen);
  6800. goto done;
  6801. }
  6802. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6803. if (headers_len <= 0) {
  6804. /* Could not parse the CGI response. Check if some error message on
  6805. * stderr. */
  6806. i = pull_all(err, conn, buf, (int)buflen);
  6807. if (i > 0) {
  6808. mg_cry(conn,
  6809. "Error: CGI program \"%s\" sent error "
  6810. "message: [%.*s]",
  6811. prog,
  6812. i,
  6813. buf);
  6814. send_http_error(conn,
  6815. 500,
  6816. "Error: CGI program \"%s\" sent error "
  6817. "message: [%.*s]",
  6818. prog,
  6819. i,
  6820. buf);
  6821. } else {
  6822. mg_cry(conn,
  6823. "Error: CGI program sent malformed or too big "
  6824. "(>%u bytes) HTTP headers: [%.*s]",
  6825. (unsigned)buflen,
  6826. data_len,
  6827. buf);
  6828. send_http_error(conn,
  6829. 500,
  6830. "Error: CGI program sent malformed or too big "
  6831. "(>%u bytes) HTTP headers: [%.*s]",
  6832. (unsigned)buflen,
  6833. data_len,
  6834. buf);
  6835. }
  6836. goto done;
  6837. }
  6838. pbuf = buf;
  6839. buf[headers_len - 1] = '\0';
  6840. parse_http_headers(&pbuf, &ri);
  6841. /* Make up and send the status line */
  6842. status_text = "OK";
  6843. if ((status = get_header(&ri, "Status")) != NULL) {
  6844. conn->status_code = atoi(status);
  6845. status_text = status;
  6846. while (isdigit(*(const unsigned char *)status_text)
  6847. || *status_text == ' ') {
  6848. status_text++;
  6849. }
  6850. } else if (get_header(&ri, "Location") != NULL) {
  6851. conn->status_code = 302;
  6852. } else {
  6853. conn->status_code = 200;
  6854. }
  6855. connection_state = get_header(&ri, "Connection");
  6856. if (!header_has_option(connection_state, "keep-alive")) {
  6857. conn->must_close = 1;
  6858. }
  6859. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6860. /* Send headers */
  6861. for (i = 0; i < ri.num_headers; i++) {
  6862. mg_printf(conn,
  6863. "%s: %s\r\n",
  6864. ri.http_headers[i].name,
  6865. ri.http_headers[i].value);
  6866. }
  6867. mg_write(conn, "\r\n", 2);
  6868. /* Send chunk of data that may have been read after the headers */
  6869. conn->num_bytes_sent +=
  6870. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6871. /* Read the rest of CGI output and send to the client */
  6872. send_file_data(conn, &fout, 0, INT64_MAX);
  6873. done:
  6874. mg_free(blk.var);
  6875. mg_free(blk.buf);
  6876. if (pid != (pid_t)-1) {
  6877. kill(pid, SIGKILL);
  6878. #if !defined(_WIN32)
  6879. {
  6880. int st;
  6881. while (waitpid(pid, &st, 0) != -1)
  6882. ; /* clean zombies */
  6883. }
  6884. #endif
  6885. }
  6886. if (fdin[0] != -1) {
  6887. close(fdin[0]);
  6888. }
  6889. if (fdout[1] != -1) {
  6890. close(fdout[1]);
  6891. }
  6892. if (in != NULL) {
  6893. fclose(in);
  6894. } else if (fdin[1] != -1) {
  6895. close(fdin[1]);
  6896. }
  6897. if (out != NULL) {
  6898. fclose(out);
  6899. } else if (fdout[0] != -1) {
  6900. close(fdout[0]);
  6901. }
  6902. if (err != NULL) {
  6903. fclose(err);
  6904. } else if (fderr[0] != -1) {
  6905. close(fderr[0]);
  6906. }
  6907. if (buf != NULL) {
  6908. mg_free(buf);
  6909. }
  6910. }
  6911. #endif /* !NO_CGI */
  6912. #if !defined(NO_FILES)
  6913. static void
  6914. mkcol(struct mg_connection *conn, const char *path)
  6915. {
  6916. int rc, body_len;
  6917. struct de de;
  6918. char date[64];
  6919. time_t curtime = time(NULL);
  6920. if (conn == NULL) {
  6921. return;
  6922. }
  6923. /* TODO (mid): Check the send_http_error situations in this function */
  6924. memset(&de.file, 0, sizeof(de.file));
  6925. if (!mg_stat(conn, path, &de.file)) {
  6926. mg_cry(conn,
  6927. "%s: mg_stat(%s) failed: %s",
  6928. __func__,
  6929. path,
  6930. strerror(ERRNO));
  6931. }
  6932. if (de.file.last_modified) {
  6933. /* TODO (high): This check does not seem to make any sense ! */
  6934. send_http_error(
  6935. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6936. return;
  6937. }
  6938. body_len = conn->data_len - conn->request_len;
  6939. if (body_len > 0) {
  6940. send_http_error(
  6941. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6942. return;
  6943. }
  6944. rc = mg_mkdir(conn, path, 0755);
  6945. if (rc == 0) {
  6946. conn->status_code = 201;
  6947. gmt_time_string(date, sizeof(date), &curtime);
  6948. mg_printf(conn,
  6949. "HTTP/1.1 %d Created\r\n"
  6950. "Date: %s\r\n",
  6951. conn->status_code,
  6952. date);
  6953. send_static_cache_header(conn);
  6954. mg_printf(conn,
  6955. "Content-Length: 0\r\n"
  6956. "Connection: %s\r\n\r\n",
  6957. suggest_connection_header(conn));
  6958. } else if (rc == -1) {
  6959. if (errno == EEXIST) {
  6960. send_http_error(
  6961. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6962. } else if (errno == EACCES) {
  6963. send_http_error(
  6964. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6965. } else if (errno == ENOENT) {
  6966. send_http_error(
  6967. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6968. } else {
  6969. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6970. }
  6971. }
  6972. }
  6973. static void
  6974. put_file(struct mg_connection *conn, const char *path)
  6975. {
  6976. struct file file = STRUCT_FILE_INITIALIZER;
  6977. const char *range;
  6978. int64_t r1, r2;
  6979. int rc;
  6980. char date[64];
  6981. time_t curtime = time(NULL);
  6982. if (conn == NULL) {
  6983. return;
  6984. }
  6985. if (mg_stat(conn, path, &file)) {
  6986. /* File already exists */
  6987. conn->status_code = 200;
  6988. if (file.is_directory) {
  6989. /* This is an already existing directory,
  6990. * so there is nothing to do for the server. */
  6991. rc = 0;
  6992. } else {
  6993. /* File exists and is not a directory. */
  6994. /* Can it be replaced? */
  6995. if (file.membuf != NULL) {
  6996. /* This is an "in-memory" file, that can not be replaced */
  6997. send_http_error(
  6998. conn,
  6999. 405,
  7000. "Error: Put not possible\nReplacing %s is not supported",
  7001. path);
  7002. return;
  7003. }
  7004. /* Check if the server may write this file */
  7005. if (access(path, W_OK) == 0) {
  7006. /* Access granted */
  7007. conn->status_code = 200;
  7008. rc = 1;
  7009. } else {
  7010. send_http_error(
  7011. conn,
  7012. 403,
  7013. "Error: Put not possible\nReplacing %s is not allowed",
  7014. path);
  7015. return;
  7016. }
  7017. }
  7018. } else {
  7019. /* File should be created */
  7020. conn->status_code = 201;
  7021. rc = put_dir(conn, path);
  7022. }
  7023. if (rc == 0) {
  7024. /* put_dir returns 0 if path is a directory */
  7025. gmt_time_string(date, sizeof(date), &curtime);
  7026. mg_printf(conn,
  7027. "HTTP/1.1 %d %s\r\n",
  7028. conn->status_code,
  7029. mg_get_response_code_text(NULL, conn->status_code));
  7030. send_no_cache_header(conn);
  7031. mg_printf(conn,
  7032. "Date: %s\r\n"
  7033. "Content-Length: 0\r\n"
  7034. "Connection: %s\r\n\r\n",
  7035. date,
  7036. suggest_connection_header(conn));
  7037. /* Request to create a directory has been fulfilled successfully.
  7038. * No need to put a file. */
  7039. return;
  7040. }
  7041. if (rc == -1) {
  7042. /* put_dir returns -1 if the path is too long */
  7043. send_http_error(conn,
  7044. 414,
  7045. "Error: Path too long\nput_dir(%s): %s",
  7046. path,
  7047. strerror(ERRNO));
  7048. return;
  7049. }
  7050. if (rc == -2) {
  7051. /* put_dir returns -2 if the directory can not be created */
  7052. send_http_error(conn,
  7053. 500,
  7054. "Error: Can not create directory\nput_dir(%s): %s",
  7055. path,
  7056. strerror(ERRNO));
  7057. return;
  7058. }
  7059. /* A file should be created or overwritten. */
  7060. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7061. mg_fclose(&file);
  7062. send_http_error(conn,
  7063. 500,
  7064. "Error: Can not create file\nfopen(%s): %s",
  7065. path,
  7066. strerror(ERRNO));
  7067. return;
  7068. }
  7069. fclose_on_exec(&file, conn);
  7070. range = mg_get_header(conn, "Content-Range");
  7071. r1 = r2 = 0;
  7072. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7073. conn->status_code = 206; /* Partial content */
  7074. fseeko(file.fp, r1, SEEK_SET);
  7075. }
  7076. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7077. /* forward_body_data failed.
  7078. * The error code has already been sent to the client,
  7079. * and conn->status_code is already set. */
  7080. mg_fclose(&file);
  7081. return;
  7082. }
  7083. gmt_time_string(date, sizeof(date), &curtime);
  7084. mg_printf(conn,
  7085. "HTTP/1.1 %d %s\r\n",
  7086. conn->status_code,
  7087. mg_get_response_code_text(NULL, conn->status_code));
  7088. send_no_cache_header(conn);
  7089. mg_printf(conn,
  7090. "Date: %s\r\n"
  7091. "Content-Length: 0\r\n"
  7092. "Connection: %s\r\n\r\n",
  7093. date,
  7094. suggest_connection_header(conn));
  7095. mg_fclose(&file);
  7096. }
  7097. static void
  7098. delete_file(struct mg_connection *conn, const char *path)
  7099. {
  7100. struct de de;
  7101. memset(&de.file, 0, sizeof(de.file));
  7102. if (!mg_stat(conn, path, &de.file)) {
  7103. /* mg_stat returns 0 if the file does not exist */
  7104. send_http_error(conn,
  7105. 404,
  7106. "Error: Cannot delete file\nFile %s not found",
  7107. path);
  7108. return;
  7109. }
  7110. if (de.file.membuf != NULL) {
  7111. /* the file is cached in memory */
  7112. send_http_error(
  7113. conn,
  7114. 405,
  7115. "Error: Delete not possible\nDeleting %s is not supported",
  7116. path);
  7117. return;
  7118. }
  7119. if (de.file.is_directory) {
  7120. if (remove_directory(conn, path)) {
  7121. /* Delete is successful: Return 204 without content. */
  7122. send_http_error(conn, 204, "%s", "");
  7123. } else {
  7124. /* Delete is not successful: Return 500 (Server error). */
  7125. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7126. }
  7127. return;
  7128. }
  7129. /* This is an existing file (not a directory).
  7130. * Check if write permission is granted. */
  7131. if (access(path, W_OK) != 0) {
  7132. /* File is read only */
  7133. send_http_error(
  7134. conn,
  7135. 403,
  7136. "Error: Delete not possible\nDeleting %s is not allowed",
  7137. path);
  7138. return;
  7139. }
  7140. /* Try to delete it. */
  7141. if (mg_remove(conn, path) == 0) {
  7142. /* Delete was successful: Return 204 without content. */
  7143. send_http_error(conn, 204, "%s", "");
  7144. } else {
  7145. /* Delete not successful (file locked). */
  7146. send_http_error(conn,
  7147. 423,
  7148. "Error: Cannot delete file\nremove(%s): %s",
  7149. path,
  7150. strerror(ERRNO));
  7151. }
  7152. }
  7153. #endif /* !NO_FILES */
  7154. static void
  7155. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7156. static void
  7157. do_ssi_include(struct mg_connection *conn,
  7158. const char *ssi,
  7159. char *tag,
  7160. int include_level)
  7161. {
  7162. char file_name[MG_BUF_LEN], path[512], *p;
  7163. struct file file = STRUCT_FILE_INITIALIZER;
  7164. size_t len;
  7165. int truncated = 0;
  7166. if (conn == NULL) {
  7167. return;
  7168. }
  7169. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7170. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7171. * always < MG_BUF_LEN. */
  7172. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7173. /* File name is relative to the webserver root */
  7174. file_name[511] = 0;
  7175. (void)mg_snprintf(conn,
  7176. &truncated,
  7177. path,
  7178. sizeof(path),
  7179. "%s/%s",
  7180. conn->ctx->config[DOCUMENT_ROOT],
  7181. file_name);
  7182. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7183. /* File name is relative to the webserver working directory
  7184. * or it is absolute system path */
  7185. file_name[511] = 0;
  7186. (void)
  7187. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7188. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7189. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7190. /* File name is relative to the currect document */
  7191. file_name[511] = 0;
  7192. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7193. if (!truncated) {
  7194. if ((p = strrchr(path, '/')) != NULL) {
  7195. p[1] = '\0';
  7196. }
  7197. len = strlen(path);
  7198. (void)mg_snprintf(conn,
  7199. &truncated,
  7200. path + len,
  7201. sizeof(path) - len,
  7202. "%s",
  7203. file_name);
  7204. }
  7205. } else {
  7206. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7207. return;
  7208. }
  7209. if (truncated) {
  7210. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7211. return;
  7212. }
  7213. if (!mg_fopen(conn, path, "rb", &file)) {
  7214. mg_cry(conn,
  7215. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7216. tag,
  7217. path,
  7218. strerror(ERRNO));
  7219. } else {
  7220. fclose_on_exec(&file, conn);
  7221. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7222. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7223. path) > 0) {
  7224. send_ssi_file(conn, path, &file, include_level + 1);
  7225. } else {
  7226. send_file_data(conn, &file, 0, INT64_MAX);
  7227. }
  7228. mg_fclose(&file);
  7229. }
  7230. }
  7231. #if !defined(NO_POPEN)
  7232. static void
  7233. do_ssi_exec(struct mg_connection *conn, char *tag)
  7234. {
  7235. char cmd[1024] = "";
  7236. struct file file = STRUCT_FILE_INITIALIZER;
  7237. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7238. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7239. } else {
  7240. cmd[1023] = 0;
  7241. if ((file.fp = popen(cmd, "r")) == NULL) {
  7242. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7243. } else {
  7244. send_file_data(conn, &file, 0, INT64_MAX);
  7245. pclose(file.fp);
  7246. }
  7247. }
  7248. }
  7249. #endif /* !NO_POPEN */
  7250. static int
  7251. mg_fgetc(struct file *filep, int offset)
  7252. {
  7253. if (filep == NULL) {
  7254. return EOF;
  7255. }
  7256. if (filep->membuf != NULL && offset >= 0
  7257. && ((unsigned int)(offset)) < filep->size) {
  7258. return ((const unsigned char *)filep->membuf)[offset];
  7259. } else if (filep->fp != NULL) {
  7260. return fgetc(filep->fp);
  7261. } else {
  7262. return EOF;
  7263. }
  7264. }
  7265. static void
  7266. send_ssi_file(struct mg_connection *conn,
  7267. const char *path,
  7268. struct file *filep,
  7269. int include_level)
  7270. {
  7271. char buf[MG_BUF_LEN];
  7272. int ch, offset, len, in_ssi_tag;
  7273. if (include_level > 10) {
  7274. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7275. return;
  7276. }
  7277. in_ssi_tag = len = offset = 0;
  7278. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7279. if (in_ssi_tag && ch == '>') {
  7280. in_ssi_tag = 0;
  7281. buf[len++] = (char)ch;
  7282. buf[len] = '\0';
  7283. /* assert(len <= (int) sizeof(buf)); */
  7284. if (len > (int)sizeof(buf)) {
  7285. break;
  7286. }
  7287. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7288. /* Not an SSI tag, pass it */
  7289. (void)mg_write(conn, buf, (size_t)len);
  7290. } else {
  7291. if (!memcmp(buf + 5, "include", 7)) {
  7292. do_ssi_include(conn, path, buf + 12, include_level);
  7293. #if !defined(NO_POPEN)
  7294. } else if (!memcmp(buf + 5, "exec", 4)) {
  7295. do_ssi_exec(conn, buf + 9);
  7296. #endif /* !NO_POPEN */
  7297. } else {
  7298. mg_cry(conn,
  7299. "%s: unknown SSI "
  7300. "command: \"%s\"",
  7301. path,
  7302. buf);
  7303. }
  7304. }
  7305. len = 0;
  7306. } else if (in_ssi_tag) {
  7307. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7308. /* Not an SSI tag */
  7309. in_ssi_tag = 0;
  7310. } else if (len == (int)sizeof(buf) - 2) {
  7311. mg_cry(conn, "%s: SSI tag is too large", path);
  7312. len = 0;
  7313. }
  7314. buf[len++] = (char)(ch & 0xff);
  7315. } else if (ch == '<') {
  7316. in_ssi_tag = 1;
  7317. if (len > 0) {
  7318. mg_write(conn, buf, (size_t)len);
  7319. }
  7320. len = 0;
  7321. buf[len++] = (char)(ch & 0xff);
  7322. } else {
  7323. buf[len++] = (char)(ch & 0xff);
  7324. if (len == (int)sizeof(buf)) {
  7325. mg_write(conn, buf, (size_t)len);
  7326. len = 0;
  7327. }
  7328. }
  7329. }
  7330. /* Send the rest of buffered data */
  7331. if (len > 0) {
  7332. mg_write(conn, buf, (size_t)len);
  7333. }
  7334. }
  7335. static void
  7336. handle_ssi_file_request(struct mg_connection *conn,
  7337. const char *path,
  7338. struct file *filep)
  7339. {
  7340. char date[64];
  7341. time_t curtime = time(NULL);
  7342. const char *cors1, *cors2, *cors3;
  7343. if (conn == NULL || path == NULL || filep == NULL) {
  7344. return;
  7345. }
  7346. if (mg_get_header(conn, "Origin")) {
  7347. /* Cross-origin resource sharing (CORS). */
  7348. cors1 = "Access-Control-Allow-Origin: ";
  7349. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7350. cors3 = "\r\n";
  7351. } else {
  7352. cors1 = cors2 = cors3 = "";
  7353. }
  7354. if (!mg_fopen(conn, path, "rb", filep)) {
  7355. /* File exists (precondition for calling this function),
  7356. * but can not be opened by the server. */
  7357. send_http_error(conn,
  7358. 500,
  7359. "Error: Cannot read file\nfopen(%s): %s",
  7360. path,
  7361. strerror(ERRNO));
  7362. } else {
  7363. conn->must_close = 1;
  7364. gmt_time_string(date, sizeof(date), &curtime);
  7365. fclose_on_exec(filep, conn);
  7366. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7367. send_no_cache_header(conn);
  7368. mg_printf(conn,
  7369. "%s%s%s"
  7370. "Date: %s\r\n"
  7371. "Content-Type: text/html\r\n"
  7372. "Connection: %s\r\n\r\n",
  7373. cors1,
  7374. cors2,
  7375. cors3,
  7376. date,
  7377. suggest_connection_header(conn));
  7378. send_ssi_file(conn, path, filep, 0);
  7379. mg_fclose(filep);
  7380. }
  7381. }
  7382. #if !defined(NO_FILES)
  7383. static void
  7384. send_options(struct mg_connection *conn)
  7385. {
  7386. char date[64];
  7387. time_t curtime = time(NULL);
  7388. if (!conn) {
  7389. return;
  7390. }
  7391. conn->status_code = 200;
  7392. conn->must_close = 1;
  7393. gmt_time_string(date, sizeof(date), &curtime);
  7394. mg_printf(conn,
  7395. "HTTP/1.1 200 OK\r\n"
  7396. "Date: %s\r\n"
  7397. /* TODO: "Cache-Control" (?) */
  7398. "Connection: %s\r\n"
  7399. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7400. "PROPFIND, MKCOL\r\n"
  7401. "DAV: 1\r\n\r\n",
  7402. date,
  7403. suggest_connection_header(conn));
  7404. }
  7405. /* Writes PROPFIND properties for a collection element */
  7406. static void
  7407. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7408. {
  7409. char mtime[64];
  7410. if (conn == NULL || uri == NULL || filep == NULL) {
  7411. return;
  7412. }
  7413. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7414. conn->num_bytes_sent +=
  7415. mg_printf(conn,
  7416. "<d:response>"
  7417. "<d:href>%s</d:href>"
  7418. "<d:propstat>"
  7419. "<d:prop>"
  7420. "<d:resourcetype>%s</d:resourcetype>"
  7421. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7422. "<d:getlastmodified>%s</d:getlastmodified>"
  7423. "</d:prop>"
  7424. "<d:status>HTTP/1.1 200 OK</d:status>"
  7425. "</d:propstat>"
  7426. "</d:response>\n",
  7427. uri,
  7428. filep->is_directory ? "<d:collection/>" : "",
  7429. filep->size,
  7430. mtime);
  7431. }
  7432. static void
  7433. print_dav_dir_entry(struct de *de, void *data)
  7434. {
  7435. char href[PATH_MAX];
  7436. char href_encoded[PATH_MAX * 3 /* worst case */];
  7437. int truncated;
  7438. struct mg_connection *conn = (struct mg_connection *)data;
  7439. if (!de || !conn) {
  7440. return;
  7441. }
  7442. mg_snprintf(conn,
  7443. &truncated,
  7444. href,
  7445. sizeof(href),
  7446. "%s%s",
  7447. conn->request_info.local_uri,
  7448. de->file_name);
  7449. if (!truncated) {
  7450. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7451. print_props(conn, href_encoded, &de->file);
  7452. }
  7453. }
  7454. static void
  7455. handle_propfind(struct mg_connection *conn,
  7456. const char *path,
  7457. struct file *filep)
  7458. {
  7459. const char *depth = mg_get_header(conn, "Depth");
  7460. char date[64];
  7461. time_t curtime = time(NULL);
  7462. gmt_time_string(date, sizeof(date), &curtime);
  7463. if (!conn || !path || !filep || !conn->ctx) {
  7464. return;
  7465. }
  7466. conn->must_close = 1;
  7467. conn->status_code = 207;
  7468. mg_printf(conn,
  7469. "HTTP/1.1 207 Multi-Status\r\n"
  7470. "Date: %s\r\n",
  7471. date);
  7472. send_static_cache_header(conn);
  7473. mg_printf(conn,
  7474. "Connection: %s\r\n"
  7475. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7476. suggest_connection_header(conn));
  7477. conn->num_bytes_sent +=
  7478. mg_printf(conn,
  7479. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7480. "<d:multistatus xmlns:d='DAV:'>\n");
  7481. /* Print properties for the requested resource itself */
  7482. print_props(conn, conn->request_info.local_uri, filep);
  7483. /* If it is a directory, print directory entries too if Depth is not 0 */
  7484. if (filep && filep->is_directory
  7485. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7486. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7487. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7488. }
  7489. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7490. }
  7491. #endif
  7492. void
  7493. mg_lock_connection(struct mg_connection *conn)
  7494. {
  7495. if (conn) {
  7496. (void)pthread_mutex_lock(&conn->mutex);
  7497. }
  7498. }
  7499. void
  7500. mg_unlock_connection(struct mg_connection *conn)
  7501. {
  7502. if (conn) {
  7503. (void)pthread_mutex_unlock(&conn->mutex);
  7504. }
  7505. }
  7506. void
  7507. mg_lock_context(struct mg_context *ctx)
  7508. {
  7509. if (ctx) {
  7510. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7511. }
  7512. }
  7513. void
  7514. mg_unlock_context(struct mg_context *ctx)
  7515. {
  7516. if (ctx) {
  7517. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7518. }
  7519. }
  7520. #if defined(USE_TIMERS)
  7521. #include "timer.inl"
  7522. #endif /* USE_TIMERS */
  7523. #ifdef USE_LUA
  7524. #include "mod_lua.inl"
  7525. #endif /* USE_LUA */
  7526. #ifdef USE_DUKTAPE
  7527. #include "mod_duktape.inl"
  7528. #endif /* USE_DUKTAPE */
  7529. #if defined(USE_WEBSOCKET)
  7530. /* START OF SHA-1 code
  7531. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7532. #define SHA1HANDSOFF
  7533. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7534. *
  7535. * #if defined(__sun)
  7536. * #include "solarisfixes.h"
  7537. * #endif
  7538. */
  7539. static int
  7540. is_big_endian(void)
  7541. {
  7542. static const int n = 1;
  7543. return ((char *)&n)[0] == 0;
  7544. }
  7545. union char64long16 {
  7546. unsigned char c[64];
  7547. uint32_t l[16];
  7548. };
  7549. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7550. static uint32_t
  7551. blk0(union char64long16 *block, int i)
  7552. {
  7553. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7554. if (!is_big_endian()) {
  7555. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7556. | (rol(block->l[i], 8) & 0x00FF00FF);
  7557. }
  7558. return block->l[i];
  7559. }
  7560. #define blk(i) \
  7561. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7562. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7563. 1))
  7564. #define R0(v, w, x, y, z, i) \
  7565. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7566. w = rol(w, 30);
  7567. #define R1(v, w, x, y, z, i) \
  7568. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7569. w = rol(w, 30);
  7570. #define R2(v, w, x, y, z, i) \
  7571. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7572. w = rol(w, 30);
  7573. #define R3(v, w, x, y, z, i) \
  7574. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7575. w = rol(w, 30);
  7576. #define R4(v, w, x, y, z, i) \
  7577. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7578. w = rol(w, 30);
  7579. typedef struct {
  7580. uint32_t state[5];
  7581. uint32_t count[2];
  7582. unsigned char buffer[64];
  7583. } SHA1_CTX;
  7584. static void
  7585. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7586. {
  7587. uint32_t a, b, c, d, e;
  7588. union char64long16 block[1];
  7589. memcpy(block, buffer, 64);
  7590. a = state[0];
  7591. b = state[1];
  7592. c = state[2];
  7593. d = state[3];
  7594. e = state[4];
  7595. R0(a, b, c, d, e, 0);
  7596. R0(e, a, b, c, d, 1);
  7597. R0(d, e, a, b, c, 2);
  7598. R0(c, d, e, a, b, 3);
  7599. R0(b, c, d, e, a, 4);
  7600. R0(a, b, c, d, e, 5);
  7601. R0(e, a, b, c, d, 6);
  7602. R0(d, e, a, b, c, 7);
  7603. R0(c, d, e, a, b, 8);
  7604. R0(b, c, d, e, a, 9);
  7605. R0(a, b, c, d, e, 10);
  7606. R0(e, a, b, c, d, 11);
  7607. R0(d, e, a, b, c, 12);
  7608. R0(c, d, e, a, b, 13);
  7609. R0(b, c, d, e, a, 14);
  7610. R0(a, b, c, d, e, 15);
  7611. R1(e, a, b, c, d, 16);
  7612. R1(d, e, a, b, c, 17);
  7613. R1(c, d, e, a, b, 18);
  7614. R1(b, c, d, e, a, 19);
  7615. R2(a, b, c, d, e, 20);
  7616. R2(e, a, b, c, d, 21);
  7617. R2(d, e, a, b, c, 22);
  7618. R2(c, d, e, a, b, 23);
  7619. R2(b, c, d, e, a, 24);
  7620. R2(a, b, c, d, e, 25);
  7621. R2(e, a, b, c, d, 26);
  7622. R2(d, e, a, b, c, 27);
  7623. R2(c, d, e, a, b, 28);
  7624. R2(b, c, d, e, a, 29);
  7625. R2(a, b, c, d, e, 30);
  7626. R2(e, a, b, c, d, 31);
  7627. R2(d, e, a, b, c, 32);
  7628. R2(c, d, e, a, b, 33);
  7629. R2(b, c, d, e, a, 34);
  7630. R2(a, b, c, d, e, 35);
  7631. R2(e, a, b, c, d, 36);
  7632. R2(d, e, a, b, c, 37);
  7633. R2(c, d, e, a, b, 38);
  7634. R2(b, c, d, e, a, 39);
  7635. R3(a, b, c, d, e, 40);
  7636. R3(e, a, b, c, d, 41);
  7637. R3(d, e, a, b, c, 42);
  7638. R3(c, d, e, a, b, 43);
  7639. R3(b, c, d, e, a, 44);
  7640. R3(a, b, c, d, e, 45);
  7641. R3(e, a, b, c, d, 46);
  7642. R3(d, e, a, b, c, 47);
  7643. R3(c, d, e, a, b, 48);
  7644. R3(b, c, d, e, a, 49);
  7645. R3(a, b, c, d, e, 50);
  7646. R3(e, a, b, c, d, 51);
  7647. R3(d, e, a, b, c, 52);
  7648. R3(c, d, e, a, b, 53);
  7649. R3(b, c, d, e, a, 54);
  7650. R3(a, b, c, d, e, 55);
  7651. R3(e, a, b, c, d, 56);
  7652. R3(d, e, a, b, c, 57);
  7653. R3(c, d, e, a, b, 58);
  7654. R3(b, c, d, e, a, 59);
  7655. R4(a, b, c, d, e, 60);
  7656. R4(e, a, b, c, d, 61);
  7657. R4(d, e, a, b, c, 62);
  7658. R4(c, d, e, a, b, 63);
  7659. R4(b, c, d, e, a, 64);
  7660. R4(a, b, c, d, e, 65);
  7661. R4(e, a, b, c, d, 66);
  7662. R4(d, e, a, b, c, 67);
  7663. R4(c, d, e, a, b, 68);
  7664. R4(b, c, d, e, a, 69);
  7665. R4(a, b, c, d, e, 70);
  7666. R4(e, a, b, c, d, 71);
  7667. R4(d, e, a, b, c, 72);
  7668. R4(c, d, e, a, b, 73);
  7669. R4(b, c, d, e, a, 74);
  7670. R4(a, b, c, d, e, 75);
  7671. R4(e, a, b, c, d, 76);
  7672. R4(d, e, a, b, c, 77);
  7673. R4(c, d, e, a, b, 78);
  7674. R4(b, c, d, e, a, 79);
  7675. state[0] += a;
  7676. state[1] += b;
  7677. state[2] += c;
  7678. state[3] += d;
  7679. state[4] += e;
  7680. a = b = c = d = e = 0;
  7681. memset(block, '\0', sizeof(block));
  7682. }
  7683. static void
  7684. SHA1Init(SHA1_CTX *context)
  7685. {
  7686. context->state[0] = 0x67452301;
  7687. context->state[1] = 0xEFCDAB89;
  7688. context->state[2] = 0x98BADCFE;
  7689. context->state[3] = 0x10325476;
  7690. context->state[4] = 0xC3D2E1F0;
  7691. context->count[0] = context->count[1] = 0;
  7692. }
  7693. static void
  7694. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7695. {
  7696. uint32_t i, j;
  7697. j = context->count[0];
  7698. if ((context->count[0] += len << 3) < j) {
  7699. context->count[1]++;
  7700. }
  7701. context->count[1] += (len >> 29);
  7702. j = (j >> 3) & 63;
  7703. if ((j + len) > 63) {
  7704. memcpy(&context->buffer[j], data, (i = 64 - j));
  7705. SHA1Transform(context->state, context->buffer);
  7706. for (; i + 63 < len; i += 64) {
  7707. SHA1Transform(context->state, &data[i]);
  7708. }
  7709. j = 0;
  7710. } else
  7711. i = 0;
  7712. memcpy(&context->buffer[j], &data[i], len - i);
  7713. }
  7714. static void
  7715. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7716. {
  7717. unsigned i;
  7718. unsigned char finalcount[8], c;
  7719. for (i = 0; i < 8; i++) {
  7720. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7721. >> ((3 - (i & 3)) * 8)) & 255);
  7722. }
  7723. c = 0200;
  7724. SHA1Update(context, &c, 1);
  7725. while ((context->count[0] & 504) != 448) {
  7726. c = 0000;
  7727. SHA1Update(context, &c, 1);
  7728. }
  7729. SHA1Update(context, finalcount, 8);
  7730. for (i = 0; i < 20; i++) {
  7731. digest[i] = (unsigned char)((context->state[i >> 2]
  7732. >> ((3 - (i & 3)) * 8)) & 255);
  7733. }
  7734. memset(context, '\0', sizeof(*context));
  7735. memset(&finalcount, '\0', sizeof(finalcount));
  7736. }
  7737. /* END OF SHA1 CODE */
  7738. static int
  7739. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7740. {
  7741. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7742. const char *protocol = NULL;
  7743. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7744. SHA1_CTX sha_ctx;
  7745. int truncated;
  7746. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7747. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7748. if (truncated) {
  7749. conn->must_close = 1;
  7750. return 0;
  7751. }
  7752. SHA1Init(&sha_ctx);
  7753. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7754. SHA1Final((unsigned char *)sha, &sha_ctx);
  7755. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7756. mg_printf(conn,
  7757. "HTTP/1.1 101 Switching Protocols\r\n"
  7758. "Upgrade: websocket\r\n"
  7759. "Connection: Upgrade\r\n"
  7760. "Sec-WebSocket-Accept: %s\r\n",
  7761. b64_sha);
  7762. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7763. if (protocol) {
  7764. /* The protocol is a comma seperated list of names. */
  7765. /* The server must only return one value from this list. */
  7766. /* First check if it is a list or just a single value. */
  7767. const char *sep = strchr(protocol, ',');
  7768. if (sep == NULL) {
  7769. /* Just a single protocol -> accept it. */
  7770. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7771. } else {
  7772. /* Multiple protocols -> accept the first one. */
  7773. /* This is just a quick fix if the client offers multiple
  7774. * protocols. In order to get the behavior intended by
  7775. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7776. * required to have a list of websocket subprotocols accepted
  7777. * by the server. Then the server must either select a subprotocol
  7778. * supported by client and server, or the server has to abort the
  7779. * handshake by not returning a Sec-Websocket-Protocol header if
  7780. * no subprotocol is acceptable.
  7781. */
  7782. mg_printf(conn,
  7783. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7784. (int)(sep - protocol),
  7785. protocol);
  7786. }
  7787. /* TODO: Real subprotocol negotiation instead of just taking the first
  7788. * websocket subprotocol suggested by the client. */
  7789. } else {
  7790. mg_printf(conn, "%s", "\r\n");
  7791. }
  7792. return 1;
  7793. }
  7794. static void
  7795. read_websocket(struct mg_connection *conn,
  7796. mg_websocket_data_handler ws_data_handler,
  7797. void *callback_data)
  7798. {
  7799. /* Pointer to the beginning of the portion of the incoming websocket
  7800. * message queue.
  7801. * The original websocket upgrade request is never removed, so the queue
  7802. * begins after it. */
  7803. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7804. int n, error, exit_by_callback;
  7805. /* body_len is the length of the entire queue in bytes
  7806. * len is the length of the current message
  7807. * data_len is the length of the current message's data payload
  7808. * header_len is the length of the current message's header */
  7809. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7810. /* "The masking key is a 32-bit value chosen at random by the client."
  7811. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7812. */
  7813. unsigned char mask[4];
  7814. /* data points to the place where the message is stored when passed to
  7815. * the
  7816. * websocket_data callback. This is either mem on the stack, or a
  7817. * dynamically allocated buffer if it is too large. */
  7818. char mem[4096];
  7819. char *data = mem;
  7820. unsigned char mop; /* mask flag and opcode */
  7821. double timeout = -1.0;
  7822. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7823. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7824. }
  7825. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7826. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7827. }
  7828. mg_set_thread_name("wsock");
  7829. /* Loop continuously, reading messages from the socket, invoking the
  7830. * callback, and waiting repeatedly until an error occurs. */
  7831. while (!conn->ctx->stop_flag) {
  7832. header_len = 0;
  7833. assert(conn->data_len >= conn->request_len);
  7834. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7835. len = buf[1] & 127;
  7836. mask_len = (buf[1] & 128) ? 4 : 0;
  7837. if ((len < 126) && (body_len >= mask_len)) {
  7838. data_len = len;
  7839. header_len = 2 + mask_len;
  7840. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7841. header_len = 4 + mask_len;
  7842. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7843. } else if (body_len >= (10 + mask_len)) {
  7844. header_len = 10 + mask_len;
  7845. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7846. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7847. }
  7848. }
  7849. if (header_len > 0 && body_len >= header_len) {
  7850. /* Allocate space to hold websocket payload */
  7851. data = mem;
  7852. if (data_len > sizeof(mem)) {
  7853. data = (char *)mg_malloc(data_len);
  7854. if (data == NULL) {
  7855. /* Allocation failed, exit the loop and then close the
  7856. * connection */
  7857. mg_cry(conn, "websocket out of memory; closing connection");
  7858. break;
  7859. }
  7860. }
  7861. /* Copy the mask before we shift the queue and destroy it */
  7862. if (mask_len > 0) {
  7863. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7864. } else {
  7865. memset(mask, 0, sizeof(mask));
  7866. }
  7867. /* Read frame payload from the first message in the queue into
  7868. * data and advance the queue by moving the memory in place. */
  7869. assert(body_len >= header_len);
  7870. if (data_len + header_len > body_len) {
  7871. mop = buf[0]; /* current mask and opcode */
  7872. /* Overflow case */
  7873. len = body_len - header_len;
  7874. memcpy(data, buf + header_len, len);
  7875. error = 0;
  7876. while (len < data_len) {
  7877. n = pull(
  7878. NULL, conn, data + len, (int)(data_len - len), timeout);
  7879. if (n <= 0) {
  7880. error = 1;
  7881. break;
  7882. }
  7883. len += (size_t)n;
  7884. }
  7885. if (error) {
  7886. mg_cry(conn, "Websocket pull failed; closing connection");
  7887. break;
  7888. }
  7889. conn->data_len = conn->request_len;
  7890. } else {
  7891. mop = buf[0]; /* current mask and opcode, overwritten by
  7892. * memmove() */
  7893. /* Length of the message being read at the front of the
  7894. * queue */
  7895. len = data_len + header_len;
  7896. /* Copy the data payload into the data pointer for the
  7897. * callback */
  7898. memcpy(data, buf + header_len, data_len);
  7899. /* Move the queue forward len bytes */
  7900. memmove(buf, buf + len, body_len - len);
  7901. /* Mark the queue as advanced */
  7902. conn->data_len -= (int)len;
  7903. }
  7904. /* Apply mask if necessary */
  7905. if (mask_len > 0) {
  7906. for (i = 0; i < data_len; ++i) {
  7907. data[i] ^= mask[i & 3];
  7908. }
  7909. }
  7910. /* Exit the loop if callback signals to exit (server side),
  7911. * or "connection close" opcode received (client side). */
  7912. exit_by_callback = 0;
  7913. if ((ws_data_handler != NULL)
  7914. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7915. exit_by_callback = 1;
  7916. }
  7917. if (data != mem) {
  7918. mg_free(data);
  7919. }
  7920. if (exit_by_callback
  7921. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7922. /* Opcode == 8, connection close */
  7923. break;
  7924. }
  7925. /* Not breaking the loop, process next websocket frame. */
  7926. } else {
  7927. /* Read from the socket into the next available location in the
  7928. * message queue. */
  7929. if ((n = pull(NULL,
  7930. conn,
  7931. conn->buf + conn->data_len,
  7932. conn->buf_size - conn->data_len,
  7933. timeout)) <= 0) {
  7934. /* Error, no bytes read */
  7935. break;
  7936. }
  7937. conn->data_len += n;
  7938. }
  7939. }
  7940. mg_set_thread_name("worker");
  7941. }
  7942. static int
  7943. mg_websocket_write_exec(struct mg_connection *conn,
  7944. int opcode,
  7945. const char *data,
  7946. size_t dataLen,
  7947. uint32_t masking_key)
  7948. {
  7949. unsigned char header[14];
  7950. size_t headerLen = 1;
  7951. int retval = -1;
  7952. header[0] = 0x80 + (opcode & 0xF);
  7953. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7954. if (dataLen < 126) {
  7955. /* inline 7-bit length field */
  7956. header[1] = (unsigned char)dataLen;
  7957. headerLen = 2;
  7958. } else if (dataLen <= 0xFFFF) {
  7959. /* 16-bit length field */
  7960. uint16_t len = htons((uint16_t)dataLen);
  7961. header[1] = 126;
  7962. memcpy(header + 2, &len, 2);
  7963. headerLen = 4;
  7964. } else {
  7965. /* 64-bit length field */
  7966. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  7967. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  7968. header[1] = 127;
  7969. memcpy(header + 2, &len1, 4);
  7970. memcpy(header + 6, &len2, 4);
  7971. headerLen = 10;
  7972. }
  7973. if (masking_key) {
  7974. /* add mask */
  7975. header[1] |= 0x80;
  7976. memcpy(header + headerLen, &masking_key, 4);
  7977. headerLen += 4;
  7978. }
  7979. /* Note that POSIX/Winsock's send() is threadsafe
  7980. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7981. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7982. * push(), although that is only a problem if the packet is large or
  7983. * outgoing buffer is full). */
  7984. (void)mg_lock_connection(conn);
  7985. retval = mg_write(conn, header, headerLen);
  7986. if (dataLen > 0) {
  7987. retval = mg_write(conn, data, dataLen);
  7988. }
  7989. mg_unlock_connection(conn);
  7990. return retval;
  7991. }
  7992. int
  7993. mg_websocket_write(struct mg_connection *conn,
  7994. int opcode,
  7995. const char *data,
  7996. size_t dataLen)
  7997. {
  7998. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7999. }
  8000. static void
  8001. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8002. {
  8003. size_t i = 0;
  8004. i = 0;
  8005. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8006. /* Convert in 32 bit words, if data is 4 byte aligned */
  8007. while (i < (in_len - 3)) {
  8008. *(uint32_t *)(void *)(out + i) =
  8009. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8010. i += 4;
  8011. }
  8012. }
  8013. if (i != in_len) {
  8014. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8015. while (i < in_len) {
  8016. *(uint8_t *)(void *)(out + i) =
  8017. *(uint8_t *)(void *)(in + i)
  8018. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8019. i++;
  8020. }
  8021. }
  8022. }
  8023. int
  8024. mg_websocket_client_write(struct mg_connection *conn,
  8025. int opcode,
  8026. const char *data,
  8027. size_t dataLen)
  8028. {
  8029. int retval = -1;
  8030. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8031. uint32_t masking_key = (uint32_t)get_random();
  8032. if (masked_data == NULL) {
  8033. /* Return -1 in an error case */
  8034. mg_cry(conn,
  8035. "Cannot allocate buffer for masked websocket response: "
  8036. "Out of memory");
  8037. return -1;
  8038. }
  8039. mask_data(data, dataLen, masking_key, masked_data);
  8040. retval = mg_websocket_write_exec(
  8041. conn, opcode, masked_data, dataLen, masking_key);
  8042. mg_free(masked_data);
  8043. return retval;
  8044. }
  8045. static void
  8046. handle_websocket_request(struct mg_connection *conn,
  8047. const char *path,
  8048. int is_callback_resource,
  8049. mg_websocket_connect_handler ws_connect_handler,
  8050. mg_websocket_ready_handler ws_ready_handler,
  8051. mg_websocket_data_handler ws_data_handler,
  8052. mg_websocket_close_handler ws_close_handler,
  8053. void *cbData)
  8054. {
  8055. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8056. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8057. int lua_websock = 0;
  8058. #if !defined(USE_LUA)
  8059. (void)path;
  8060. #endif
  8061. /* Step 1: Check websocket protocol version. */
  8062. /* Step 1.1: Check Sec-WebSocket-Key. */
  8063. if (!websock_key) {
  8064. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8065. * requires a Sec-WebSocket-Key header.
  8066. */
  8067. /* It could be the hixie draft version
  8068. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8069. */
  8070. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8071. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8072. char key3[8];
  8073. if ((key1 != NULL) && (key2 != NULL)) {
  8074. /* This version uses 8 byte body data in a GET request */
  8075. conn->content_len = 8;
  8076. if (8 == mg_read(conn, key3, 8)) {
  8077. /* This is the hixie version */
  8078. send_http_error(conn,
  8079. 426,
  8080. "%s",
  8081. "Protocol upgrade to RFC 6455 required");
  8082. return;
  8083. }
  8084. }
  8085. /* This is an unknown version */
  8086. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8087. return;
  8088. }
  8089. /* Step 1.2: Check websocket protocol version. */
  8090. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8091. if (version == NULL || strcmp(version, "13") != 0) {
  8092. /* Reject wrong versions */
  8093. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8094. return;
  8095. }
  8096. /* Step 1.3: Could check for "Host", but we do not really nead this
  8097. * value for anything, so just ignore it. */
  8098. /* Step 2: If a callback is responsible, call it. */
  8099. if (is_callback_resource) {
  8100. if (ws_connect_handler != NULL
  8101. && ws_connect_handler(conn, cbData) != 0) {
  8102. /* C callback has returned non-zero, do not proceed with
  8103. * handshake.
  8104. */
  8105. /* Note that C callbacks are no longer called when Lua is
  8106. * responsible, so C can no longer filter callbacks for Lua. */
  8107. return;
  8108. }
  8109. }
  8110. #if defined(USE_LUA)
  8111. /* Step 3: No callback. Check if Lua is responsible. */
  8112. else {
  8113. /* Step 3.1: Check if Lua is responsible. */
  8114. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8115. lua_websock =
  8116. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8117. strlen(
  8118. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8119. path);
  8120. }
  8121. if (lua_websock) {
  8122. /* Step 3.2: Lua is responsible: call it. */
  8123. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8124. if (!conn->lua_websocket_state) {
  8125. /* Lua rejected the new client */
  8126. return;
  8127. }
  8128. }
  8129. }
  8130. #endif
  8131. /* Step 4: Check if there is a responsible websocket handler. */
  8132. if (!is_callback_resource && !lua_websock) {
  8133. /* There is no callback, an Lua is not responsible either. */
  8134. /* Reply with a 404 Not Found or with nothing at all?
  8135. * TODO (mid): check the websocket standards, how to reply to
  8136. * requests to invalid websocket addresses. */
  8137. send_http_error(conn, 404, "%s", "Not found");
  8138. return;
  8139. }
  8140. /* Step 5: The websocket connection has been accepted */
  8141. if (!send_websocket_handshake(conn, websock_key)) {
  8142. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8143. return;
  8144. }
  8145. /* Step 6: Call the ready handler */
  8146. if (is_callback_resource) {
  8147. if (ws_ready_handler != NULL) {
  8148. ws_ready_handler(conn, cbData);
  8149. }
  8150. #if defined(USE_LUA)
  8151. } else if (lua_websock) {
  8152. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8153. /* the ready handler returned false */
  8154. return;
  8155. }
  8156. #endif
  8157. }
  8158. /* Step 7: Enter the read loop */
  8159. if (is_callback_resource) {
  8160. read_websocket(conn, ws_data_handler, cbData);
  8161. #if defined(USE_LUA)
  8162. } else if (lua_websock) {
  8163. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8164. #endif
  8165. }
  8166. /* Step 8: Call the close handler */
  8167. if (ws_close_handler) {
  8168. ws_close_handler(conn, cbData);
  8169. }
  8170. }
  8171. static int
  8172. is_websocket_protocol(const struct mg_connection *conn)
  8173. {
  8174. const char *upgrade, *connection;
  8175. /* A websocket protocoll has the following HTTP headers:
  8176. *
  8177. * Connection: Upgrade
  8178. * Upgrade: Websocket
  8179. */
  8180. upgrade = mg_get_header(conn, "Upgrade");
  8181. if (upgrade == NULL) {
  8182. return 0; /* fail early, don't waste time checking other header
  8183. * fields
  8184. */
  8185. }
  8186. if (!mg_strcasestr(upgrade, "websocket")) {
  8187. return 0;
  8188. }
  8189. connection = mg_get_header(conn, "Connection");
  8190. if (connection == NULL) {
  8191. return 0;
  8192. }
  8193. if (!mg_strcasestr(connection, "upgrade")) {
  8194. return 0;
  8195. }
  8196. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8197. * "Sec-WebSocket-Version" are also required.
  8198. * Don't check them here, since even an unsupported websocket protocol
  8199. * request still IS a websocket request (in contrast to a standard HTTP
  8200. * request). It will fail later in handle_websocket_request.
  8201. */
  8202. return 1;
  8203. }
  8204. #endif /* !USE_WEBSOCKET */
  8205. static int
  8206. isbyte(int n)
  8207. {
  8208. return n >= 0 && n <= 255;
  8209. }
  8210. static int
  8211. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8212. {
  8213. int n, a, b, c, d, slash = 32, len = 0;
  8214. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8215. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8216. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8217. && slash < 33) {
  8218. len = n;
  8219. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8220. | (uint32_t)d;
  8221. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8222. }
  8223. return len;
  8224. }
  8225. static int
  8226. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8227. {
  8228. int throttle = 0;
  8229. struct vec vec, val;
  8230. uint32_t net, mask;
  8231. char mult;
  8232. double v;
  8233. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8234. mult = ',';
  8235. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8236. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8237. && mult != ',')) {
  8238. continue;
  8239. }
  8240. v *= (lowercase(&mult) == 'k')
  8241. ? 1024
  8242. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8243. if (vec.len == 1 && vec.ptr[0] == '*') {
  8244. throttle = (int)v;
  8245. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8246. if ((remote_ip & mask) == net) {
  8247. throttle = (int)v;
  8248. }
  8249. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8250. throttle = (int)v;
  8251. }
  8252. }
  8253. return throttle;
  8254. }
  8255. static uint32_t
  8256. get_remote_ip(const struct mg_connection *conn)
  8257. {
  8258. if (!conn) {
  8259. return 0;
  8260. }
  8261. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8262. }
  8263. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8264. #include "handle_form.inl"
  8265. #if defined(MG_LEGACY_INTERFACE)
  8266. /* Implement the deprecated mg_upload function by calling the new
  8267. * mg_handle_form_request function. While mg_upload could only handle
  8268. * HTML forms sent as POST request in multipart/form-data format
  8269. * containing only file input elements, mg_handle_form_request can
  8270. * handle all form input elements and all standard request methods. */
  8271. struct mg_upload_user_data {
  8272. struct mg_connection *conn;
  8273. const char *destination_dir;
  8274. int num_uploaded_files;
  8275. };
  8276. /* Helper function for deprecated mg_upload. */
  8277. static int
  8278. mg_upload_field_found(const char *key,
  8279. const char *filename,
  8280. char *path,
  8281. size_t pathlen,
  8282. void *user_data)
  8283. {
  8284. int truncated = 0;
  8285. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8286. (void)key;
  8287. if (!filename) {
  8288. mg_cry(fud->conn, "%s: No filename set", __func__);
  8289. return FORM_FIELD_STORAGE_ABORT;
  8290. }
  8291. mg_snprintf(fud->conn,
  8292. &truncated,
  8293. path,
  8294. pathlen - 1,
  8295. "%s/%s",
  8296. fud->destination_dir,
  8297. filename);
  8298. if (!truncated) {
  8299. mg_cry(fud->conn, "%s: File path too long", __func__);
  8300. return FORM_FIELD_STORAGE_ABORT;
  8301. }
  8302. return FORM_FIELD_STORAGE_STORE;
  8303. }
  8304. /* Helper function for deprecated mg_upload. */
  8305. static int
  8306. mg_upload_field_get(const char *key,
  8307. const char *value,
  8308. size_t value_size,
  8309. void *user_data)
  8310. {
  8311. /* Function should never be called */
  8312. (void)key;
  8313. (void)value;
  8314. (void)value_size;
  8315. (void)user_data;
  8316. return 0;
  8317. }
  8318. /* Helper function for deprecated mg_upload. */
  8319. static int
  8320. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8321. {
  8322. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8323. (void)file_size;
  8324. fud->num_uploaded_files++;
  8325. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8326. return 0;
  8327. }
  8328. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8329. int
  8330. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8331. {
  8332. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8333. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8334. mg_upload_field_get,
  8335. mg_upload_field_stored,
  8336. 0};
  8337. int ret;
  8338. fdh.user_data = (void *)&fud;
  8339. ret = mg_handle_form_request(conn, &fdh);
  8340. if (ret < 0) {
  8341. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8342. }
  8343. return fud.num_uploaded_files;
  8344. }
  8345. #endif
  8346. static int
  8347. get_first_ssl_listener_index(const struct mg_context *ctx)
  8348. {
  8349. unsigned int i;
  8350. int idx = -1;
  8351. if (ctx) {
  8352. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8353. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8354. }
  8355. }
  8356. return idx;
  8357. }
  8358. static void
  8359. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8360. {
  8361. char host[1025];
  8362. const char *host_header;
  8363. size_t hostlen;
  8364. host_header = mg_get_header(conn, "Host");
  8365. hostlen = sizeof(host);
  8366. if (host_header != NULL) {
  8367. char *pos;
  8368. mg_strlcpy(host, host_header, hostlen);
  8369. host[hostlen - 1] = '\0';
  8370. pos = strchr(host, ':');
  8371. if (pos != NULL) {
  8372. *pos = '\0';
  8373. }
  8374. } else {
  8375. /* Cannot get host from the Host: header.
  8376. * Fallback to our IP address. */
  8377. if (conn) {
  8378. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8379. }
  8380. }
  8381. /* Send host, port, uri and (if it exists) ?query_string */
  8382. if (conn) {
  8383. mg_printf(conn,
  8384. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8385. host,
  8386. #if defined(USE_IPV6)
  8387. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8388. == AF_INET6)
  8389. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8390. .lsa.sin6.sin6_port)
  8391. :
  8392. #endif
  8393. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8394. .lsa.sin.sin_port),
  8395. conn->request_info.local_uri,
  8396. (conn->request_info.query_string == NULL) ? "" : "?",
  8397. (conn->request_info.query_string == NULL)
  8398. ? ""
  8399. : conn->request_info.query_string);
  8400. }
  8401. }
  8402. static void
  8403. mg_set_handler_type(struct mg_context *ctx,
  8404. const char *uri,
  8405. int handler_type,
  8406. int is_delete_request,
  8407. mg_request_handler handler,
  8408. mg_websocket_connect_handler connect_handler,
  8409. mg_websocket_ready_handler ready_handler,
  8410. mg_websocket_data_handler data_handler,
  8411. mg_websocket_close_handler close_handler,
  8412. mg_authorization_handler auth_handler,
  8413. void *cbdata)
  8414. {
  8415. struct mg_handler_info *tmp_rh, **lastref;
  8416. size_t urilen = strlen(uri);
  8417. if (handler_type == WEBSOCKET_HANDLER) {
  8418. /* assert(handler == NULL); */
  8419. /* assert(is_delete_request || connect_handler!=NULL ||
  8420. * ready_handler!=NULL || data_handler!=NULL ||
  8421. * close_handler!=NULL);
  8422. */
  8423. /* assert(auth_handler == NULL); */
  8424. if (handler != NULL) {
  8425. return;
  8426. }
  8427. if (!is_delete_request && connect_handler == NULL
  8428. && ready_handler == NULL
  8429. && data_handler == NULL
  8430. && close_handler == NULL) {
  8431. return;
  8432. }
  8433. if (auth_handler != NULL) {
  8434. return;
  8435. }
  8436. } else if (handler_type == REQUEST_HANDLER) {
  8437. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8438. * data_handler==NULL && close_handler==NULL); */
  8439. /* assert(is_delete_request || (handler!=NULL));
  8440. */
  8441. /* assert(auth_handler == NULL); */
  8442. if (connect_handler != NULL || ready_handler != NULL
  8443. || data_handler != NULL
  8444. || close_handler != NULL) {
  8445. return;
  8446. }
  8447. if (!is_delete_request && (handler == NULL)) {
  8448. return;
  8449. }
  8450. if (auth_handler != NULL) {
  8451. return;
  8452. }
  8453. } else { /* AUTH_HANDLER */
  8454. /* assert(handler == NULL); */
  8455. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8456. * data_handler==NULL && close_handler==NULL); */
  8457. /* assert(auth_handler != NULL); */
  8458. if (handler != NULL) {
  8459. return;
  8460. }
  8461. if (connect_handler != NULL || ready_handler != NULL
  8462. || data_handler != NULL
  8463. || close_handler != NULL) {
  8464. return;
  8465. }
  8466. if (!is_delete_request && (auth_handler == NULL)) {
  8467. return;
  8468. }
  8469. }
  8470. if (!ctx) {
  8471. return;
  8472. }
  8473. mg_lock_context(ctx);
  8474. /* first try to find an existing handler */
  8475. lastref = &(ctx->handlers);
  8476. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8477. if (tmp_rh->handler_type == handler_type) {
  8478. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8479. if (!is_delete_request) {
  8480. /* update existing handler */
  8481. if (handler_type == REQUEST_HANDLER) {
  8482. tmp_rh->handler = handler;
  8483. } else if (handler_type == WEBSOCKET_HANDLER) {
  8484. tmp_rh->connect_handler = connect_handler;
  8485. tmp_rh->ready_handler = ready_handler;
  8486. tmp_rh->data_handler = data_handler;
  8487. tmp_rh->close_handler = close_handler;
  8488. } else { /* AUTH_HANDLER */
  8489. tmp_rh->auth_handler = auth_handler;
  8490. }
  8491. tmp_rh->cbdata = cbdata;
  8492. } else {
  8493. /* remove existing handler */
  8494. *lastref = tmp_rh->next;
  8495. mg_free(tmp_rh->uri);
  8496. mg_free(tmp_rh);
  8497. }
  8498. mg_unlock_context(ctx);
  8499. return;
  8500. }
  8501. }
  8502. lastref = &(tmp_rh->next);
  8503. }
  8504. if (is_delete_request) {
  8505. /* no handler to set, this was a remove request to a non-existing
  8506. * handler */
  8507. mg_unlock_context(ctx);
  8508. return;
  8509. }
  8510. tmp_rh =
  8511. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8512. if (tmp_rh == NULL) {
  8513. mg_unlock_context(ctx);
  8514. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8515. return;
  8516. }
  8517. tmp_rh->uri = mg_strdup(uri);
  8518. if (!tmp_rh->uri) {
  8519. mg_unlock_context(ctx);
  8520. mg_free(tmp_rh);
  8521. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8522. return;
  8523. }
  8524. tmp_rh->uri_len = urilen;
  8525. if (handler_type == REQUEST_HANDLER) {
  8526. tmp_rh->handler = handler;
  8527. } else if (handler_type == WEBSOCKET_HANDLER) {
  8528. tmp_rh->connect_handler = connect_handler;
  8529. tmp_rh->ready_handler = ready_handler;
  8530. tmp_rh->data_handler = data_handler;
  8531. tmp_rh->close_handler = close_handler;
  8532. } else { /* AUTH_HANDLER */
  8533. tmp_rh->auth_handler = auth_handler;
  8534. }
  8535. tmp_rh->cbdata = cbdata;
  8536. tmp_rh->handler_type = handler_type;
  8537. tmp_rh->next = NULL;
  8538. *lastref = tmp_rh;
  8539. mg_unlock_context(ctx);
  8540. }
  8541. void
  8542. mg_set_request_handler(struct mg_context *ctx,
  8543. const char *uri,
  8544. mg_request_handler handler,
  8545. void *cbdata)
  8546. {
  8547. mg_set_handler_type(ctx,
  8548. uri,
  8549. REQUEST_HANDLER,
  8550. handler == NULL,
  8551. handler,
  8552. NULL,
  8553. NULL,
  8554. NULL,
  8555. NULL,
  8556. NULL,
  8557. cbdata);
  8558. }
  8559. void
  8560. mg_set_websocket_handler(struct mg_context *ctx,
  8561. const char *uri,
  8562. mg_websocket_connect_handler connect_handler,
  8563. mg_websocket_ready_handler ready_handler,
  8564. mg_websocket_data_handler data_handler,
  8565. mg_websocket_close_handler close_handler,
  8566. void *cbdata)
  8567. {
  8568. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8569. && (data_handler == NULL)
  8570. && (close_handler == NULL);
  8571. mg_set_handler_type(ctx,
  8572. uri,
  8573. WEBSOCKET_HANDLER,
  8574. is_delete_request,
  8575. NULL,
  8576. connect_handler,
  8577. ready_handler,
  8578. data_handler,
  8579. close_handler,
  8580. NULL,
  8581. cbdata);
  8582. }
  8583. void
  8584. mg_set_auth_handler(struct mg_context *ctx,
  8585. const char *uri,
  8586. mg_request_handler handler,
  8587. void *cbdata)
  8588. {
  8589. mg_set_handler_type(ctx,
  8590. uri,
  8591. AUTH_HANDLER,
  8592. handler == NULL,
  8593. NULL,
  8594. NULL,
  8595. NULL,
  8596. NULL,
  8597. NULL,
  8598. handler,
  8599. cbdata);
  8600. }
  8601. static int
  8602. get_request_handler(struct mg_connection *conn,
  8603. int handler_type,
  8604. mg_request_handler *handler,
  8605. mg_websocket_connect_handler *connect_handler,
  8606. mg_websocket_ready_handler *ready_handler,
  8607. mg_websocket_data_handler *data_handler,
  8608. mg_websocket_close_handler *close_handler,
  8609. mg_authorization_handler *auth_handler,
  8610. void **cbdata)
  8611. {
  8612. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8613. if (request_info) {
  8614. const char *uri = request_info->local_uri;
  8615. size_t urilen = strlen(uri);
  8616. struct mg_handler_info *tmp_rh;
  8617. if (!conn || !conn->ctx) {
  8618. return 0;
  8619. }
  8620. mg_lock_context(conn->ctx);
  8621. /* first try for an exact match */
  8622. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8623. tmp_rh = tmp_rh->next) {
  8624. if (tmp_rh->handler_type == handler_type) {
  8625. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8626. if (handler_type == WEBSOCKET_HANDLER) {
  8627. *connect_handler = tmp_rh->connect_handler;
  8628. *ready_handler = tmp_rh->ready_handler;
  8629. *data_handler = tmp_rh->data_handler;
  8630. *close_handler = tmp_rh->close_handler;
  8631. } else if (handler_type == REQUEST_HANDLER) {
  8632. *handler = tmp_rh->handler;
  8633. } else { /* AUTH_HANDLER */
  8634. *auth_handler = tmp_rh->auth_handler;
  8635. }
  8636. *cbdata = tmp_rh->cbdata;
  8637. mg_unlock_context(conn->ctx);
  8638. return 1;
  8639. }
  8640. }
  8641. }
  8642. /* next try for a partial match, we will accept uri/something */
  8643. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8644. tmp_rh = tmp_rh->next) {
  8645. if (tmp_rh->handler_type == handler_type) {
  8646. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8647. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8648. if (handler_type == WEBSOCKET_HANDLER) {
  8649. *connect_handler = tmp_rh->connect_handler;
  8650. *ready_handler = tmp_rh->ready_handler;
  8651. *data_handler = tmp_rh->data_handler;
  8652. *close_handler = tmp_rh->close_handler;
  8653. } else if (handler_type == REQUEST_HANDLER) {
  8654. *handler = tmp_rh->handler;
  8655. } else { /* AUTH_HANDLER */
  8656. *auth_handler = tmp_rh->auth_handler;
  8657. }
  8658. *cbdata = tmp_rh->cbdata;
  8659. mg_unlock_context(conn->ctx);
  8660. return 1;
  8661. }
  8662. }
  8663. }
  8664. /* finally try for pattern match */
  8665. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8666. tmp_rh = tmp_rh->next) {
  8667. if (tmp_rh->handler_type == handler_type) {
  8668. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8669. if (handler_type == WEBSOCKET_HANDLER) {
  8670. *connect_handler = tmp_rh->connect_handler;
  8671. *ready_handler = tmp_rh->ready_handler;
  8672. *data_handler = tmp_rh->data_handler;
  8673. *close_handler = tmp_rh->close_handler;
  8674. } else if (handler_type == REQUEST_HANDLER) {
  8675. *handler = tmp_rh->handler;
  8676. } else { /* AUTH_HANDLER */
  8677. *auth_handler = tmp_rh->auth_handler;
  8678. }
  8679. *cbdata = tmp_rh->cbdata;
  8680. mg_unlock_context(conn->ctx);
  8681. return 1;
  8682. }
  8683. }
  8684. }
  8685. mg_unlock_context(conn->ctx);
  8686. }
  8687. return 0; /* none found */
  8688. }
  8689. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8690. static int
  8691. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8692. void *cbdata)
  8693. {
  8694. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8695. if (pcallbacks->websocket_connect) {
  8696. return pcallbacks->websocket_connect(conn);
  8697. }
  8698. /* No handler set - assume "OK" */
  8699. return 0;
  8700. }
  8701. static void
  8702. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8703. {
  8704. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8705. if (pcallbacks->websocket_ready) {
  8706. pcallbacks->websocket_ready(conn);
  8707. }
  8708. }
  8709. static int
  8710. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8711. int bits,
  8712. char *data,
  8713. size_t len,
  8714. void *cbdata)
  8715. {
  8716. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8717. if (pcallbacks->websocket_data) {
  8718. return pcallbacks->websocket_data(conn, bits, data, len);
  8719. }
  8720. /* No handler set - assume "OK" */
  8721. return 1;
  8722. }
  8723. #endif
  8724. /* This is the heart of the Civetweb's logic.
  8725. * This function is called when the request is read, parsed and validated,
  8726. * and Civetweb must decide what action to take: serve a file, or
  8727. * a directory, or call embedded function, etcetera. */
  8728. static void
  8729. handle_request(struct mg_connection *conn)
  8730. {
  8731. if (conn) {
  8732. struct mg_request_info *ri = &conn->request_info;
  8733. char path[PATH_MAX];
  8734. int uri_len, ssl_index;
  8735. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8736. is_put_or_delete_request = 0, is_callback_resource = 0;
  8737. int i;
  8738. struct file file = STRUCT_FILE_INITIALIZER;
  8739. mg_request_handler callback_handler = NULL;
  8740. mg_websocket_connect_handler ws_connect_handler = NULL;
  8741. mg_websocket_ready_handler ws_ready_handler = NULL;
  8742. mg_websocket_data_handler ws_data_handler = NULL;
  8743. mg_websocket_close_handler ws_close_handler = NULL;
  8744. void *callback_data = NULL;
  8745. mg_authorization_handler auth_handler = NULL;
  8746. void *auth_callback_data = NULL;
  8747. #if !defined(NO_FILES)
  8748. time_t curtime = time(NULL);
  8749. char date[64];
  8750. #endif
  8751. path[0] = 0;
  8752. if (!ri) {
  8753. return;
  8754. }
  8755. /* 1. get the request url */
  8756. /* 1.1. split into url and query string */
  8757. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8758. != NULL) {
  8759. *((char *)conn->request_info.query_string++) = '\0';
  8760. }
  8761. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8762. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8763. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8764. if (ssl_index >= 0) {
  8765. redirect_to_https_port(conn, ssl_index);
  8766. } else {
  8767. /* A http to https forward port has been specified,
  8768. * but no https port to forward to. */
  8769. send_http_error(conn,
  8770. 503,
  8771. "%s",
  8772. "Error: SSL forward not configured properly");
  8773. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8774. }
  8775. return;
  8776. }
  8777. uri_len = (int)strlen(ri->local_uri);
  8778. /* 1.3. decode url (if config says so) */
  8779. if (should_decode_url(conn)) {
  8780. mg_url_decode(
  8781. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8782. }
  8783. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8784. * not possible */
  8785. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8786. /* step 1. completed, the url is known now */
  8787. uri_len = (int)strlen(ri->local_uri);
  8788. DEBUG_TRACE("URL: %s", ri->local_uri);
  8789. /* 3. if this ip has limited speed, set it for this connection */
  8790. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8791. get_remote_ip(conn),
  8792. ri->local_uri);
  8793. /* 4. call a "handle everything" callback, if registered */
  8794. if (conn->ctx->callbacks.begin_request != NULL) {
  8795. /* Note that since V1.7 the "begin_request" function is called
  8796. * before an authorization check. If an authorization check is
  8797. * required, use a request_handler instead. */
  8798. i = conn->ctx->callbacks.begin_request(conn);
  8799. if (i > 0) {
  8800. /* callback already processed the request. Store the
  8801. return value as a status code for the access log. */
  8802. conn->status_code = i;
  8803. return;
  8804. } else if (i == 0) {
  8805. /* civetweb should process the request */
  8806. } else {
  8807. /* unspecified - may change with the next version */
  8808. return;
  8809. }
  8810. }
  8811. /* request not yet handled by a handler or redirect, so the request
  8812. * is processed here */
  8813. /* 5. interpret the url to find out how the request must be handled
  8814. */
  8815. /* 5.1. first test, if the request targets the regular http(s)://
  8816. * protocol namespace or the websocket ws(s):// protocol namespace.
  8817. */
  8818. is_websocket_request = is_websocket_protocol(conn);
  8819. /* 5.2. check if the request will be handled by a callback */
  8820. if (get_request_handler(conn,
  8821. is_websocket_request ? WEBSOCKET_HANDLER
  8822. : REQUEST_HANDLER,
  8823. &callback_handler,
  8824. &ws_connect_handler,
  8825. &ws_ready_handler,
  8826. &ws_data_handler,
  8827. &ws_close_handler,
  8828. NULL,
  8829. &callback_data)) {
  8830. /* 5.2.1. A callback will handle this request. All requests
  8831. * handled
  8832. * by a callback have to be considered as requests to a script
  8833. * resource. */
  8834. is_callback_resource = 1;
  8835. is_script_resource = 1;
  8836. is_put_or_delete_request = is_put_or_delete_method(conn);
  8837. } else {
  8838. no_callback_resource:
  8839. /* 5.2.2. No callback is responsible for this request. The URI
  8840. * addresses a file based resource (static content or Lua/cgi
  8841. * scripts in the file system). */
  8842. is_callback_resource = 0;
  8843. interpret_uri(conn,
  8844. path,
  8845. sizeof(path),
  8846. &file,
  8847. &is_found,
  8848. &is_script_resource,
  8849. &is_websocket_request,
  8850. &is_put_or_delete_request);
  8851. }
  8852. /* 6. authorization check */
  8853. /* 6.1. a custom authorization handler is installed */
  8854. if (get_request_handler(conn,
  8855. AUTH_HANDLER,
  8856. NULL,
  8857. NULL,
  8858. NULL,
  8859. NULL,
  8860. NULL,
  8861. &auth_handler,
  8862. &auth_callback_data)) {
  8863. if (!auth_handler(conn, auth_callback_data)) {
  8864. return;
  8865. }
  8866. } else if (is_put_or_delete_request && !is_script_resource
  8867. && !is_callback_resource) {
  8868. /* 6.2. this request is a PUT/DELETE to a real file */
  8869. /* 6.2.1. thus, the server must have real files */
  8870. #if defined(NO_FILES)
  8871. if (1) {
  8872. #else
  8873. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8874. #endif
  8875. /* This server does not have any real files, thus the
  8876. * PUT/DELETE methods are not valid. */
  8877. send_http_error(conn,
  8878. 405,
  8879. "%s method not allowed",
  8880. conn->request_info.request_method);
  8881. return;
  8882. }
  8883. #if !defined(NO_FILES)
  8884. /* 6.2.2. Check if put authorization for static files is
  8885. * available.
  8886. */
  8887. if (!is_authorized_for_put(conn)) {
  8888. send_authorization_request(conn);
  8889. return;
  8890. }
  8891. #endif
  8892. } else {
  8893. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8894. * or it is a PUT or DELETE request to a resource that does not
  8895. * correspond to a file. Check authorization. */
  8896. if (!check_authorization(conn, path)) {
  8897. send_authorization_request(conn);
  8898. return;
  8899. }
  8900. }
  8901. /* request is authorized or does not need authorization */
  8902. /* 7. check if there are request handlers for this uri */
  8903. if (is_callback_resource) {
  8904. if (!is_websocket_request) {
  8905. i = callback_handler(conn, callback_data);
  8906. if (i > 0) {
  8907. /* Do nothing, callback has served the request. Store
  8908. * the
  8909. * return value as status code for the log and discard
  8910. * all
  8911. * data from the client not used by the callback. */
  8912. conn->status_code = i;
  8913. discard_unread_request_data(conn);
  8914. } else {
  8915. /* TODO (high): what if the handler did NOT handle the
  8916. * request */
  8917. /* The last version did handle this as a file request,
  8918. * but
  8919. * since a file request is not always a script resource,
  8920. * the authorization check might be different */
  8921. interpret_uri(conn,
  8922. path,
  8923. sizeof(path),
  8924. &file,
  8925. &is_found,
  8926. &is_script_resource,
  8927. &is_websocket_request,
  8928. &is_put_or_delete_request);
  8929. callback_handler = NULL;
  8930. /* TODO (very low): goto is deprecated but for the
  8931. * moment,
  8932. * a goto is simpler than some curious loop. */
  8933. /* The situation "callback does not handle the request"
  8934. * needs to be reconsidered anyway. */
  8935. goto no_callback_resource;
  8936. }
  8937. } else {
  8938. #if defined(USE_WEBSOCKET)
  8939. handle_websocket_request(conn,
  8940. path,
  8941. is_callback_resource,
  8942. ws_connect_handler,
  8943. ws_ready_handler,
  8944. ws_data_handler,
  8945. ws_close_handler,
  8946. callback_data);
  8947. #endif
  8948. }
  8949. return;
  8950. }
  8951. /* 8. handle websocket requests */
  8952. #if defined(USE_WEBSOCKET)
  8953. if (is_websocket_request) {
  8954. if (is_script_resource) {
  8955. /* Websocket Lua script */
  8956. handle_websocket_request(conn,
  8957. path,
  8958. 0 /* Lua Script */,
  8959. NULL,
  8960. NULL,
  8961. NULL,
  8962. NULL,
  8963. &conn->ctx->callbacks);
  8964. } else {
  8965. #if defined(MG_LEGACY_INTERFACE)
  8966. handle_websocket_request(
  8967. conn,
  8968. path,
  8969. !is_script_resource /* could be deprecated global callback */,
  8970. deprecated_websocket_connect_wrapper,
  8971. deprecated_websocket_ready_wrapper,
  8972. deprecated_websocket_data_wrapper,
  8973. NULL,
  8974. &conn->ctx->callbacks);
  8975. #else
  8976. send_http_error(conn, 404, "%s", "Not found");
  8977. #endif
  8978. }
  8979. return;
  8980. } else
  8981. #endif
  8982. #if defined(NO_FILES)
  8983. /* 9a. In case the server uses only callbacks, this uri is
  8984. * unknown.
  8985. * Then, all request handling ends here. */
  8986. send_http_error(conn, 404, "%s", "Not Found");
  8987. #else
  8988. /* 9b. This request is either for a static file or resource handled
  8989. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8990. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8991. send_http_error(conn, 404, "%s", "Not Found");
  8992. return;
  8993. }
  8994. /* 10. File is handled by a script. */
  8995. if (is_script_resource) {
  8996. handle_file_based_request(conn, path, &file);
  8997. return;
  8998. }
  8999. /* 11. Handle put/delete/mkcol requests */
  9000. if (is_put_or_delete_request) {
  9001. /* 11.1. PUT method */
  9002. if (!strcmp(ri->request_method, "PUT")) {
  9003. put_file(conn, path);
  9004. return;
  9005. }
  9006. /* 11.2. DELETE method */
  9007. if (!strcmp(ri->request_method, "DELETE")) {
  9008. delete_file(conn, path);
  9009. return;
  9010. }
  9011. /* 11.3. MKCOL method */
  9012. if (!strcmp(ri->request_method, "MKCOL")) {
  9013. mkcol(conn, path);
  9014. return;
  9015. }
  9016. /* 11.4. PATCH method
  9017. * This method is not supported for static resources,
  9018. * only for scripts (Lua, CGI) and callbacks. */
  9019. send_http_error(conn,
  9020. 405,
  9021. "%s method not allowed",
  9022. conn->request_info.request_method);
  9023. return;
  9024. }
  9025. /* 11. File does not exist, or it was configured that it should be
  9026. * hidden */
  9027. if (!is_found || (must_hide_file(conn, path))) {
  9028. send_http_error(conn, 404, "%s", "Not found");
  9029. return;
  9030. }
  9031. /* 12. Directory uris should end with a slash */
  9032. if (file.is_directory && (uri_len > 0)
  9033. && (ri->local_uri[uri_len - 1] != '/')) {
  9034. gmt_time_string(date, sizeof(date), &curtime);
  9035. mg_printf(conn,
  9036. "HTTP/1.1 301 Moved Permanently\r\n"
  9037. "Location: %s/\r\n"
  9038. "Date: %s\r\n"
  9039. /* "Cache-Control: private\r\n" (= default) */
  9040. "Content-Length: 0\r\n"
  9041. "Connection: %s\r\n\r\n",
  9042. ri->request_uri,
  9043. date,
  9044. suggest_connection_header(conn));
  9045. return;
  9046. }
  9047. /* 13. Handle other methods than GET/HEAD */
  9048. /* 13.1. Handle PROPFIND */
  9049. if (!strcmp(ri->request_method, "PROPFIND")) {
  9050. handle_propfind(conn, path, &file);
  9051. return;
  9052. }
  9053. /* 13.2. Handle OPTIONS for files */
  9054. if (!strcmp(ri->request_method, "OPTIONS")) {
  9055. /* This standard handler is only used for real files.
  9056. * Scripts should support the OPTIONS method themselves, to allow a
  9057. * maximum flexibility.
  9058. * Lua and CGI scripts may fully support CORS this way (including
  9059. * preflights). */
  9060. send_options(conn);
  9061. return;
  9062. }
  9063. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9064. if (0 != strcmp(ri->request_method, "GET")
  9065. && 0 != strcmp(ri->request_method, "HEAD")) {
  9066. send_http_error(conn,
  9067. 405,
  9068. "%s method not allowed",
  9069. conn->request_info.request_method);
  9070. return;
  9071. }
  9072. /* 14. directories */
  9073. if (file.is_directory) {
  9074. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9075. /* 14.1. use a substitute file */
  9076. /* TODO (high): substitute index may be a script resource.
  9077. * define what should be possible in this case. */
  9078. } else {
  9079. /* 14.2. no substitute file */
  9080. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9081. "yes")) {
  9082. handle_directory_request(conn, path);
  9083. } else {
  9084. send_http_error(conn,
  9085. 403,
  9086. "%s",
  9087. "Error: Directory listing denied");
  9088. }
  9089. return;
  9090. }
  9091. }
  9092. handle_file_based_request(conn, path, &file);
  9093. #endif /* !defined(NO_FILES) */
  9094. #if 0
  9095. /* Perform redirect and auth checks before calling begin_request()
  9096. * handler.
  9097. * Otherwise, begin_request() would need to perform auth checks and
  9098. * redirects. */
  9099. #endif
  9100. }
  9101. return;
  9102. }
  9103. static void
  9104. handle_file_based_request(struct mg_connection *conn,
  9105. const char *path,
  9106. struct file *file)
  9107. {
  9108. if (!conn || !conn->ctx) {
  9109. return;
  9110. }
  9111. if (0) {
  9112. #ifdef USE_LUA
  9113. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9114. strlen(
  9115. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9116. path) > 0) {
  9117. /* Lua server page: an SSI like page containing mostly plain html
  9118. * code
  9119. * plus some tags with server generated contents. */
  9120. handle_lsp_request(conn, path, file, NULL);
  9121. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9122. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9123. path) > 0) {
  9124. /* Lua in-server module script: a CGI like script used to generate
  9125. * the
  9126. * entire reply. */
  9127. mg_exec_lua_script(conn, path, NULL);
  9128. #endif
  9129. #if defined(USE_DUKTAPE)
  9130. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9131. strlen(
  9132. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9133. path) > 0) {
  9134. /* Call duktape to generate the page */
  9135. mg_exec_duktape_script(conn, path);
  9136. #endif
  9137. #if !defined(NO_CGI)
  9138. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9139. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9140. path) > 0) {
  9141. /* CGI scripts may support all HTTP methods */
  9142. handle_cgi_request(conn, path);
  9143. #endif /* !NO_CGI */
  9144. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9145. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9146. path) > 0) {
  9147. handle_ssi_file_request(conn, path, file);
  9148. #if !defined(NO_CACHING)
  9149. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9150. /* Send 304 "Not Modified" - this must not send any body data */
  9151. handle_not_modified_static_file_request(conn, file);
  9152. #endif /* !NO_CACHING */
  9153. } else {
  9154. handle_static_file_request(conn, path, file, NULL);
  9155. }
  9156. }
  9157. static void
  9158. close_all_listening_sockets(struct mg_context *ctx)
  9159. {
  9160. unsigned int i;
  9161. if (!ctx) {
  9162. return;
  9163. }
  9164. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9165. closesocket(ctx->listening_sockets[i].sock);
  9166. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9167. }
  9168. mg_free(ctx->listening_sockets);
  9169. ctx->listening_sockets = NULL;
  9170. mg_free(ctx->listening_socket_fds);
  9171. ctx->listening_socket_fds = NULL;
  9172. }
  9173. /* Valid listening port specification is: [ip_address:]port[s]
  9174. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9175. * Examples for IPv6: [::]:80, [::1]:80,
  9176. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9177. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9178. static int
  9179. parse_port_string(const struct vec *vec, struct socket *so)
  9180. {
  9181. unsigned int a, b, c, d, port;
  9182. int ch, len;
  9183. #if defined(USE_IPV6)
  9184. char buf[100] = {0};
  9185. #endif
  9186. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9187. * Also, all-zeroes in the socket address means binding to all addresses
  9188. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9189. memset(so, 0, sizeof(*so));
  9190. so->lsa.sin.sin_family = AF_INET;
  9191. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9192. == 5) {
  9193. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9194. so->lsa.sin.sin_addr.s_addr =
  9195. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9196. so->lsa.sin.sin_port = htons((uint16_t)port);
  9197. #if defined(USE_IPV6)
  9198. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9199. && mg_inet_pton(
  9200. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9201. /* IPv6 address, examples: see above */
  9202. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9203. */
  9204. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9205. #endif
  9206. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9207. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9208. so->lsa.sin.sin_port = htons((uint16_t)port);
  9209. } else {
  9210. /* Parsing failure. Make port invalid. */
  9211. port = 0;
  9212. len = 0;
  9213. }
  9214. /* sscanf and the option splitting code ensure the following condition
  9215. */
  9216. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9217. return 0;
  9218. }
  9219. ch = vec->ptr[len]; /* Next character after the port number */
  9220. so->is_ssl = (ch == 's');
  9221. so->ssl_redir = (ch == 'r');
  9222. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9223. return is_valid_port(port)
  9224. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9225. }
  9226. static int
  9227. set_ports_option(struct mg_context *ctx)
  9228. {
  9229. const char *list;
  9230. int on = 1;
  9231. #if defined(USE_IPV6)
  9232. int off = 0;
  9233. #endif
  9234. struct vec vec;
  9235. struct socket so, *ptr;
  9236. struct pollfd *pfd;
  9237. union usa usa;
  9238. socklen_t len;
  9239. int portsTotal = 0;
  9240. int portsOk = 0;
  9241. if (!ctx) {
  9242. return 0;
  9243. }
  9244. memset(&so, 0, sizeof(so));
  9245. memset(&usa, 0, sizeof(usa));
  9246. len = sizeof(usa);
  9247. list = ctx->config[LISTENING_PORTS];
  9248. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9249. portsTotal++;
  9250. if (!parse_port_string(&vec, &so)) {
  9251. mg_cry(fc(ctx),
  9252. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9253. (int)vec.len,
  9254. vec.ptr,
  9255. portsTotal,
  9256. "[IP_ADDRESS:]PORT[s|r]");
  9257. continue;
  9258. }
  9259. #if !defined(NO_SSL)
  9260. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9261. mg_cry(fc(ctx),
  9262. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9263. "option set?",
  9264. portsTotal);
  9265. continue;
  9266. }
  9267. #endif
  9268. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9269. == INVALID_SOCKET) {
  9270. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9271. continue;
  9272. }
  9273. #ifdef _WIN32
  9274. /* Windows SO_REUSEADDR lets many procs binds to a
  9275. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9276. * if someone already has the socket -- DTL */
  9277. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9278. * Windows might need a few seconds before
  9279. * the same port can be used again in the
  9280. * same process, so a short Sleep may be
  9281. * required between mg_stop and mg_start.
  9282. */
  9283. if (setsockopt(so.sock,
  9284. SOL_SOCKET,
  9285. SO_EXCLUSIVEADDRUSE,
  9286. (SOCK_OPT_TYPE)&on,
  9287. sizeof(on)) != 0) {
  9288. mg_cry(fc(ctx),
  9289. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9290. portsTotal);
  9291. }
  9292. #else
  9293. if (setsockopt(so.sock,
  9294. SOL_SOCKET,
  9295. SO_REUSEADDR,
  9296. (SOCK_OPT_TYPE)&on,
  9297. sizeof(on)) != 0) {
  9298. mg_cry(fc(ctx),
  9299. "cannot set socket option SO_REUSEADDR (entry %i)",
  9300. portsTotal);
  9301. }
  9302. #endif
  9303. #if defined(USE_IPV6)
  9304. if (so.lsa.sa.sa_family == AF_INET6
  9305. && setsockopt(so.sock,
  9306. IPPROTO_IPV6,
  9307. IPV6_V6ONLY,
  9308. (void *)&off,
  9309. sizeof(off)) != 0) {
  9310. mg_cry(fc(ctx),
  9311. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9312. portsTotal);
  9313. }
  9314. #endif
  9315. if (so.lsa.sa.sa_family == AF_INET) {
  9316. len = sizeof(so.lsa.sin);
  9317. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9318. mg_cry(fc(ctx),
  9319. "cannot bind to %.*s: %d (%s)",
  9320. (int)vec.len,
  9321. vec.ptr,
  9322. (int)ERRNO,
  9323. strerror(errno));
  9324. closesocket(so.sock);
  9325. so.sock = INVALID_SOCKET;
  9326. continue;
  9327. }
  9328. }
  9329. #if defined(USE_IPV6)
  9330. else if (so.lsa.sa.sa_family == AF_INET6) {
  9331. len = sizeof(so.lsa.sin6);
  9332. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9333. mg_cry(fc(ctx),
  9334. "cannot bind to IPv6 %.*s: %d (%s)",
  9335. (int)vec.len,
  9336. vec.ptr,
  9337. (int)ERRNO,
  9338. strerror(errno));
  9339. closesocket(so.sock);
  9340. so.sock = INVALID_SOCKET;
  9341. continue;
  9342. }
  9343. }
  9344. #endif
  9345. else {
  9346. mg_cry(fc(ctx),
  9347. "cannot bind: address family not supported (entry %i)",
  9348. portsTotal);
  9349. continue;
  9350. }
  9351. if (listen(so.sock, SOMAXCONN) != 0) {
  9352. mg_cry(fc(ctx),
  9353. "cannot listen to %.*s: %d (%s)",
  9354. (int)vec.len,
  9355. vec.ptr,
  9356. (int)ERRNO,
  9357. strerror(errno));
  9358. closesocket(so.sock);
  9359. so.sock = INVALID_SOCKET;
  9360. continue;
  9361. }
  9362. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9363. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9364. int err = (int)ERRNO;
  9365. mg_cry(fc(ctx),
  9366. "call to getsockname failed %.*s: %d (%s)",
  9367. (int)vec.len,
  9368. vec.ptr,
  9369. err,
  9370. strerror(errno));
  9371. closesocket(so.sock);
  9372. so.sock = INVALID_SOCKET;
  9373. continue;
  9374. }
  9375. /* Update lsa port in case of random free ports */
  9376. #if defined(USE_IPV6)
  9377. if (so.lsa.sa.sa_family == AF_INET6) {
  9378. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9379. } else
  9380. #endif
  9381. {
  9382. so.lsa.sin.sin_port = usa.sin.sin_port;
  9383. }
  9384. if ((ptr = (struct socket *)
  9385. mg_realloc(ctx->listening_sockets,
  9386. (ctx->num_listening_sockets + 1)
  9387. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9388. mg_cry(fc(ctx), "%s", "Out of memory");
  9389. closesocket(so.sock);
  9390. so.sock = INVALID_SOCKET;
  9391. continue;
  9392. }
  9393. if ((pfd = (struct pollfd *)mg_realloc(
  9394. ctx->listening_socket_fds,
  9395. (ctx->num_listening_sockets + 1)
  9396. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9397. mg_cry(fc(ctx), "%s", "Out of memory");
  9398. closesocket(so.sock);
  9399. so.sock = INVALID_SOCKET;
  9400. mg_free(ptr);
  9401. continue;
  9402. }
  9403. set_close_on_exec(so.sock, fc(ctx));
  9404. ctx->listening_sockets = ptr;
  9405. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9406. ctx->listening_socket_fds = pfd;
  9407. ctx->num_listening_sockets++;
  9408. portsOk++;
  9409. }
  9410. if (portsOk != portsTotal) {
  9411. close_all_listening_sockets(ctx);
  9412. portsOk = 0;
  9413. }
  9414. return portsOk;
  9415. }
  9416. static const char *
  9417. header_val(const struct mg_connection *conn, const char *header)
  9418. {
  9419. const char *header_value;
  9420. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9421. return "-";
  9422. } else {
  9423. return header_value;
  9424. }
  9425. }
  9426. static void
  9427. log_access(const struct mg_connection *conn)
  9428. {
  9429. const struct mg_request_info *ri;
  9430. struct file fi;
  9431. char date[64], src_addr[IP_ADDR_STR_LEN];
  9432. struct tm *tm;
  9433. const char *referer;
  9434. const char *user_agent;
  9435. char buf[4096];
  9436. if (!conn || !conn->ctx) {
  9437. return;
  9438. }
  9439. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9440. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9441. == 0) {
  9442. fi.fp = NULL;
  9443. }
  9444. } else {
  9445. fi.fp = NULL;
  9446. }
  9447. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  9448. return;
  9449. }
  9450. tm = localtime(&conn->conn_birth_time);
  9451. if (tm != NULL) {
  9452. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9453. } else {
  9454. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9455. date[sizeof(date) - 1] = '\0';
  9456. }
  9457. ri = &conn->request_info;
  9458. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9459. referer = header_val(conn, "Referer");
  9460. user_agent = header_val(conn, "User-Agent");
  9461. mg_snprintf(conn,
  9462. NULL, /* Ignore truncation in access log */
  9463. buf,
  9464. sizeof(buf),
  9465. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9466. src_addr,
  9467. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9468. date,
  9469. ri->request_method ? ri->request_method : "-",
  9470. ri->request_uri ? ri->request_uri : "-",
  9471. ri->query_string ? "?" : "",
  9472. ri->query_string ? ri->query_string : "",
  9473. ri->http_version,
  9474. conn->status_code,
  9475. conn->num_bytes_sent,
  9476. referer,
  9477. user_agent);
  9478. if (conn->ctx->callbacks.log_access) {
  9479. conn->ctx->callbacks.log_access(conn, buf);
  9480. }
  9481. if (fi.fp) {
  9482. flockfile(fi.fp);
  9483. fprintf(fi.fp, "%s\n", buf);
  9484. fflush(fi.fp);
  9485. funlockfile(fi.fp);
  9486. mg_fclose(&fi);
  9487. }
  9488. }
  9489. /* Verify given socket address against the ACL.
  9490. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9491. */
  9492. static int
  9493. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9494. {
  9495. int allowed, flag;
  9496. uint32_t net, mask;
  9497. struct vec vec;
  9498. if (ctx) {
  9499. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9500. /* If any ACL is set, deny by default */
  9501. allowed = (list == NULL) ? '+' : '-';
  9502. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9503. flag = vec.ptr[0];
  9504. if ((flag != '+' && flag != '-')
  9505. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9506. mg_cry(fc(ctx),
  9507. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9508. __func__);
  9509. return -1;
  9510. }
  9511. if (net == (remote_ip & mask)) {
  9512. allowed = flag;
  9513. }
  9514. }
  9515. return allowed == '+';
  9516. }
  9517. return -1;
  9518. }
  9519. #if !defined(_WIN32)
  9520. static int
  9521. set_uid_option(struct mg_context *ctx)
  9522. {
  9523. struct passwd *pw;
  9524. if (ctx) {
  9525. const char *uid = ctx->config[RUN_AS_USER];
  9526. int success = 0;
  9527. if (uid == NULL) {
  9528. success = 1;
  9529. } else {
  9530. if ((pw = getpwnam(uid)) == NULL) {
  9531. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9532. } else if (setgid(pw->pw_gid) == -1) {
  9533. mg_cry(fc(ctx),
  9534. "%s: setgid(%s): %s",
  9535. __func__,
  9536. uid,
  9537. strerror(errno));
  9538. } else if (setgroups(0, NULL)) {
  9539. mg_cry(fc(ctx),
  9540. "%s: setgroups(): %s",
  9541. __func__,
  9542. strerror(errno));
  9543. } else if (setuid(pw->pw_uid) == -1) {
  9544. mg_cry(fc(ctx),
  9545. "%s: setuid(%s): %s",
  9546. __func__,
  9547. uid,
  9548. strerror(errno));
  9549. } else {
  9550. success = 1;
  9551. }
  9552. }
  9553. return success;
  9554. }
  9555. return 0;
  9556. }
  9557. #endif /* !_WIN32 */
  9558. static void
  9559. tls_dtor(void *key)
  9560. {
  9561. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9562. /* key == pthread_getspecific(sTlsKey); */
  9563. if (tls) {
  9564. if (tls->is_master == 2) {
  9565. tls->is_master = -3; /* Mark memory as dead */
  9566. mg_free(tls);
  9567. }
  9568. }
  9569. pthread_setspecific(sTlsKey, NULL);
  9570. }
  9571. #if !defined(NO_SSL)
  9572. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9573. static unsigned long
  9574. ssl_id_callback(void)
  9575. {
  9576. #ifdef _WIN32
  9577. return GetCurrentThreadId();
  9578. #else
  9579. #ifdef __clang__
  9580. #pragma clang diagnostic push
  9581. #pragma clang diagnostic ignored "-Wunreachable-code"
  9582. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9583. * or not, so one of the two conditions will be unreachable by construction.
  9584. * Unfortunately the C standard does not define a way to check this at
  9585. * compile time, since the #if preprocessor conditions can not use the sizeof
  9586. * operator as an argument. */
  9587. #endif
  9588. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9589. /* This is the problematic case for CRYPTO_set_id_callback:
  9590. * The OS pthread_t can not be cast to unsigned long. */
  9591. struct mg_workerTLS *tls =
  9592. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9593. if (tls == NULL) {
  9594. /* SSL called from an unknown thread: Create some thread index.
  9595. */
  9596. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9597. tls->is_master = -2; /* -2 means "3rd party thread" */
  9598. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9599. pthread_setspecific(sTlsKey, tls);
  9600. }
  9601. return tls->thread_idx;
  9602. } else {
  9603. /* pthread_t may be any data type, so a simple cast to unsigned long
  9604. * can rise a warning/error, depending on the platform.
  9605. * Here memcpy is used as an anything-to-anything cast. */
  9606. unsigned long ret = 0;
  9607. pthread_t t = pthread_self();
  9608. memcpy(&ret, &t, sizeof(pthread_t));
  9609. return ret;
  9610. }
  9611. #ifdef __clang__
  9612. #pragma clang diagnostic pop
  9613. #endif
  9614. #endif
  9615. }
  9616. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9617. static const char *ssl_error(void);
  9618. static int
  9619. refresh_trust(struct mg_connection *conn)
  9620. {
  9621. static int reload_lock = 0;
  9622. static long int data_check = 0;
  9623. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9624. struct stat cert_buf;
  9625. long int t;
  9626. char *pem;
  9627. int should_verify_peer;
  9628. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9629. && conn->ctx->callbacks.init_ssl == NULL) {
  9630. return 0;
  9631. }
  9632. t = data_check;
  9633. if (stat(pem, &cert_buf) != -1) {
  9634. t = (long int)cert_buf.st_mtime;
  9635. }
  9636. if (data_check != t) {
  9637. data_check = t;
  9638. should_verify_peer =
  9639. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9640. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9641. == 0);
  9642. if (should_verify_peer) {
  9643. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9644. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9645. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9646. ca_file,
  9647. ca_path) != 1) {
  9648. mg_cry(fc(conn->ctx),
  9649. "SSL_CTX_load_verify_locations error: %s "
  9650. "ssl_verify_peer requires setting "
  9651. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9652. "present in "
  9653. "the .conf file?",
  9654. ssl_error());
  9655. return 0;
  9656. }
  9657. }
  9658. if (1 == mg_atomic_inc(p_reload_lock)) {
  9659. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9660. return 0;
  9661. }
  9662. *p_reload_lock = 0;
  9663. }
  9664. }
  9665. /* lock while cert is reloading */
  9666. while (*p_reload_lock) {
  9667. sleep(1);
  9668. }
  9669. return 1;
  9670. }
  9671. static pthread_mutex_t *ssl_mutexes;
  9672. static int
  9673. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9674. {
  9675. int ret, err;
  9676. int short_trust;
  9677. unsigned i;
  9678. if (!conn) {
  9679. return 0;
  9680. }
  9681. short_trust =
  9682. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9683. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9684. if (short_trust) {
  9685. int trust_ret = refresh_trust(conn);
  9686. if (!trust_ret) {
  9687. return trust_ret;
  9688. }
  9689. }
  9690. conn->ssl = SSL_new(s);
  9691. if (conn->ssl == NULL) {
  9692. return 0;
  9693. }
  9694. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9695. if (ret != 1) {
  9696. err = SSL_get_error(conn->ssl, ret);
  9697. (void)err; /* TODO: set some error message */
  9698. SSL_free(conn->ssl);
  9699. conn->ssl = NULL;
  9700. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9701. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9702. ERR_remove_state(0);
  9703. return 0;
  9704. }
  9705. /* SSL functions may fail and require to be called again:
  9706. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9707. * Here "func" could be SSL_connect or SSL_accept. */
  9708. for (i = 0; i <= 16; i *= 2) {
  9709. ret = func(conn->ssl);
  9710. if (ret != 1) {
  9711. err = SSL_get_error(conn->ssl, ret);
  9712. if ((err == SSL_ERROR_WANT_CONNECT)
  9713. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9714. /* Retry */
  9715. mg_sleep(i);
  9716. } else {
  9717. /* This is an error */
  9718. /* TODO: set some error message */
  9719. break;
  9720. }
  9721. } else {
  9722. /* success */
  9723. break;
  9724. }
  9725. }
  9726. if (ret != 1) {
  9727. SSL_free(conn->ssl);
  9728. conn->ssl = NULL;
  9729. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9730. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9731. ERR_remove_state(0);
  9732. return 0;
  9733. }
  9734. return 1;
  9735. }
  9736. /* Return OpenSSL error message (from CRYPTO lib) */
  9737. static const char *
  9738. ssl_error(void)
  9739. {
  9740. unsigned long err;
  9741. err = ERR_get_error();
  9742. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9743. }
  9744. static void
  9745. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9746. {
  9747. (void)line;
  9748. (void)file;
  9749. if (mode & 1) {
  9750. /* 1 is CRYPTO_LOCK */
  9751. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9752. } else {
  9753. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9754. }
  9755. }
  9756. #if !defined(NO_SSL_DL)
  9757. static void *
  9758. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9759. {
  9760. union {
  9761. void *p;
  9762. void (*fp)(void);
  9763. } u;
  9764. void *dll_handle;
  9765. struct ssl_func *fp;
  9766. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9767. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9768. return NULL;
  9769. }
  9770. for (fp = sw; fp->name != NULL; fp++) {
  9771. #ifdef _WIN32
  9772. /* GetProcAddress() returns pointer to function */
  9773. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9774. #else
  9775. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9776. * pointers to function pointers. We need to use a union to make a
  9777. * cast. */
  9778. u.p = dlsym(dll_handle, fp->name);
  9779. #endif /* _WIN32 */
  9780. if (u.fp == NULL) {
  9781. mg_cry(fc(ctx),
  9782. "%s: %s: cannot find %s",
  9783. __func__,
  9784. dll_name,
  9785. fp->name);
  9786. dlclose(dll_handle);
  9787. return NULL;
  9788. } else {
  9789. fp->ptr = u.fp;
  9790. }
  9791. }
  9792. return dll_handle;
  9793. }
  9794. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9795. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9796. #endif /* NO_SSL_DL */
  9797. #if defined(SSL_ALREADY_INITIALIZED)
  9798. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9799. #else
  9800. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9801. #endif
  9802. static int
  9803. initialize_ssl(struct mg_context *ctx)
  9804. {
  9805. int i;
  9806. size_t size;
  9807. #if !defined(NO_SSL_DL)
  9808. if (!cryptolib_dll_handle) {
  9809. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9810. if (!cryptolib_dll_handle) {
  9811. return 0;
  9812. }
  9813. }
  9814. #endif /* NO_SSL_DL */
  9815. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9816. return 1;
  9817. }
  9818. /* Initialize locking callbacks, needed for thread safety.
  9819. * http://www.openssl.org/support/faq.html#PROG1
  9820. */
  9821. i = CRYPTO_num_locks();
  9822. if (i < 0) {
  9823. i = 0;
  9824. }
  9825. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9826. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9827. mg_cry(fc(ctx),
  9828. "%s: cannot allocate mutexes: %s",
  9829. __func__,
  9830. ssl_error());
  9831. return 0;
  9832. }
  9833. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9834. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9835. }
  9836. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9837. CRYPTO_set_id_callback(&ssl_id_callback);
  9838. return 1;
  9839. }
  9840. static int
  9841. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9842. {
  9843. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9844. mg_cry(fc(ctx),
  9845. "%s: cannot open certificate file %s: %s",
  9846. __func__,
  9847. pem,
  9848. ssl_error());
  9849. return 0;
  9850. }
  9851. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9852. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9853. mg_cry(fc(ctx),
  9854. "%s: cannot open private key file %s: %s",
  9855. __func__,
  9856. pem,
  9857. ssl_error());
  9858. return 0;
  9859. }
  9860. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9861. mg_cry(fc(ctx),
  9862. "%s: certificate and private key do not match: %s",
  9863. __func__,
  9864. pem);
  9865. return 0;
  9866. }
  9867. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9868. mg_cry(fc(ctx),
  9869. "%s: cannot use certificate chain file %s: %s",
  9870. __func__,
  9871. pem,
  9872. ssl_error());
  9873. return 0;
  9874. }
  9875. return 1;
  9876. }
  9877. static long
  9878. ssl_get_protocol(int version_id)
  9879. {
  9880. long ret = SSL_OP_ALL;
  9881. if (version_id > 0)
  9882. ret |= SSL_OP_NO_SSLv2;
  9883. if (version_id > 1)
  9884. ret |= SSL_OP_NO_SSLv3;
  9885. if (version_id > 2)
  9886. ret |= SSL_OP_NO_TLSv1;
  9887. if (version_id > 3)
  9888. ret |= SSL_OP_NO_TLSv1_1;
  9889. return ret;
  9890. }
  9891. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9892. static int
  9893. set_ssl_option(struct mg_context *ctx)
  9894. {
  9895. const char *pem;
  9896. int callback_ret;
  9897. int should_verify_peer;
  9898. const char *ca_path;
  9899. const char *ca_file;
  9900. int use_default_verify_paths;
  9901. int verify_depth;
  9902. time_t now_rt = time(NULL);
  9903. struct timespec now_mt;
  9904. md5_byte_t ssl_context_id[16];
  9905. md5_state_t md5state;
  9906. int protocol_ver;
  9907. /* If PEM file is not specified and the init_ssl callback
  9908. * is not specified, skip SSL initialization. */
  9909. if (!ctx) {
  9910. return 0;
  9911. }
  9912. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9913. && ctx->callbacks.init_ssl == NULL) {
  9914. return 1;
  9915. }
  9916. if (!initialize_ssl(ctx)) {
  9917. return 0;
  9918. }
  9919. #if !defined(NO_SSL_DL)
  9920. if (!ssllib_dll_handle) {
  9921. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9922. if (!ssllib_dll_handle) {
  9923. return 0;
  9924. }
  9925. }
  9926. #endif /* NO_SSL_DL */
  9927. /* Initialize SSL library */
  9928. SSL_library_init();
  9929. SSL_load_error_strings();
  9930. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9931. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9932. return 0;
  9933. }
  9934. SSL_CTX_clear_options(ctx->ssl_ctx,
  9935. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9936. | SSL_OP_NO_TLSv1_1);
  9937. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9938. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9939. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9940. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9941. /* If a callback has been specified, call it. */
  9942. callback_ret =
  9943. (ctx->callbacks.init_ssl == NULL)
  9944. ? 0
  9945. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9946. /* If callback returns 0, civetweb sets up the SSL certificate.
  9947. * If it returns 1, civetweb assumes the calback already did this.
  9948. * If it returns -1, initializing ssl fails. */
  9949. if (callback_ret < 0) {
  9950. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9951. return 0;
  9952. }
  9953. if (callback_ret > 0) {
  9954. if (pem != NULL) {
  9955. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9956. }
  9957. return 1;
  9958. }
  9959. /* Use some UID as session context ID. */
  9960. md5_init(&md5state);
  9961. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9962. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9963. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9964. md5_append(&md5state,
  9965. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9966. strlen(ctx->config[LISTENING_PORTS]));
  9967. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9968. md5_finish(&md5state, ssl_context_id);
  9969. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9970. (const unsigned char *)&ssl_context_id,
  9971. sizeof(ssl_context_id));
  9972. if (pem != NULL) {
  9973. if (!ssl_use_pem_file(ctx, pem)) {
  9974. return 0;
  9975. }
  9976. }
  9977. should_verify_peer =
  9978. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9979. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9980. use_default_verify_paths =
  9981. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9982. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9983. if (should_verify_peer) {
  9984. ca_path = ctx->config[SSL_CA_PATH];
  9985. ca_file = ctx->config[SSL_CA_FILE];
  9986. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9987. != 1) {
  9988. mg_cry(fc(ctx),
  9989. "SSL_CTX_load_verify_locations error: %s "
  9990. "ssl_verify_peer requires setting "
  9991. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9992. "present in "
  9993. "the .conf file?",
  9994. ssl_error());
  9995. return 0;
  9996. }
  9997. SSL_CTX_set_verify(ctx->ssl_ctx,
  9998. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9999. NULL);
  10000. if (use_default_verify_paths
  10001. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10002. mg_cry(fc(ctx),
  10003. "SSL_CTX_set_default_verify_paths error: %s",
  10004. ssl_error());
  10005. return 0;
  10006. }
  10007. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10008. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10009. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10010. }
  10011. }
  10012. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10013. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10014. != 1) {
  10015. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10016. }
  10017. }
  10018. return 1;
  10019. }
  10020. static void
  10021. uninitialize_ssl(struct mg_context *ctx)
  10022. {
  10023. int i;
  10024. (void)ctx;
  10025. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10026. /* Shutdown according to
  10027. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10028. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10029. */
  10030. CRYPTO_set_locking_callback(NULL);
  10031. CRYPTO_set_id_callback(NULL);
  10032. ENGINE_cleanup();
  10033. CONF_modules_unload(1);
  10034. ERR_free_strings();
  10035. EVP_cleanup();
  10036. CRYPTO_cleanup_all_ex_data();
  10037. ERR_remove_state(0);
  10038. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10039. pthread_mutex_destroy(&ssl_mutexes[i]);
  10040. }
  10041. mg_free(ssl_mutexes);
  10042. ssl_mutexes = NULL;
  10043. }
  10044. }
  10045. #endif /* !NO_SSL */
  10046. static int
  10047. set_gpass_option(struct mg_context *ctx)
  10048. {
  10049. if (ctx) {
  10050. struct file file = STRUCT_FILE_INITIALIZER;
  10051. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10052. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10053. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10054. return 0;
  10055. }
  10056. return 1;
  10057. }
  10058. return 0;
  10059. }
  10060. static int
  10061. set_acl_option(struct mg_context *ctx)
  10062. {
  10063. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10064. }
  10065. static void
  10066. reset_per_request_attributes(struct mg_connection *conn)
  10067. {
  10068. if (!conn) {
  10069. return;
  10070. }
  10071. conn->path_info = NULL;
  10072. conn->num_bytes_sent = conn->consumed_content = 0;
  10073. conn->status_code = -1;
  10074. conn->is_chunked = 0;
  10075. conn->must_close = conn->request_len = conn->throttle = 0;
  10076. conn->request_info.content_length = -1;
  10077. conn->request_info.remote_user = NULL;
  10078. conn->request_info.request_method = NULL;
  10079. conn->request_info.request_uri = NULL;
  10080. conn->request_info.local_uri = NULL;
  10081. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10082. * local_uri and request_uri */
  10083. conn->request_info.http_version = NULL;
  10084. conn->request_info.num_headers = 0;
  10085. conn->data_len = 0;
  10086. conn->chunk_remainder = 0;
  10087. conn->internal_error = 0;
  10088. }
  10089. static int
  10090. set_sock_timeout(SOCKET sock, int milliseconds)
  10091. {
  10092. int r0 = 0, r1, r2;
  10093. #ifdef _WIN32
  10094. /* Windows specific */
  10095. DWORD tv = (DWORD)milliseconds;
  10096. #else
  10097. /* Linux, ... (not Windows) */
  10098. struct timeval tv;
  10099. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10100. * max. time waiting for the acknowledged of TCP data before the connection
  10101. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10102. * If this option is not set, the default timeout of 20-30 minutes is used.
  10103. */
  10104. /* #define TCP_USER_TIMEOUT (18) */
  10105. #if defined(TCP_USER_TIMEOUT)
  10106. unsigned int uto = (unsigned int)milliseconds;
  10107. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10108. #endif
  10109. memset(&tv, 0, sizeof(tv));
  10110. tv.tv_sec = milliseconds / 1000;
  10111. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10112. #endif /* _WIN32 */
  10113. r1 = setsockopt(
  10114. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10115. r2 = setsockopt(
  10116. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10117. return r0 || r1 || r2;
  10118. }
  10119. static int
  10120. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10121. {
  10122. if (setsockopt(sock,
  10123. IPPROTO_TCP,
  10124. TCP_NODELAY,
  10125. (SOCK_OPT_TYPE)&nodelay_on,
  10126. sizeof(nodelay_on)) != 0) {
  10127. /* Error */
  10128. return 1;
  10129. }
  10130. /* OK */
  10131. return 0;
  10132. }
  10133. static void
  10134. close_socket_gracefully(struct mg_connection *conn)
  10135. {
  10136. #if defined(_WIN32)
  10137. char buf[MG_BUF_LEN];
  10138. int n;
  10139. #endif
  10140. struct linger linger;
  10141. if (!conn) {
  10142. return;
  10143. }
  10144. /* Set linger option to avoid socket hanging out after close. This
  10145. * prevent
  10146. * ephemeral port exhaust problem under high QPS. */
  10147. linger.l_onoff = 1;
  10148. linger.l_linger = 1;
  10149. if (setsockopt(conn->client.sock,
  10150. SOL_SOCKET,
  10151. SO_LINGER,
  10152. (char *)&linger,
  10153. sizeof(linger)) != 0) {
  10154. mg_cry(conn,
  10155. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10156. __func__,
  10157. strerror(ERRNO));
  10158. }
  10159. /* Send FIN to the client */
  10160. shutdown(conn->client.sock, SHUTDOWN_WR);
  10161. set_non_blocking_mode(conn->client.sock);
  10162. #if defined(_WIN32)
  10163. /* Read and discard pending incoming data. If we do not do that and
  10164. * close
  10165. * the socket, the data in the send buffer may be discarded. This
  10166. * behaviour is seen on Windows, when client keeps sending data
  10167. * when server decides to close the connection; then when client
  10168. * does recv() it gets no data back. */
  10169. do {
  10170. n = pull(
  10171. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10172. } while (n > 0);
  10173. #endif
  10174. /* Now we know that our FIN is ACK-ed, safe to close */
  10175. closesocket(conn->client.sock);
  10176. conn->client.sock = INVALID_SOCKET;
  10177. }
  10178. static void
  10179. close_connection(struct mg_connection *conn)
  10180. {
  10181. if (!conn || !conn->ctx) {
  10182. return;
  10183. }
  10184. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10185. if (conn->lua_websocket_state) {
  10186. lua_websocket_close(conn, conn->lua_websocket_state);
  10187. conn->lua_websocket_state = NULL;
  10188. }
  10189. #endif
  10190. /* call the connection_close callback if assigned */
  10191. if ((conn->ctx->callbacks.connection_close != NULL)
  10192. && (conn->ctx->context_type == 1)) {
  10193. conn->ctx->callbacks.connection_close(conn);
  10194. }
  10195. mg_lock_connection(conn);
  10196. conn->must_close = 1;
  10197. #ifndef NO_SSL
  10198. if (conn->ssl != NULL) {
  10199. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10200. */
  10201. SSL_shutdown(conn->ssl);
  10202. SSL_free(conn->ssl);
  10203. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10204. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10205. ERR_remove_state(0);
  10206. conn->ssl = NULL;
  10207. }
  10208. #endif
  10209. if (conn->client.sock != INVALID_SOCKET) {
  10210. close_socket_gracefully(conn);
  10211. conn->client.sock = INVALID_SOCKET;
  10212. }
  10213. mg_unlock_connection(conn);
  10214. }
  10215. void
  10216. mg_close_connection(struct mg_connection *conn)
  10217. {
  10218. struct mg_context *client_ctx = NULL;
  10219. unsigned int i;
  10220. if (conn == NULL) {
  10221. return;
  10222. }
  10223. if (conn->ctx->context_type == 2) {
  10224. client_ctx = conn->ctx;
  10225. /* client context: loops must end */
  10226. conn->ctx->stop_flag = 1;
  10227. }
  10228. #ifndef NO_SSL
  10229. if (conn->client_ssl_ctx != NULL) {
  10230. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10231. }
  10232. #endif
  10233. close_connection(conn);
  10234. if (client_ctx != NULL) {
  10235. /* join worker thread and free context */
  10236. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10237. if (client_ctx->workerthreadids[i] != 0) {
  10238. mg_join_thread(client_ctx->workerthreadids[i]);
  10239. }
  10240. }
  10241. mg_free(client_ctx->workerthreadids);
  10242. mg_free(client_ctx);
  10243. (void)pthread_mutex_destroy(&conn->mutex);
  10244. mg_free(conn);
  10245. }
  10246. }
  10247. static struct mg_connection *
  10248. mg_connect_client_impl(const struct mg_client_options *client_options,
  10249. int use_ssl,
  10250. char *ebuf,
  10251. size_t ebuf_len)
  10252. {
  10253. static struct mg_context fake_ctx;
  10254. struct mg_connection *conn = NULL;
  10255. SOCKET sock;
  10256. union usa sa;
  10257. if (!connect_socket(&fake_ctx,
  10258. client_options->host,
  10259. client_options->port,
  10260. use_ssl,
  10261. ebuf,
  10262. ebuf_len,
  10263. &sock,
  10264. &sa)) {
  10265. ;
  10266. } else if ((conn = (struct mg_connection *)
  10267. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10268. mg_snprintf(NULL,
  10269. NULL, /* No truncation check for ebuf */
  10270. ebuf,
  10271. ebuf_len,
  10272. "calloc(): %s",
  10273. strerror(ERRNO));
  10274. closesocket(sock);
  10275. #ifndef NO_SSL
  10276. } else if (use_ssl
  10277. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10278. == NULL) {
  10279. mg_snprintf(NULL,
  10280. NULL, /* No truncation check for ebuf */
  10281. ebuf,
  10282. ebuf_len,
  10283. "SSL_CTX_new error");
  10284. closesocket(sock);
  10285. mg_free(conn);
  10286. conn = NULL;
  10287. #endif /* NO_SSL */
  10288. } else {
  10289. #ifdef USE_IPV6
  10290. socklen_t len = (sa.sa.sa_family == AF_INET)
  10291. ? sizeof(conn->client.rsa.sin)
  10292. : sizeof(conn->client.rsa.sin6);
  10293. struct sockaddr *psa =
  10294. (sa.sa.sa_family == AF_INET)
  10295. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10296. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10297. #else
  10298. socklen_t len = sizeof(conn->client.rsa.sin);
  10299. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10300. #endif
  10301. conn->buf_size = MAX_REQUEST_SIZE;
  10302. conn->buf = (char *)(conn + 1);
  10303. conn->ctx = &fake_ctx;
  10304. conn->client.sock = sock;
  10305. conn->client.lsa = sa;
  10306. if (getsockname(sock, psa, &len) != 0) {
  10307. mg_cry(conn,
  10308. "%s: getsockname() failed: %s",
  10309. __func__,
  10310. strerror(ERRNO));
  10311. }
  10312. conn->client.is_ssl = use_ssl ? 1 : 0;
  10313. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10314. #ifndef NO_SSL
  10315. if (use_ssl) {
  10316. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10317. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10318. * SSL_CTX_set_verify call is needed to switch off server
  10319. * certificate checking, which is off by default in OpenSSL and
  10320. * on in yaSSL. */
  10321. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10322. * SSL_VERIFY_PEER, verify_ssl_server); */
  10323. if (client_options->client_cert) {
  10324. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10325. mg_snprintf(NULL,
  10326. NULL, /* No truncation check for ebuf */
  10327. ebuf,
  10328. ebuf_len,
  10329. "Can not use SSL client certificate");
  10330. SSL_CTX_free(conn->client_ssl_ctx);
  10331. closesocket(sock);
  10332. mg_free(conn);
  10333. conn = NULL;
  10334. }
  10335. }
  10336. if (client_options->server_cert) {
  10337. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10338. client_options->server_cert,
  10339. NULL);
  10340. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10341. } else {
  10342. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10343. }
  10344. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10345. mg_snprintf(NULL,
  10346. NULL, /* No truncation check for ebuf */
  10347. ebuf,
  10348. ebuf_len,
  10349. "SSL connection error");
  10350. SSL_CTX_free(conn->client_ssl_ctx);
  10351. closesocket(sock);
  10352. mg_free(conn);
  10353. conn = NULL;
  10354. }
  10355. }
  10356. #endif
  10357. }
  10358. return conn;
  10359. }
  10360. CIVETWEB_API struct mg_connection *
  10361. mg_connect_client_secure(const struct mg_client_options *client_options,
  10362. char *error_buffer,
  10363. size_t error_buffer_size)
  10364. {
  10365. return mg_connect_client_impl(client_options,
  10366. 1,
  10367. error_buffer,
  10368. error_buffer_size);
  10369. }
  10370. struct mg_connection *
  10371. mg_connect_client(const char *host,
  10372. int port,
  10373. int use_ssl,
  10374. char *error_buffer,
  10375. size_t error_buffer_size)
  10376. {
  10377. struct mg_client_options opts;
  10378. memset(&opts, 0, sizeof(opts));
  10379. opts.host = host;
  10380. opts.port = port;
  10381. return mg_connect_client_impl(&opts,
  10382. use_ssl,
  10383. error_buffer,
  10384. error_buffer_size);
  10385. }
  10386. static const struct {
  10387. const char *proto;
  10388. size_t proto_len;
  10389. unsigned default_port;
  10390. } abs_uri_protocols[] = {{"http://", 7, 80},
  10391. {"https://", 8, 443},
  10392. {"ws://", 5, 80},
  10393. {"wss://", 6, 443},
  10394. {NULL, 0, 0}};
  10395. /* Check if the uri is valid.
  10396. * return 0 for invalid uri,
  10397. * return 1 for *,
  10398. * return 2 for relative uri,
  10399. * return 3 for absolute uri without port,
  10400. * return 4 for absolute uri with port */
  10401. static int
  10402. get_uri_type(const char *uri)
  10403. {
  10404. int i;
  10405. char *hostend, *portbegin, *portend;
  10406. unsigned long port;
  10407. /* According to the HTTP standard
  10408. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10409. * URI can be an asterisk (*) or should start with slash (relative uri),
  10410. * or it should start with the protocol (absolute uri). */
  10411. if (uri[0] == '*' && uri[1] == '\0') {
  10412. /* asterisk */
  10413. return 1;
  10414. }
  10415. if (uri[0] == '/') {
  10416. /* relative uri */
  10417. return 2;
  10418. }
  10419. /* It could be an absolute uri: */
  10420. /* This function only checks if the uri is valid, not if it is
  10421. * addressing the current server. So civetweb can also be used
  10422. * as a proxy server. */
  10423. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10424. if (mg_strncasecmp(uri,
  10425. abs_uri_protocols[i].proto,
  10426. abs_uri_protocols[i].proto_len) == 0) {
  10427. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10428. if (!hostend) {
  10429. return 0;
  10430. }
  10431. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10432. if (!portbegin) {
  10433. return 3;
  10434. }
  10435. port = strtoul(portbegin + 1, &portend, 10);
  10436. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10437. return 0;
  10438. }
  10439. return 4;
  10440. }
  10441. }
  10442. return 0;
  10443. }
  10444. /* Return NULL or the relative uri at the current server */
  10445. static const char *
  10446. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10447. {
  10448. const char *server_domain;
  10449. size_t server_domain_len;
  10450. size_t request_domain_len = 0;
  10451. unsigned long port = 0;
  10452. int i;
  10453. const char *hostbegin = NULL;
  10454. const char *hostend = NULL;
  10455. const char *portbegin;
  10456. char *portend;
  10457. /* DNS is case insensitive, so use case insensitive string compare here
  10458. */
  10459. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10460. if (!server_domain) {
  10461. return 0;
  10462. }
  10463. server_domain_len = strlen(server_domain);
  10464. if (!server_domain_len) {
  10465. return 0;
  10466. }
  10467. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10468. if (mg_strncasecmp(uri,
  10469. abs_uri_protocols[i].proto,
  10470. abs_uri_protocols[i].proto_len) == 0) {
  10471. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10472. hostend = strchr(hostbegin, '/');
  10473. if (!hostend) {
  10474. return 0;
  10475. }
  10476. portbegin = strchr(hostbegin, ':');
  10477. if ((!portbegin) || (portbegin > hostend)) {
  10478. port = abs_uri_protocols[i].default_port;
  10479. request_domain_len = (size_t)(hostend - hostbegin);
  10480. } else {
  10481. port = strtoul(portbegin + 1, &portend, 10);
  10482. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10483. return 0;
  10484. }
  10485. request_domain_len = (size_t)(portbegin - hostbegin);
  10486. }
  10487. /* protocol found, port set */
  10488. break;
  10489. }
  10490. }
  10491. if (!port) {
  10492. /* port remains 0 if the protocol is not found */
  10493. return 0;
  10494. }
  10495. #if defined(USE_IPV6)
  10496. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10497. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10498. /* Request is directed to a different port */
  10499. return 0;
  10500. }
  10501. } else
  10502. #endif
  10503. {
  10504. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10505. /* Request is directed to a different port */
  10506. return 0;
  10507. }
  10508. }
  10509. if ((request_domain_len != server_domain_len)
  10510. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10511. /* Request is directed to another server */
  10512. return 0;
  10513. }
  10514. return hostend;
  10515. }
  10516. static int
  10517. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10518. {
  10519. const char *cl;
  10520. if (ebuf_len > 0) {
  10521. ebuf[0] = '\0';
  10522. }
  10523. *err = 0;
  10524. reset_per_request_attributes(conn);
  10525. if (!conn) {
  10526. mg_snprintf(conn,
  10527. NULL, /* No truncation check for ebuf */
  10528. ebuf,
  10529. ebuf_len,
  10530. "%s",
  10531. "Internal error");
  10532. *err = 500;
  10533. return 0;
  10534. }
  10535. /* Set the time the request was received. This value should be used for
  10536. * timeouts. */
  10537. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10538. conn->request_len =
  10539. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10540. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10541. */
  10542. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10543. mg_snprintf(conn,
  10544. NULL, /* No truncation check for ebuf */
  10545. ebuf,
  10546. ebuf_len,
  10547. "%s",
  10548. "Invalid request size");
  10549. *err = 500;
  10550. return 0;
  10551. }
  10552. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10553. mg_snprintf(conn,
  10554. NULL, /* No truncation check for ebuf */
  10555. ebuf,
  10556. ebuf_len,
  10557. "%s",
  10558. "Request Too Large");
  10559. *err = 413;
  10560. return 0;
  10561. } else if (conn->request_len <= 0) {
  10562. if (conn->data_len > 0) {
  10563. mg_snprintf(conn,
  10564. NULL, /* No truncation check for ebuf */
  10565. ebuf,
  10566. ebuf_len,
  10567. "%s",
  10568. "Client sent malformed request");
  10569. *err = 400;
  10570. } else {
  10571. /* Server did not send anything -> just close the connection */
  10572. conn->must_close = 1;
  10573. mg_snprintf(conn,
  10574. NULL, /* No truncation check for ebuf */
  10575. ebuf,
  10576. ebuf_len,
  10577. "%s",
  10578. "Client did not send a request");
  10579. *err = 0;
  10580. }
  10581. return 0;
  10582. } else if (parse_http_message(conn->buf,
  10583. conn->buf_size,
  10584. &conn->request_info) <= 0) {
  10585. mg_snprintf(conn,
  10586. NULL, /* No truncation check for ebuf */
  10587. ebuf,
  10588. ebuf_len,
  10589. "%s",
  10590. "Bad Request");
  10591. *err = 400;
  10592. return 0;
  10593. } else {
  10594. /* Message is a valid request or response */
  10595. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10596. /* Request/response has content length set */
  10597. char *endptr = NULL;
  10598. conn->content_len = strtoll(cl, &endptr, 10);
  10599. if (endptr == cl) {
  10600. mg_snprintf(conn,
  10601. NULL, /* No truncation check for ebuf */
  10602. ebuf,
  10603. ebuf_len,
  10604. "%s",
  10605. "Bad Request");
  10606. *err = 411;
  10607. return 0;
  10608. }
  10609. /* Publish the content length back to the request info. */
  10610. conn->request_info.content_length = conn->content_len;
  10611. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10612. != NULL
  10613. && !mg_strcasecmp(cl, "chunked")) {
  10614. conn->is_chunked = 1;
  10615. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10616. || !mg_strcasecmp(conn->request_info.request_method,
  10617. "PUT")) {
  10618. /* POST or PUT request without content length set */
  10619. conn->content_len = -1;
  10620. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10621. "HTTP/",
  10622. 5)) {
  10623. /* Response without content length set */
  10624. conn->content_len = -1;
  10625. } else {
  10626. /* Other request */
  10627. conn->content_len = 0;
  10628. }
  10629. }
  10630. return 1;
  10631. }
  10632. int
  10633. mg_get_response(struct mg_connection *conn,
  10634. char *ebuf,
  10635. size_t ebuf_len,
  10636. int timeout)
  10637. {
  10638. if (conn) {
  10639. /* Implementation of API function for HTTP clients */
  10640. int err, ret;
  10641. struct mg_context *octx = conn->ctx;
  10642. struct mg_context rctx = *(conn->ctx);
  10643. char txt[32]; /* will not overflow */
  10644. if (timeout >= 0) {
  10645. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10646. rctx.config[REQUEST_TIMEOUT] = txt;
  10647. set_sock_timeout(conn->client.sock, timeout);
  10648. } else {
  10649. rctx.config[REQUEST_TIMEOUT] = NULL;
  10650. }
  10651. conn->ctx = &rctx;
  10652. ret = getreq(conn, ebuf, ebuf_len, &err);
  10653. conn->ctx = octx;
  10654. /* TODO: 1) uri is deprecated;
  10655. * 2) here, ri.uri is the http response code */
  10656. conn->request_info.uri = conn->request_info.request_uri;
  10657. /* TODO (mid): Define proper return values - maybe return length?
  10658. * For the first test use <0 for error and >0 for OK */
  10659. return (ret == 0) ? -1 : +1;
  10660. }
  10661. return -1;
  10662. }
  10663. struct mg_connection *
  10664. mg_download(const char *host,
  10665. int port,
  10666. int use_ssl,
  10667. char *ebuf,
  10668. size_t ebuf_len,
  10669. const char *fmt,
  10670. ...)
  10671. {
  10672. struct mg_connection *conn;
  10673. va_list ap;
  10674. int i;
  10675. int reqerr;
  10676. va_start(ap, fmt);
  10677. ebuf[0] = '\0';
  10678. /* open a connection */
  10679. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10680. if (conn != NULL) {
  10681. i = mg_vprintf(conn, fmt, ap);
  10682. if (i <= 0) {
  10683. mg_snprintf(conn,
  10684. NULL, /* No truncation check for ebuf */
  10685. ebuf,
  10686. ebuf_len,
  10687. "%s",
  10688. "Error sending request");
  10689. } else {
  10690. getreq(conn, ebuf, ebuf_len, &reqerr);
  10691. /* TODO: 1) uri is deprecated;
  10692. * 2) here, ri.uri is the http response code */
  10693. conn->request_info.uri = conn->request_info.request_uri;
  10694. }
  10695. }
  10696. /* if an error occured, close the connection */
  10697. if (ebuf[0] != '\0' && conn != NULL) {
  10698. mg_close_connection(conn);
  10699. conn = NULL;
  10700. }
  10701. va_end(ap);
  10702. return conn;
  10703. }
  10704. struct websocket_client_thread_data {
  10705. struct mg_connection *conn;
  10706. mg_websocket_data_handler data_handler;
  10707. mg_websocket_close_handler close_handler;
  10708. void *callback_data;
  10709. };
  10710. #if defined(USE_WEBSOCKET)
  10711. #ifdef _WIN32
  10712. static unsigned __stdcall websocket_client_thread(void *data)
  10713. #else
  10714. static void *
  10715. websocket_client_thread(void *data)
  10716. #endif
  10717. {
  10718. struct websocket_client_thread_data *cdata =
  10719. (struct websocket_client_thread_data *)data;
  10720. mg_set_thread_name("ws-client");
  10721. if (cdata->conn->ctx) {
  10722. if (cdata->conn->ctx->callbacks.init_thread) {
  10723. /* 3 indicates a websocket client thread */
  10724. /* TODO: check if conn->ctx can be set */
  10725. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10726. }
  10727. }
  10728. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10729. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10730. if (cdata->close_handler != NULL) {
  10731. cdata->close_handler(cdata->conn, cdata->callback_data);
  10732. }
  10733. mg_free((void *)cdata);
  10734. #ifdef _WIN32
  10735. return 0;
  10736. #else
  10737. return NULL;
  10738. #endif
  10739. }
  10740. #endif
  10741. struct mg_connection *
  10742. mg_connect_websocket_client(const char *host,
  10743. int port,
  10744. int use_ssl,
  10745. char *error_buffer,
  10746. size_t error_buffer_size,
  10747. const char *path,
  10748. const char *origin,
  10749. mg_websocket_data_handler data_func,
  10750. mg_websocket_close_handler close_func,
  10751. void *user_data)
  10752. {
  10753. struct mg_connection *conn = NULL;
  10754. #if defined(USE_WEBSOCKET)
  10755. struct mg_context *newctx = NULL;
  10756. struct websocket_client_thread_data *thread_data;
  10757. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10758. static const char *handshake_req;
  10759. if (origin != NULL) {
  10760. handshake_req = "GET %s HTTP/1.1\r\n"
  10761. "Host: %s\r\n"
  10762. "Upgrade: websocket\r\n"
  10763. "Connection: Upgrade\r\n"
  10764. "Sec-WebSocket-Key: %s\r\n"
  10765. "Sec-WebSocket-Version: 13\r\n"
  10766. "Origin: %s\r\n"
  10767. "\r\n";
  10768. } else {
  10769. handshake_req = "GET %s HTTP/1.1\r\n"
  10770. "Host: %s\r\n"
  10771. "Upgrade: websocket\r\n"
  10772. "Connection: Upgrade\r\n"
  10773. "Sec-WebSocket-Key: %s\r\n"
  10774. "Sec-WebSocket-Version: 13\r\n"
  10775. "\r\n";
  10776. }
  10777. /* Establish the client connection and request upgrade */
  10778. conn = mg_download(host,
  10779. port,
  10780. use_ssl,
  10781. error_buffer,
  10782. error_buffer_size,
  10783. handshake_req,
  10784. path,
  10785. host,
  10786. magic,
  10787. origin);
  10788. /* Connection object will be null if something goes wrong */
  10789. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10790. if (!*error_buffer) {
  10791. /* if there is a connection, but it did not return 101,
  10792. * error_buffer is not yet set */
  10793. mg_snprintf(conn,
  10794. NULL, /* No truncation check for ebuf */
  10795. error_buffer,
  10796. error_buffer_size,
  10797. "Unexpected server reply");
  10798. }
  10799. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10800. if (conn != NULL) {
  10801. mg_free(conn);
  10802. conn = NULL;
  10803. }
  10804. return conn;
  10805. }
  10806. /* For client connections, mg_context is fake. Since we need to set a
  10807. * callback function, we need to create a copy and modify it. */
  10808. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10809. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10810. newctx->user_data = user_data;
  10811. newctx->context_type = 2; /* client context type */
  10812. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10813. newctx->workerthreadids =
  10814. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10815. conn->ctx = newctx;
  10816. thread_data = (struct websocket_client_thread_data *)
  10817. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10818. thread_data->conn = conn;
  10819. thread_data->data_handler = data_func;
  10820. thread_data->close_handler = close_func;
  10821. thread_data->callback_data = NULL;
  10822. /* Start a thread to read the websocket client connection
  10823. * This thread will automatically stop when mg_disconnect is
  10824. * called on the client connection */
  10825. if (mg_start_thread_with_id(websocket_client_thread,
  10826. (void *)thread_data,
  10827. newctx->workerthreadids) != 0) {
  10828. mg_free((void *)thread_data);
  10829. mg_free((void *)newctx->workerthreadids);
  10830. mg_free((void *)newctx);
  10831. mg_free((void *)conn);
  10832. conn = NULL;
  10833. DEBUG_TRACE("%s",
  10834. "Websocket client connect thread could not be started\r\n");
  10835. }
  10836. #else
  10837. /* Appease "unused parameter" warnings */
  10838. (void)host;
  10839. (void)port;
  10840. (void)use_ssl;
  10841. (void)error_buffer;
  10842. (void)error_buffer_size;
  10843. (void)path;
  10844. (void)origin;
  10845. (void)user_data;
  10846. (void)data_func;
  10847. (void)close_func;
  10848. #endif
  10849. return conn;
  10850. }
  10851. static void
  10852. process_new_connection(struct mg_connection *conn)
  10853. {
  10854. if (conn && conn->ctx) {
  10855. struct mg_request_info *ri = &conn->request_info;
  10856. int keep_alive_enabled, keep_alive, discard_len;
  10857. char ebuf[100];
  10858. const char *hostend;
  10859. int reqerr, uri_type;
  10860. keep_alive_enabled =
  10861. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10862. /* Important: on new connection, reset the receiving buffer. Credit
  10863. * goes to crule42. */
  10864. conn->data_len = 0;
  10865. do {
  10866. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10867. /* The request sent by the client could not be understood by
  10868. * the server, or it was incomplete or a timeout. Send an
  10869. * error message and close the connection. */
  10870. if (reqerr > 0) {
  10871. /*assert(ebuf[0] != '\0');*/
  10872. send_http_error(conn, reqerr, "%s", ebuf);
  10873. }
  10874. } else if (strcmp(ri->http_version, "1.0")
  10875. && strcmp(ri->http_version, "1.1")) {
  10876. mg_snprintf(conn,
  10877. NULL, /* No truncation check for ebuf */
  10878. ebuf,
  10879. sizeof(ebuf),
  10880. "Bad HTTP version: [%s]",
  10881. ri->http_version);
  10882. send_http_error(conn, 505, "%s", ebuf);
  10883. }
  10884. if (ebuf[0] == '\0') {
  10885. uri_type = get_uri_type(conn->request_info.request_uri);
  10886. switch (uri_type) {
  10887. case 1:
  10888. /* Asterisk */
  10889. conn->request_info.local_uri = NULL;
  10890. break;
  10891. case 2:
  10892. /* relative uri */
  10893. conn->request_info.local_uri =
  10894. conn->request_info.request_uri;
  10895. break;
  10896. case 3:
  10897. case 4:
  10898. /* absolute uri (with/without port) */
  10899. hostend = get_rel_url_at_current_server(
  10900. conn->request_info.request_uri, conn);
  10901. if (hostend) {
  10902. conn->request_info.local_uri = hostend;
  10903. } else {
  10904. conn->request_info.local_uri = NULL;
  10905. }
  10906. break;
  10907. default:
  10908. mg_snprintf(conn,
  10909. NULL, /* No truncation check for ebuf */
  10910. ebuf,
  10911. sizeof(ebuf),
  10912. "Invalid URI: [%s]",
  10913. ri->request_uri);
  10914. send_http_error(conn, 400, "%s", ebuf);
  10915. break;
  10916. }
  10917. /* TODO: cleanup uri, local_uri and request_uri */
  10918. conn->request_info.uri = conn->request_info.local_uri;
  10919. }
  10920. if (ebuf[0] == '\0') {
  10921. if (conn->request_info.local_uri) {
  10922. /* handle request to local server */
  10923. handle_request(conn);
  10924. if (conn->ctx->callbacks.end_request != NULL) {
  10925. conn->ctx->callbacks.end_request(conn,
  10926. conn->status_code);
  10927. }
  10928. log_access(conn);
  10929. } else {
  10930. /* TODO: handle non-local request (PROXY) */
  10931. conn->must_close = 1;
  10932. }
  10933. } else {
  10934. conn->must_close = 1;
  10935. }
  10936. if (ri->remote_user != NULL) {
  10937. mg_free((void *)ri->remote_user);
  10938. /* Important! When having connections with and without auth
  10939. * would cause double free and then crash */
  10940. ri->remote_user = NULL;
  10941. }
  10942. /* NOTE(lsm): order is important here. should_keep_alive() call
  10943. * is
  10944. * using parsed request, which will be invalid after memmove's
  10945. * below.
  10946. * Therefore, memorize should_keep_alive() result now for later
  10947. * use
  10948. * in loop exit condition. */
  10949. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10950. && conn->content_len >= 0 && should_keep_alive(conn);
  10951. /* Discard all buffered data for this request */
  10952. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  10953. && ((conn->request_len + conn->content_len)
  10954. < (int64_t)conn->data_len))
  10955. ? (int)(conn->request_len + conn->content_len)
  10956. : conn->data_len;
  10957. /*assert(discard_len >= 0);*/
  10958. if (discard_len < 0)
  10959. break;
  10960. conn->data_len -= discard_len;
  10961. if (conn->data_len > 0) {
  10962. memmove(conn->buf,
  10963. conn->buf + discard_len,
  10964. (size_t)conn->data_len);
  10965. }
  10966. /* assert(conn->data_len >= 0); */
  10967. /* assert(conn->data_len <= conn->buf_size); */
  10968. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10969. break;
  10970. }
  10971. } while (keep_alive);
  10972. }
  10973. }
  10974. #if defined(ALTERNATIVE_QUEUE)
  10975. static void
  10976. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10977. {
  10978. unsigned int i;
  10979. for (;;) {
  10980. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10981. /* find a free worker slot and signal it */
  10982. if (ctx->client_socks[i].in_use == 0) {
  10983. ctx->client_socks[i] = *sp;
  10984. ctx->client_socks[i].in_use = 1;
  10985. event_signal(ctx->client_wait_events[i]);
  10986. return;
  10987. }
  10988. }
  10989. /* queue is full */
  10990. mg_sleep(1);
  10991. }
  10992. }
  10993. static int
  10994. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  10995. {
  10996. ctx->client_socks[thread_index].in_use = 0;
  10997. event_wait(ctx->client_wait_events[thread_index]);
  10998. *sp = ctx->client_socks[thread_index];
  10999. return !ctx->stop_flag;
  11000. }
  11001. #else /* ALTERNATIVE_QUEUE */
  11002. /* Worker threads take accepted socket from the queue */
  11003. static int
  11004. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11005. {
  11006. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11007. (void)thread_index;
  11008. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11009. DEBUG_TRACE("%s", "going idle");
  11010. /* If the queue is empty, wait. We're idle at this point. */
  11011. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11012. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11013. }
  11014. /* If we're stopping, sq_head may be equal to sq_tail. */
  11015. if (ctx->sq_head > ctx->sq_tail) {
  11016. /* Copy socket from the queue and increment tail */
  11017. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11018. ctx->sq_tail++;
  11019. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11020. /* Wrap pointers if needed */
  11021. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11022. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11023. ctx->sq_head -= QUEUE_SIZE(ctx);
  11024. }
  11025. }
  11026. (void)pthread_cond_signal(&ctx->sq_empty);
  11027. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11028. return !ctx->stop_flag;
  11029. #undef QUEUE_SIZE
  11030. }
  11031. /* Master thread adds accepted socket to a queue */
  11032. static void
  11033. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11034. {
  11035. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11036. if (!ctx) {
  11037. return;
  11038. }
  11039. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11040. /* If the queue is full, wait */
  11041. while (ctx->stop_flag == 0
  11042. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11043. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11044. }
  11045. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11046. /* Copy socket to the queue and increment head */
  11047. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11048. ctx->sq_head++;
  11049. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11050. }
  11051. (void)pthread_cond_signal(&ctx->sq_full);
  11052. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11053. #undef QUEUE_SIZE
  11054. }
  11055. #endif /* ALTERNATIVE_QUEUE */
  11056. struct worker_thread_args {
  11057. struct mg_context *ctx;
  11058. int index;
  11059. };
  11060. static void *
  11061. worker_thread_run(struct worker_thread_args *thread_args)
  11062. {
  11063. struct mg_context *ctx = thread_args->ctx;
  11064. struct mg_connection *conn;
  11065. struct mg_workerTLS tls;
  11066. #if defined(MG_LEGACY_INTERFACE)
  11067. uint32_t addr;
  11068. #endif
  11069. mg_set_thread_name("worker");
  11070. tls.is_master = 0;
  11071. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11072. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11073. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11074. #endif
  11075. if (ctx->callbacks.init_thread) {
  11076. /* call init_thread for a worker thread (type 1) */
  11077. ctx->callbacks.init_thread(ctx, 1);
  11078. }
  11079. conn =
  11080. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11081. if (conn == NULL) {
  11082. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11083. } else {
  11084. pthread_setspecific(sTlsKey, &tls);
  11085. conn->buf_size = MAX_REQUEST_SIZE;
  11086. conn->buf = (char *)(conn + 1);
  11087. conn->ctx = ctx;
  11088. conn->thread_index = thread_args->index;
  11089. conn->request_info.user_data = ctx->user_data;
  11090. /* Allocate a mutex for this connection to allow communication both
  11091. * within the request handler and from elsewhere in the application
  11092. */
  11093. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11094. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11095. * signal sq_empty condvar to wake up the master waiting in
  11096. * produce_socket() */
  11097. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11098. conn->conn_birth_time = time(NULL);
  11099. /* Fill in IP, port info early so even if SSL setup below fails,
  11100. * error handler would have the corresponding info.
  11101. * Thanks to Johannes Winkelmann for the patch.
  11102. */
  11103. #if defined(USE_IPV6)
  11104. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11105. conn->request_info.remote_port =
  11106. ntohs(conn->client.rsa.sin6.sin6_port);
  11107. } else
  11108. #endif
  11109. {
  11110. conn->request_info.remote_port =
  11111. ntohs(conn->client.rsa.sin.sin_port);
  11112. }
  11113. sockaddr_to_string(conn->request_info.remote_addr,
  11114. sizeof(conn->request_info.remote_addr),
  11115. &conn->client.rsa);
  11116. #if defined(MG_LEGACY_INTERFACE)
  11117. /* This legacy interface only works for the IPv4 case */
  11118. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11119. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11120. #endif
  11121. conn->request_info.is_ssl = conn->client.is_ssl;
  11122. if (!conn->client.is_ssl
  11123. #ifndef NO_SSL
  11124. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  11125. #endif
  11126. ) {
  11127. process_new_connection(conn);
  11128. }
  11129. close_connection(conn);
  11130. }
  11131. }
  11132. pthread_setspecific(sTlsKey, NULL);
  11133. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11134. CloseHandle(tls.pthread_cond_helper_mutex);
  11135. #endif
  11136. pthread_mutex_destroy(&conn->mutex);
  11137. mg_free(conn);
  11138. DEBUG_TRACE("%s", "exiting");
  11139. return NULL;
  11140. }
  11141. /* Threads have different return types on Windows and Unix. */
  11142. #ifdef _WIN32
  11143. static unsigned __stdcall worker_thread(void *thread_func_param)
  11144. {
  11145. struct worker_thread_args *pwta =
  11146. (struct worker_thread_args *)thread_func_param;
  11147. worker_thread_run(pwta);
  11148. mg_free(thread_func_param);
  11149. return 0;
  11150. }
  11151. #else
  11152. static void *
  11153. worker_thread(void *thread_func_param)
  11154. {
  11155. struct worker_thread_args *pwta =
  11156. (struct worker_thread_args *)thread_func_param;
  11157. worker_thread_run(pwta);
  11158. mg_free(thread_func_param);
  11159. return NULL;
  11160. }
  11161. #endif /* _WIN32 */
  11162. static void
  11163. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11164. {
  11165. struct socket so;
  11166. char src_addr[IP_ADDR_STR_LEN];
  11167. socklen_t len = sizeof(so.rsa);
  11168. int on = 1;
  11169. int timeout;
  11170. if (!listener) {
  11171. return;
  11172. }
  11173. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11174. == INVALID_SOCKET) {
  11175. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11176. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11177. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11178. closesocket(so.sock);
  11179. so.sock = INVALID_SOCKET;
  11180. } else {
  11181. /* Put so socket structure into the queue */
  11182. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11183. set_close_on_exec(so.sock, fc(ctx));
  11184. so.is_ssl = listener->is_ssl;
  11185. so.ssl_redir = listener->ssl_redir;
  11186. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11187. mg_cry(fc(ctx),
  11188. "%s: getsockname() failed: %s",
  11189. __func__,
  11190. strerror(ERRNO));
  11191. }
  11192. /* Set TCP keep-alive. This is needed because if HTTP-level
  11193. * keep-alive
  11194. * is enabled, and client resets the connection, server won't get
  11195. * TCP FIN or RST and will keep the connection open forever. With
  11196. * TCP keep-alive, next keep-alive handshake will figure out that
  11197. * the client is down and will close the server end.
  11198. * Thanks to Igor Klopov who suggested the patch. */
  11199. if (setsockopt(so.sock,
  11200. SOL_SOCKET,
  11201. SO_KEEPALIVE,
  11202. (SOCK_OPT_TYPE)&on,
  11203. sizeof(on)) != 0) {
  11204. mg_cry(fc(ctx),
  11205. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11206. __func__,
  11207. strerror(ERRNO));
  11208. }
  11209. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11210. * to effectively fill up the underlying IP packet payload and
  11211. * reduce the overhead of sending lots of small buffers. However
  11212. * this hurts the server's throughput (ie. operations per second)
  11213. * when HTTP 1.1 persistent connections are used and the responses
  11214. * are relatively small (eg. less than 1400 bytes).
  11215. */
  11216. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11217. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11218. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11219. mg_cry(fc(ctx),
  11220. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11221. __func__,
  11222. strerror(ERRNO));
  11223. }
  11224. }
  11225. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11226. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11227. } else {
  11228. timeout = -1;
  11229. }
  11230. if (timeout > 0) {
  11231. set_sock_timeout(so.sock, timeout);
  11232. }
  11233. produce_socket(ctx, &so);
  11234. }
  11235. }
  11236. static void
  11237. master_thread_run(void *thread_func_param)
  11238. {
  11239. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11240. struct mg_workerTLS tls;
  11241. struct pollfd *pfd;
  11242. unsigned int i;
  11243. unsigned int workerthreadcount;
  11244. if (!ctx) {
  11245. return;
  11246. }
  11247. mg_set_thread_name("master");
  11248. /* Increase priority of the master thread */
  11249. #if defined(_WIN32)
  11250. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11251. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11252. int min_prio = sched_get_priority_min(SCHED_RR);
  11253. int max_prio = sched_get_priority_max(SCHED_RR);
  11254. if ((min_prio >= 0) && (max_prio >= 0)
  11255. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11256. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11257. struct sched_param sched_param = {0};
  11258. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11259. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11260. }
  11261. #endif
  11262. /* Initialize thread local storage */
  11263. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11264. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11265. #endif
  11266. tls.is_master = 1;
  11267. pthread_setspecific(sTlsKey, &tls);
  11268. if (ctx->callbacks.init_thread) {
  11269. /* Callback for the master thread (type 0) */
  11270. ctx->callbacks.init_thread(ctx, 0);
  11271. }
  11272. /* Server starts *now* */
  11273. ctx->start_time = time(NULL);
  11274. /* Start the server */
  11275. pfd = ctx->listening_socket_fds;
  11276. while (ctx->stop_flag == 0) {
  11277. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11278. pfd[i].fd = ctx->listening_sockets[i].sock;
  11279. pfd[i].events = POLLIN;
  11280. }
  11281. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11282. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11283. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11284. * successful poll, and POLLIN is defined as
  11285. * (POLLRDNORM | POLLRDBAND)
  11286. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11287. * pfd[i].revents == POLLIN. */
  11288. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11289. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11290. }
  11291. }
  11292. }
  11293. }
  11294. /* Here stop_flag is 1 - Initiate shutdown. */
  11295. DEBUG_TRACE("%s", "stopping workers");
  11296. /* Stop signal received: somebody called mg_stop. Quit. */
  11297. close_all_listening_sockets(ctx);
  11298. /* Wakeup workers that are waiting for connections to handle. */
  11299. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11300. #if defined(ALTERNATIVE_QUEUE)
  11301. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11302. event_signal(ctx->client_wait_events[i]);
  11303. /* Since we know all sockets, we can shutdown the connections. */
  11304. if (ctx->client_socks[i].in_use) {
  11305. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11306. }
  11307. }
  11308. #else
  11309. pthread_cond_broadcast(&ctx->sq_full);
  11310. #endif
  11311. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11312. /* Join all worker threads to avoid leaking threads. */
  11313. workerthreadcount = ctx->cfg_worker_threads;
  11314. for (i = 0; i < workerthreadcount; i++) {
  11315. if (ctx->workerthreadids[i] != 0) {
  11316. mg_join_thread(ctx->workerthreadids[i]);
  11317. }
  11318. }
  11319. #if !defined(NO_SSL)
  11320. if (ctx->ssl_ctx != NULL) {
  11321. uninitialize_ssl(ctx);
  11322. }
  11323. #endif
  11324. DEBUG_TRACE("%s", "exiting");
  11325. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11326. CloseHandle(tls.pthread_cond_helper_mutex);
  11327. #endif
  11328. pthread_setspecific(sTlsKey, NULL);
  11329. /* Signal mg_stop() that we're done.
  11330. * WARNING: This must be the very last thing this
  11331. * thread does, as ctx becomes invalid after this line. */
  11332. ctx->stop_flag = 2;
  11333. }
  11334. /* Threads have different return types on Windows and Unix. */
  11335. #ifdef _WIN32
  11336. static unsigned __stdcall master_thread(void *thread_func_param)
  11337. {
  11338. master_thread_run(thread_func_param);
  11339. return 0;
  11340. }
  11341. #else
  11342. static void *
  11343. master_thread(void *thread_func_param)
  11344. {
  11345. master_thread_run(thread_func_param);
  11346. return NULL;
  11347. }
  11348. #endif /* _WIN32 */
  11349. static void
  11350. free_context(struct mg_context *ctx)
  11351. {
  11352. int i;
  11353. struct mg_handler_info *tmp_rh;
  11354. if (ctx == NULL) {
  11355. return;
  11356. }
  11357. if (ctx->callbacks.exit_context) {
  11358. ctx->callbacks.exit_context(ctx);
  11359. }
  11360. /* All threads exited, no sync is needed. Destroy thread mutex and
  11361. * condvars
  11362. */
  11363. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11364. #if defined(ALTERNATIVE_QUEUE)
  11365. mg_free(ctx->client_socks);
  11366. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11367. event_destroy(ctx->client_wait_events[i]);
  11368. }
  11369. mg_free(ctx->client_wait_events);
  11370. #else
  11371. (void)pthread_cond_destroy(&ctx->sq_empty);
  11372. (void)pthread_cond_destroy(&ctx->sq_full);
  11373. #endif
  11374. /* Destroy other context global data structures mutex */
  11375. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11376. #if defined(USE_TIMERS)
  11377. timers_exit(ctx);
  11378. #endif
  11379. /* Deallocate config parameters */
  11380. for (i = 0; i < NUM_OPTIONS; i++) {
  11381. if (ctx->config[i] != NULL) {
  11382. #if defined(_MSC_VER)
  11383. #pragma warning(suppress : 6001)
  11384. #endif
  11385. mg_free(ctx->config[i]);
  11386. }
  11387. }
  11388. /* Deallocate request handlers */
  11389. while (ctx->handlers) {
  11390. tmp_rh = ctx->handlers;
  11391. ctx->handlers = tmp_rh->next;
  11392. mg_free(tmp_rh->uri);
  11393. mg_free(tmp_rh);
  11394. }
  11395. #ifndef NO_SSL
  11396. /* Deallocate SSL context */
  11397. if (ctx->ssl_ctx != NULL) {
  11398. SSL_CTX_free(ctx->ssl_ctx);
  11399. }
  11400. #endif /* !NO_SSL */
  11401. /* Deallocate worker thread ID array */
  11402. if (ctx->workerthreadids != NULL) {
  11403. mg_free(ctx->workerthreadids);
  11404. }
  11405. /* Deallocate the tls variable */
  11406. if (mg_atomic_dec(&sTlsInit) == 0) {
  11407. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11408. DeleteCriticalSection(&global_log_file_lock);
  11409. #endif /* _WIN32 && !__SYMBIAN32__ */
  11410. #if !defined(_WIN32)
  11411. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11412. #endif
  11413. pthread_key_delete(sTlsKey);
  11414. }
  11415. /* deallocate system name string */
  11416. mg_free(ctx->systemName);
  11417. /* Deallocate context itself */
  11418. mg_free(ctx);
  11419. }
  11420. void
  11421. mg_stop(struct mg_context *ctx)
  11422. {
  11423. pthread_t mt;
  11424. if (!ctx) {
  11425. return;
  11426. }
  11427. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11428. * two threads is not allowed. */
  11429. mt = ctx->masterthreadid;
  11430. if (mt == 0) {
  11431. return;
  11432. }
  11433. ctx->masterthreadid = 0;
  11434. /* Set stop flag, so all threads know they have to exit. */
  11435. ctx->stop_flag = 1;
  11436. /* Wait until everything has stopped. */
  11437. while (ctx->stop_flag != 2) {
  11438. (void)mg_sleep(10);
  11439. }
  11440. mg_join_thread(mt);
  11441. free_context(ctx);
  11442. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11443. (void)WSACleanup();
  11444. #endif /* _WIN32 && !__SYMBIAN32__ */
  11445. }
  11446. static void
  11447. get_system_name(char **sysName)
  11448. {
  11449. #if defined(_WIN32)
  11450. #if !defined(__SYMBIAN32__)
  11451. #if defined(_WIN32_WCE)
  11452. *sysName = mg_strdup("WinCE");
  11453. #else
  11454. char name[128];
  11455. DWORD dwVersion = 0;
  11456. DWORD dwMajorVersion = 0;
  11457. DWORD dwMinorVersion = 0;
  11458. DWORD dwBuild = 0;
  11459. #ifdef _MSC_VER
  11460. #pragma warning(push)
  11461. // GetVersion was declared deprecated
  11462. #pragma warning(disable : 4996)
  11463. #endif
  11464. dwVersion = GetVersion();
  11465. #ifdef _MSC_VER
  11466. #pragma warning(pop)
  11467. #endif
  11468. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11469. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11470. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11471. (void)dwBuild;
  11472. sprintf(name,
  11473. "Windows %u.%u",
  11474. (unsigned)dwMajorVersion,
  11475. (unsigned)dwMinorVersion);
  11476. *sysName = mg_strdup(name);
  11477. #endif
  11478. #else
  11479. *sysName = mg_strdup("Symbian");
  11480. #endif
  11481. #else
  11482. struct utsname name;
  11483. memset(&name, 0, sizeof(name));
  11484. uname(&name);
  11485. *sysName = mg_strdup(name.sysname);
  11486. #endif
  11487. }
  11488. struct mg_context *
  11489. mg_start(const struct mg_callbacks *callbacks,
  11490. void *user_data,
  11491. const char **options)
  11492. {
  11493. struct mg_context *ctx;
  11494. const char *name, *value, *default_value;
  11495. int idx, ok, workerthreadcount;
  11496. unsigned int i;
  11497. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11498. struct mg_workerTLS tls;
  11499. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11500. WSADATA data;
  11501. WSAStartup(MAKEWORD(2, 2), &data);
  11502. #endif /* _WIN32 && !__SYMBIAN32__ */
  11503. /* Allocate context and initialize reasonable general case defaults. */
  11504. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11505. return NULL;
  11506. }
  11507. /* Random number generator will initialize at the first call */
  11508. ctx->auth_nonce_mask =
  11509. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11510. if (mg_atomic_inc(&sTlsInit) == 1) {
  11511. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11512. InitializeCriticalSection(&global_log_file_lock);
  11513. #endif /* _WIN32 && !__SYMBIAN32__ */
  11514. #if !defined(_WIN32)
  11515. pthread_mutexattr_init(&pthread_mutex_attr);
  11516. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11517. #endif
  11518. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11519. /* Fatal error - abort start. However, this situation should
  11520. * never
  11521. * occur in practice. */
  11522. mg_atomic_dec(&sTlsInit);
  11523. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11524. mg_free(ctx);
  11525. return NULL;
  11526. }
  11527. } else {
  11528. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11529. * initialized. */
  11530. mg_sleep(1);
  11531. }
  11532. tls.is_master = -1;
  11533. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11534. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11535. tls.pthread_cond_helper_mutex = NULL;
  11536. #endif
  11537. pthread_setspecific(sTlsKey, &tls);
  11538. #if defined(USE_LUA)
  11539. lua_init_optional_libraries();
  11540. #endif
  11541. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11542. #if !defined(ALTERNATIVE_QUEUE)
  11543. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11544. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11545. #endif
  11546. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11547. if (!ok) {
  11548. /* Fatal error - abort start. However, this situation should never
  11549. * occur in practice. */
  11550. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11551. mg_free(ctx);
  11552. pthread_setspecific(sTlsKey, NULL);
  11553. return NULL;
  11554. }
  11555. if (callbacks) {
  11556. ctx->callbacks = *callbacks;
  11557. exit_callback = callbacks->exit_context;
  11558. ctx->callbacks.exit_context = 0;
  11559. }
  11560. ctx->user_data = user_data;
  11561. ctx->handlers = NULL;
  11562. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11563. ctx->shared_lua_websockets = 0;
  11564. #endif
  11565. while (options && (name = *options++) != NULL) {
  11566. if ((idx = get_option_index(name)) == -1) {
  11567. mg_cry(fc(ctx), "Invalid option: %s", name);
  11568. free_context(ctx);
  11569. pthread_setspecific(sTlsKey, NULL);
  11570. return NULL;
  11571. } else if ((value = *options++) == NULL) {
  11572. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11573. free_context(ctx);
  11574. pthread_setspecific(sTlsKey, NULL);
  11575. return NULL;
  11576. }
  11577. if (ctx->config[idx] != NULL) {
  11578. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11579. mg_free(ctx->config[idx]);
  11580. }
  11581. ctx->config[idx] = mg_strdup(value);
  11582. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11583. }
  11584. /* Set default value if needed */
  11585. for (i = 0; config_options[i].name != NULL; i++) {
  11586. default_value = config_options[i].default_value;
  11587. if (ctx->config[i] == NULL && default_value != NULL) {
  11588. ctx->config[i] = mg_strdup(default_value);
  11589. }
  11590. }
  11591. #if defined(NO_FILES)
  11592. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11593. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11594. free_context(ctx);
  11595. pthread_setspecific(sTlsKey, NULL);
  11596. return NULL;
  11597. }
  11598. #endif
  11599. get_system_name(&ctx->systemName);
  11600. /* NOTE(lsm): order is important here. SSL certificates must
  11601. * be initialized before listening ports. UID must be set last. */
  11602. if (!set_gpass_option(ctx) ||
  11603. #if !defined(NO_SSL)
  11604. !set_ssl_option(ctx) ||
  11605. #endif
  11606. !set_ports_option(ctx) ||
  11607. #if !defined(_WIN32)
  11608. !set_uid_option(ctx) ||
  11609. #endif
  11610. !set_acl_option(ctx)) {
  11611. free_context(ctx);
  11612. pthread_setspecific(sTlsKey, NULL);
  11613. return NULL;
  11614. }
  11615. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11616. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11617. * won't kill the whole process. */
  11618. (void)signal(SIGPIPE, SIG_IGN);
  11619. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11620. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11621. if (workerthreadcount > MAX_WORKER_THREADS) {
  11622. mg_cry(fc(ctx), "Too many worker threads");
  11623. free_context(ctx);
  11624. pthread_setspecific(sTlsKey, NULL);
  11625. return NULL;
  11626. }
  11627. if (workerthreadcount > 0) {
  11628. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11629. ctx->workerthreadids =
  11630. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11631. if (ctx->workerthreadids == NULL) {
  11632. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11633. free_context(ctx);
  11634. pthread_setspecific(sTlsKey, NULL);
  11635. return NULL;
  11636. }
  11637. #if defined(ALTERNATIVE_QUEUE)
  11638. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11639. ctx->cfg_worker_threads);
  11640. if (ctx->client_wait_events == NULL) {
  11641. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11642. mg_free(ctx->workerthreadids);
  11643. free_context(ctx);
  11644. pthread_setspecific(sTlsKey, NULL);
  11645. return NULL;
  11646. }
  11647. ctx->client_socks =
  11648. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11649. if (ctx->client_wait_events == NULL) {
  11650. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11651. mg_free(ctx->client_socks);
  11652. mg_free(ctx->workerthreadids);
  11653. free_context(ctx);
  11654. pthread_setspecific(sTlsKey, NULL);
  11655. return NULL;
  11656. }
  11657. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11658. ctx->client_wait_events[i] = event_create();
  11659. if (ctx->client_wait_events[i] == 0) {
  11660. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11661. /* TODO: clean all and exit */
  11662. }
  11663. }
  11664. #endif
  11665. }
  11666. #if defined(USE_TIMERS)
  11667. if (timers_init(ctx) != 0) {
  11668. mg_cry(fc(ctx), "Error creating timers");
  11669. free_context(ctx);
  11670. pthread_setspecific(sTlsKey, NULL);
  11671. return NULL;
  11672. }
  11673. #endif
  11674. /* Context has been created - init user libraries */
  11675. if (ctx->callbacks.init_context) {
  11676. ctx->callbacks.init_context(ctx);
  11677. }
  11678. ctx->callbacks.exit_context = exit_callback;
  11679. ctx->context_type = 1; /* server context */
  11680. /* Start master (listening) thread */
  11681. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11682. /* Start worker threads */
  11683. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11684. struct worker_thread_args *wta =
  11685. mg_malloc(sizeof(struct worker_thread_args));
  11686. if (wta) {
  11687. wta->ctx = ctx;
  11688. wta->index = (int)i;
  11689. }
  11690. if ((wta == NULL)
  11691. || (mg_start_thread_with_id(worker_thread,
  11692. wta,
  11693. &ctx->workerthreadids[i]) != 0)) {
  11694. /* thread was not created */
  11695. if (wta != NULL) {
  11696. mg_free(wta);
  11697. }
  11698. if (i > 0) {
  11699. mg_cry(fc(ctx),
  11700. "Cannot start worker thread %i: error %ld",
  11701. i + 1,
  11702. (long)ERRNO);
  11703. } else {
  11704. mg_cry(fc(ctx),
  11705. "Cannot create threads: error %ld",
  11706. (long)ERRNO);
  11707. free_context(ctx);
  11708. pthread_setspecific(sTlsKey, NULL);
  11709. return NULL;
  11710. }
  11711. break;
  11712. }
  11713. }
  11714. pthread_setspecific(sTlsKey, NULL);
  11715. return ctx;
  11716. }
  11717. /* Feature check API function */
  11718. unsigned
  11719. mg_check_feature(unsigned feature)
  11720. {
  11721. static const unsigned feature_set = 0
  11722. /* Set bits for available features according to API documentation.
  11723. * This bit mask is created at compile time, according to the active
  11724. * preprocessor defines. It is a single const value at runtime. */
  11725. #if !defined(NO_FILES)
  11726. | 0x0001u
  11727. #endif
  11728. #if !defined(NO_SSL)
  11729. | 0x0002u
  11730. #endif
  11731. #if !defined(NO_CGI)
  11732. | 0x0004u
  11733. #endif
  11734. #if defined(USE_IPV6)
  11735. | 0x0008u
  11736. #endif
  11737. #if defined(USE_WEBSOCKET)
  11738. | 0x0010u
  11739. #endif
  11740. #if defined(USE_LUA)
  11741. | 0x0020u
  11742. #endif
  11743. #if defined(USE_DUKTAPE)
  11744. | 0x0040u
  11745. #endif
  11746. #if !defined(NO_CACHING)
  11747. | 0x0080u
  11748. #endif
  11749. /* Set some extra bits not defined in the API documentation.
  11750. * These bits may change without further notice. */
  11751. #if defined(MG_LEGACY_INTERFACE)
  11752. | 0x8000u
  11753. #endif
  11754. #if defined(MEMORY_DEBUGGING)
  11755. | 0x0100u
  11756. #endif
  11757. #if defined(USE_TIMERS)
  11758. | 0x0200u
  11759. #endif
  11760. #if !defined(NO_NONCE_CHECK)
  11761. | 0x0400u
  11762. #endif
  11763. #if !defined(NO_POPEN)
  11764. | 0x0800u
  11765. #endif
  11766. ;
  11767. return (feature & feature_set);
  11768. }