civetweb.c 359 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888
  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. /* Determine if the current OSX version supports clock_gettime */
  122. #ifdef __APPLE__
  123. #include <AvailabilityMacros.h>
  124. #ifndef MAC_OS_X_VERSION_10_12
  125. #define MAC_OS_X_VERSION_10_12 101200
  126. #endif
  127. #endif
  128. #define CIVETWEB_APPLE_HAVE_CLOCK_GETTIME defined(__APPLE__) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
  129. #if !(CIVETWEB_APPLE_HAVE_CLOCK_GETTIME)
  130. /* clock_gettime is not implemented on OSX prior to 10.12 */
  131. int clock_gettime(int clk_id, struct timespec *t);
  132. int
  133. clock_gettime(int clk_id, struct timespec *t)
  134. {
  135. memset(t, 0, sizeof(*t));
  136. if (clk_id == CLOCK_REALTIME) {
  137. struct timeval now;
  138. int rv = gettimeofday(&now, NULL);
  139. if (rv) {
  140. return rv;
  141. }
  142. t->tv_sec = now.tv_sec;
  143. t->tv_nsec = now.tv_usec * 1000;
  144. return 0;
  145. } else if (clk_id == CLOCK_MONOTONIC) {
  146. static uint64_t clock_start_time = 0;
  147. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  148. uint64_t now = mach_absolute_time();
  149. if (clock_start_time == 0) {
  150. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  151. #if defined(DEBUG)
  152. assert(mach_status == KERN_SUCCESS);
  153. #else
  154. /* appease "unused variable" warning for release builds */
  155. (void)mach_status;
  156. #endif
  157. clock_start_time = now;
  158. }
  159. now = (uint64_t)((double)(now - clock_start_time)
  160. * (double)timebase_ifo.numer
  161. / (double)timebase_ifo.denom);
  162. t->tv_sec = now / 1000000000;
  163. t->tv_nsec = now % 1000000000;
  164. return 0;
  165. }
  166. return -1; /* EINVAL - Clock ID is unknown */
  167. }
  168. #endif
  169. #endif
  170. #include <time.h>
  171. #include <stdlib.h>
  172. #include <stdarg.h>
  173. #include <assert.h>
  174. #include <string.h>
  175. #include <ctype.h>
  176. #include <limits.h>
  177. #include <stddef.h>
  178. #include <stdio.h>
  179. #ifndef MAX_WORKER_THREADS
  180. #define MAX_WORKER_THREADS (1024 * 64)
  181. #endif
  182. #define SHUTDOWN_RD (0)
  183. #define SHUTDOWN_WR (1)
  184. #define SHUTDOWN_BOTH (2)
  185. mg_static_assert(MAX_WORKER_THREADS >= 1,
  186. "worker threads must be a positive number");
  187. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  188. "size_t data type size check");
  189. #if defined(_WIN32) \
  190. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  191. #include <windows.h>
  192. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  193. #include <ws2tcpip.h>
  194. typedef const char *SOCK_OPT_TYPE;
  195. #if !defined(PATH_MAX)
  196. #define PATH_MAX (MAX_PATH)
  197. #endif
  198. #if !defined(PATH_MAX)
  199. #define PATH_MAX (4096)
  200. #endif
  201. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  202. #ifndef _IN_PORT_T
  203. #ifndef in_port_t
  204. #define in_port_t u_short
  205. #endif
  206. #endif
  207. #ifndef _WIN32_WCE
  208. #include <process.h>
  209. #include <direct.h>
  210. #include <io.h>
  211. #else /* _WIN32_WCE */
  212. #define NO_CGI /* WinCE has no pipes */
  213. #define NO_POPEN /* WinCE has no popen */
  214. typedef long off_t;
  215. #define errno ((int)(GetLastError()))
  216. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  217. #endif /* _WIN32_WCE */
  218. #define MAKEUQUAD(lo, hi) \
  219. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  220. #define RATE_DIFF (10000000) /* 100 nsecs */
  221. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  222. #define SYS2UNIX_TIME(lo, hi) \
  223. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  224. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  225. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  226. * Also use _strtoui64 on modern M$ compilers */
  227. #if defined(_MSC_VER)
  228. #if (_MSC_VER < 1300)
  229. #define STRX(x) #x
  230. #define STR(x) STRX(x)
  231. #define __func__ __FILE__ ":" STR(__LINE__)
  232. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  233. #define strtoll(x, y, z) (_atoi64(x))
  234. #else
  235. #define __func__ __FUNCTION__
  236. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  237. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  238. #endif
  239. #endif /* _MSC_VER */
  240. #define ERRNO ((int)(GetLastError()))
  241. #define NO_SOCKLEN_T
  242. #if defined(_WIN64) || defined(__MINGW64__)
  243. #define SSL_LIB "ssleay64.dll"
  244. #define CRYPTO_LIB "libeay64.dll"
  245. #else
  246. #define SSL_LIB "ssleay32.dll"
  247. #define CRYPTO_LIB "libeay32.dll"
  248. #endif
  249. #define O_NONBLOCK (0)
  250. #ifndef W_OK
  251. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  252. #endif
  253. #if !defined(EWOULDBLOCK)
  254. #define EWOULDBLOCK WSAEWOULDBLOCK
  255. #endif /* !EWOULDBLOCK */
  256. #define _POSIX_
  257. #define INT64_FMT "I64d"
  258. #define UINT64_FMT "I64u"
  259. #define WINCDECL __cdecl
  260. #define vsnprintf_impl _vsnprintf
  261. #define access _access
  262. #define mg_sleep(x) (Sleep(x))
  263. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  264. #ifndef popen
  265. #define popen(x, y) (_popen(x, y))
  266. #endif
  267. #ifndef pclose
  268. #define pclose(x) (_pclose(x))
  269. #endif
  270. #define close(x) (_close(x))
  271. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  272. #define RTLD_LAZY (0)
  273. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  274. #define fdopen(x, y) (_fdopen((x), (y)))
  275. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  276. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  277. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  278. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  279. #define sleep(x) (Sleep((x)*1000))
  280. #define rmdir(x) (_rmdir(x))
  281. #define timegm(x) (_mkgmtime(x))
  282. #if !defined(fileno)
  283. #define fileno(x) (_fileno(x))
  284. #endif /* !fileno MINGW #defines fileno */
  285. typedef HANDLE pthread_mutex_t;
  286. typedef DWORD pthread_key_t;
  287. typedef HANDLE pthread_t;
  288. typedef struct {
  289. CRITICAL_SECTION threadIdSec;
  290. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  291. } pthread_cond_t;
  292. #ifndef __clockid_t_defined
  293. typedef DWORD clockid_t;
  294. #endif
  295. #ifndef CLOCK_MONOTONIC
  296. #define CLOCK_MONOTONIC (1)
  297. #endif
  298. #ifndef CLOCK_REALTIME
  299. #define CLOCK_REALTIME (2)
  300. #endif
  301. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  302. #define _TIMESPEC_DEFINED
  303. #endif
  304. #ifndef _TIMESPEC_DEFINED
  305. struct timespec {
  306. time_t tv_sec; /* seconds */
  307. long tv_nsec; /* nanoseconds */
  308. };
  309. #endif
  310. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  311. static int pthread_mutex_lock(pthread_mutex_t *);
  312. static int pthread_mutex_unlock(pthread_mutex_t *);
  313. static void path_to_unicode(const struct mg_connection *conn,
  314. const char *path,
  315. wchar_t *wbuf,
  316. size_t wbuf_len);
  317. struct file;
  318. static const char *
  319. mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  320. #if defined(HAVE_STDINT)
  321. #include <stdint.h>
  322. #else
  323. typedef unsigned char uint8_t;
  324. typedef unsigned short uint16_t;
  325. typedef unsigned int uint32_t;
  326. typedef unsigned __int64 uint64_t;
  327. typedef __int64 int64_t;
  328. #ifndef INT64_MAX
  329. #define INT64_MAX (9223372036854775807)
  330. #endif
  331. #endif /* HAVE_STDINT */
  332. /* POSIX dirent interface */
  333. struct dirent {
  334. char d_name[PATH_MAX];
  335. };
  336. typedef struct DIR {
  337. HANDLE handle;
  338. WIN32_FIND_DATAW info;
  339. struct dirent result;
  340. } DIR;
  341. #if defined(_WIN32) && !defined(POLLIN)
  342. #ifndef HAVE_POLL
  343. struct pollfd {
  344. SOCKET fd;
  345. short events;
  346. short revents;
  347. };
  348. #define POLLIN (0x0300)
  349. #endif
  350. #endif
  351. /* Mark required libraries */
  352. #if defined(_MSC_VER)
  353. #pragma comment(lib, "Ws2_32.lib")
  354. #endif
  355. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  356. WINDOWS / UNIX include block */
  357. #include <sys/wait.h>
  358. #include <sys/socket.h>
  359. #include <sys/poll.h>
  360. #include <netinet/in.h>
  361. #include <arpa/inet.h>
  362. #include <sys/time.h>
  363. #include <sys/utsname.h>
  364. #include <stdint.h>
  365. #include <inttypes.h>
  366. #include <netdb.h>
  367. #include <netinet/tcp.h>
  368. typedef const void *SOCK_OPT_TYPE;
  369. #if defined(ANDROID)
  370. typedef unsigned short int in_port_t;
  371. #endif
  372. #include <pwd.h>
  373. #include <unistd.h>
  374. #include <grp.h>
  375. #include <dirent.h>
  376. #define vsnprintf_impl vsnprintf
  377. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  378. #include <dlfcn.h>
  379. #endif
  380. #include <pthread.h>
  381. #if defined(__MACH__)
  382. #define SSL_LIB "libssl.dylib"
  383. #define CRYPTO_LIB "libcrypto.dylib"
  384. #else
  385. #if !defined(SSL_LIB)
  386. #define SSL_LIB "libssl.so"
  387. #endif
  388. #if !defined(CRYPTO_LIB)
  389. #define CRYPTO_LIB "libcrypto.so"
  390. #endif
  391. #endif
  392. #ifndef O_BINARY
  393. #define O_BINARY (0)
  394. #endif /* O_BINARY */
  395. #define closesocket(a) (close(a))
  396. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  397. #define mg_remove(conn, x) (remove(x))
  398. #define mg_sleep(x) (usleep((x)*1000))
  399. #define mg_opendir(conn, x) (opendir(x))
  400. #define mg_closedir(x) (closedir(x))
  401. #define mg_readdir(x) (readdir(x))
  402. #define ERRNO (errno)
  403. #define INVALID_SOCKET (-1)
  404. #define INT64_FMT PRId64
  405. #define UINT64_FMT PRIu64
  406. typedef int SOCKET;
  407. #define WINCDECL
  408. #if defined(__hpux)
  409. /* HPUX 11 does not have monotonic, fall back to realtime */
  410. #ifndef CLOCK_MONOTONIC
  411. #define CLOCK_MONOTONIC CLOCK_REALTIME
  412. #endif
  413. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  414. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  415. * the prototypes use int* rather than socklen_t* which matches the
  416. * actual library expectation. When called with the wrong size arg
  417. * accept() returns a zero client inet addr and check_acl() always
  418. * fails. Since socklen_t is widely used below, just force replace
  419. * their typedef with int. - DTL
  420. */
  421. #define socklen_t int
  422. #endif /* hpux */
  423. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  424. WINDOWS / UNIX include block */
  425. /* va_copy should always be a macro, C99 and C++11 - DTL */
  426. #ifndef va_copy
  427. #define va_copy(x, y) ((x) = (y))
  428. #endif
  429. #ifdef _WIN32
  430. /* Create substitutes for POSIX functions in Win32. */
  431. #if defined(__MINGW32__)
  432. /* Show no warning in case system functions are not used. */
  433. #pragma GCC diagnostic push
  434. #pragma GCC diagnostic ignored "-Wunused-function"
  435. #endif
  436. static CRITICAL_SECTION global_log_file_lock;
  437. static DWORD
  438. pthread_self(void)
  439. {
  440. return GetCurrentThreadId();
  441. }
  442. static int
  443. pthread_key_create(
  444. pthread_key_t *key,
  445. void (*_ignored)(void *) /* destructor not supported for Windows */
  446. )
  447. {
  448. (void)_ignored;
  449. if ((key != 0)) {
  450. *key = TlsAlloc();
  451. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  452. }
  453. return -2;
  454. }
  455. static int
  456. pthread_key_delete(pthread_key_t key)
  457. {
  458. return TlsFree(key) ? 0 : 1;
  459. }
  460. static int
  461. pthread_setspecific(pthread_key_t key, void *value)
  462. {
  463. return TlsSetValue(key, value) ? 0 : 1;
  464. }
  465. static void *
  466. pthread_getspecific(pthread_key_t key)
  467. {
  468. return TlsGetValue(key);
  469. }
  470. #if defined(__MINGW32__)
  471. /* Enable unused function warning again */
  472. #pragma GCC diagnostic pop
  473. #endif
  474. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  475. #else
  476. static pthread_mutexattr_t pthread_mutex_attr;
  477. #endif /* _WIN32 */
  478. #define PASSWORDS_FILE_NAME ".htpasswd"
  479. #define CGI_ENVIRONMENT_SIZE (4096)
  480. #define MAX_CGI_ENVIR_VARS (256)
  481. #define MG_BUF_LEN (8192)
  482. #ifndef MAX_REQUEST_SIZE
  483. #define MAX_REQUEST_SIZE (16384)
  484. #endif
  485. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  486. "request size length must be a positive number");
  487. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  488. #if !defined(DEBUG_TRACE)
  489. #if defined(DEBUG)
  490. #if defined(_WIN32_WCE)
  491. /* Create substitutes for POSIX functions in Win32. */
  492. #if defined(__MINGW32__)
  493. /* Show no warning in case system functions are not used. */
  494. #pragma GCC diagnostic push
  495. #pragma GCC diagnostic ignored "-Wunused-function"
  496. #endif
  497. static time_t
  498. time(time_t *ptime)
  499. {
  500. time_t t;
  501. SYSTEMTIME st;
  502. FILETIME ft;
  503. GetSystemTime(&st);
  504. SystemTimeToFileTime(&st, &ft);
  505. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  506. if (ptime != NULL) {
  507. *ptime = t;
  508. }
  509. return t;
  510. }
  511. static struct tm *
  512. localtime_s(const time_t *ptime, struct tm *ptm)
  513. {
  514. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  515. FILETIME ft, lft;
  516. SYSTEMTIME st;
  517. TIME_ZONE_INFORMATION tzinfo;
  518. if (ptm == NULL) {
  519. return NULL;
  520. }
  521. *(int64_t *)&ft = t;
  522. FileTimeToLocalFileTime(&ft, &lft);
  523. FileTimeToSystemTime(&lft, &st);
  524. ptm->tm_year = st.wYear - 1900;
  525. ptm->tm_mon = st.wMonth - 1;
  526. ptm->tm_wday = st.wDayOfWeek;
  527. ptm->tm_mday = st.wDay;
  528. ptm->tm_hour = st.wHour;
  529. ptm->tm_min = st.wMinute;
  530. ptm->tm_sec = st.wSecond;
  531. ptm->tm_yday = 0; /* hope nobody uses this */
  532. ptm->tm_isdst =
  533. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  534. return ptm;
  535. }
  536. static struct tm *
  537. gmtime_s(const time_t *ptime, struct tm *ptm)
  538. {
  539. /* FIXME(lsm): fix this. */
  540. return localtime_s(ptime, ptm);
  541. }
  542. static int mg_atomic_inc(volatile int *addr);
  543. static struct tm tm_array[MAX_WORKER_THREADS];
  544. static int tm_index = 0;
  545. static struct tm *
  546. localtime(const time_t *ptime)
  547. {
  548. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  549. return localtime_s(ptime, tm_array + i);
  550. }
  551. static struct tm *
  552. gmtime(const time_t *ptime)
  553. {
  554. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  555. return gmtime_s(ptime, tm_array + i);
  556. }
  557. static size_t
  558. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  559. {
  560. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  561. // for WinCE");
  562. return 0;
  563. }
  564. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  565. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  566. #define remove(f) mg_remove(NULL, f)
  567. static int
  568. rename(const char *a, const char *b)
  569. {
  570. wchar_t wa[PATH_MAX];
  571. wchar_t wb[PATH_MAX];
  572. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  573. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  574. return MoveFileW(wa, wb) ? 0 : -1;
  575. }
  576. struct stat {
  577. int64_t st_size;
  578. time_t st_mtime;
  579. };
  580. static int
  581. stat(const char *name, struct stat *st)
  582. {
  583. wchar_t wbuf[PATH_MAX];
  584. WIN32_FILE_ATTRIBUTE_DATA attr;
  585. time_t creation_time, write_time;
  586. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  587. memset(&attr, 0, sizeof(attr));
  588. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  589. st->st_size =
  590. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  591. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  592. attr.ftLastWriteTime.dwHighDateTime);
  593. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  594. attr.ftCreationTime.dwHighDateTime);
  595. if (creation_time > write_time) {
  596. st->st_mtime = creation_time;
  597. } else {
  598. st->st_mtime = write_time;
  599. }
  600. return 0;
  601. }
  602. #define access(x, a) 1 /* not required anyway */
  603. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  604. #define EEXIST 1 /* TODO: See Windows error codes */
  605. #define EACCES 2 /* TODO: See Windows error codes */
  606. #define ENOENT 3 /* TODO: See Windows Error codes */
  607. #if defined(__MINGW32__)
  608. /* Enable unused function warning again */
  609. #pragma GCC diagnostic pop
  610. #endif
  611. #endif /* defined(_WIN32_WCE) */
  612. static void DEBUG_TRACE_FUNC(const char *func,
  613. unsigned line,
  614. PRINTF_FORMAT_STRING(const char *fmt),
  615. ...) PRINTF_ARGS(3, 4);
  616. static void
  617. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  618. {
  619. va_list args;
  620. flockfile(stdout);
  621. printf("*** %lu.%p.%s.%u: ",
  622. (unsigned long)time(NULL),
  623. (void *)pthread_self(),
  624. func,
  625. line);
  626. va_start(args, fmt);
  627. vprintf(fmt, args);
  628. va_end(args);
  629. putchar('\n');
  630. fflush(stdout);
  631. funlockfile(stdout);
  632. }
  633. #define DEBUG_TRACE(fmt, ...) \
  634. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  635. #else
  636. #define DEBUG_TRACE(fmt, ...) \
  637. do { \
  638. } while (0)
  639. #endif /* DEBUG */
  640. #endif /* DEBUG_TRACE */
  641. #if defined(MEMORY_DEBUGGING)
  642. unsigned long mg_memory_debug_blockCount = 0;
  643. unsigned long mg_memory_debug_totalMemUsed = 0;
  644. static void *
  645. mg_malloc_ex(size_t size, const char *file, unsigned line)
  646. {
  647. void *data = malloc(size + sizeof(size_t));
  648. void *memory = 0;
  649. char mallocStr[256];
  650. if (data) {
  651. *(size_t *)data = size;
  652. mg_memory_debug_totalMemUsed += size;
  653. mg_memory_debug_blockCount++;
  654. memory = (void *)(((char *)data) + sizeof(size_t));
  655. }
  656. sprintf(mallocStr,
  657. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  658. memory,
  659. (unsigned long)size,
  660. mg_memory_debug_totalMemUsed,
  661. mg_memory_debug_blockCount,
  662. file,
  663. line);
  664. #if defined(_WIN32)
  665. OutputDebugStringA(mallocStr);
  666. #else
  667. DEBUG_TRACE("%s", mallocStr);
  668. #endif
  669. return memory;
  670. }
  671. static void *
  672. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  673. {
  674. void *data = mg_malloc_ex(size * count, file, line);
  675. if (data) {
  676. memset(data, 0, size * count);
  677. }
  678. return data;
  679. }
  680. static void
  681. mg_free_ex(void *memory, const char *file, unsigned line)
  682. {
  683. char mallocStr[256];
  684. void *data = (void *)(((char *)memory) - sizeof(size_t));
  685. size_t size;
  686. if (memory) {
  687. size = *(size_t *)data;
  688. mg_memory_debug_totalMemUsed -= size;
  689. mg_memory_debug_blockCount--;
  690. sprintf(mallocStr,
  691. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  692. memory,
  693. (unsigned long)size,
  694. mg_memory_debug_totalMemUsed,
  695. mg_memory_debug_blockCount,
  696. file,
  697. line);
  698. #if defined(_WIN32)
  699. OutputDebugStringA(mallocStr);
  700. #else
  701. DEBUG_TRACE("%s", mallocStr);
  702. #endif
  703. free(data);
  704. }
  705. }
  706. static void *
  707. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  708. {
  709. char mallocStr[256];
  710. void *data;
  711. void *_realloc;
  712. size_t oldsize;
  713. if (newsize) {
  714. if (memory) {
  715. data = (void *)(((char *)memory) - sizeof(size_t));
  716. oldsize = *(size_t *)data;
  717. _realloc = realloc(data, newsize + sizeof(size_t));
  718. if (_realloc) {
  719. data = _realloc;
  720. mg_memory_debug_totalMemUsed -= oldsize;
  721. sprintf(mallocStr,
  722. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  723. memory,
  724. (unsigned long)oldsize,
  725. mg_memory_debug_totalMemUsed,
  726. mg_memory_debug_blockCount,
  727. file,
  728. line);
  729. #if defined(_WIN32)
  730. OutputDebugStringA(mallocStr);
  731. #else
  732. DEBUG_TRACE("%s", mallocStr);
  733. #endif
  734. mg_memory_debug_totalMemUsed += newsize;
  735. sprintf(mallocStr,
  736. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  737. memory,
  738. (unsigned long)newsize,
  739. mg_memory_debug_totalMemUsed,
  740. mg_memory_debug_blockCount,
  741. file,
  742. line);
  743. #if defined(_WIN32)
  744. OutputDebugStringA(mallocStr);
  745. #else
  746. DEBUG_TRACE("%s", mallocStr);
  747. #endif
  748. *(size_t *)data = newsize;
  749. data = (void *)(((char *)data) + sizeof(size_t));
  750. } else {
  751. #if defined(_WIN32)
  752. OutputDebugStringA("MEM: realloc failed\n");
  753. #else
  754. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  755. #endif
  756. return _realloc;
  757. }
  758. } else {
  759. data = mg_malloc_ex(newsize, file, line);
  760. }
  761. } else {
  762. data = 0;
  763. mg_free_ex(memory, file, line);
  764. }
  765. return data;
  766. }
  767. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  768. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  769. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  770. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  771. #else
  772. static __inline void *
  773. mg_malloc(size_t a)
  774. {
  775. return malloc(a);
  776. }
  777. static __inline void *
  778. mg_calloc(size_t a, size_t b)
  779. {
  780. return calloc(a, b);
  781. }
  782. static __inline void *
  783. mg_realloc(void *a, size_t b)
  784. {
  785. return realloc(a, b);
  786. }
  787. static __inline void
  788. mg_free(void *a)
  789. {
  790. free(a);
  791. }
  792. #endif
  793. static void mg_vsnprintf(const struct mg_connection *conn,
  794. int *truncated,
  795. char *buf,
  796. size_t buflen,
  797. const char *fmt,
  798. va_list ap);
  799. static void mg_snprintf(const struct mg_connection *conn,
  800. int *truncated,
  801. char *buf,
  802. size_t buflen,
  803. PRINTF_FORMAT_STRING(const char *fmt),
  804. ...) PRINTF_ARGS(5, 6);
  805. /* This following lines are just meant as a reminder to use the mg-functions
  806. * for memory management */
  807. #ifdef malloc
  808. #undef malloc
  809. #endif
  810. #ifdef calloc
  811. #undef calloc
  812. #endif
  813. #ifdef realloc
  814. #undef realloc
  815. #endif
  816. #ifdef free
  817. #undef free
  818. #endif
  819. #ifdef snprintf
  820. #undef snprintf
  821. #endif
  822. #ifdef vsnprintf
  823. #undef vsnprintf
  824. #endif
  825. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  826. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  827. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  828. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  829. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  830. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  831. * but this define only works well for Windows. */
  832. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  833. #endif
  834. #define MD5_STATIC static
  835. #include "md5.inl"
  836. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  837. #ifdef NO_SOCKLEN_T
  838. typedef int socklen_t;
  839. #endif /* NO_SOCKLEN_T */
  840. #define _DARWIN_UNLIMITED_SELECT
  841. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  842. #if !defined(MSG_NOSIGNAL)
  843. #define MSG_NOSIGNAL (0)
  844. #endif
  845. #if !defined(SOMAXCONN)
  846. #define SOMAXCONN (100)
  847. #endif
  848. /* Size of the accepted socket queue */
  849. #if !defined(MGSQLEN)
  850. #define MGSQLEN (20)
  851. #endif
  852. #if defined(NO_SSL)
  853. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  854. typedef struct SSL_CTX SSL_CTX;
  855. #else
  856. #if defined(NO_SSL_DL)
  857. #include <openssl/ssl.h>
  858. #include <openssl/err.h>
  859. #include <openssl/crypto.h>
  860. #include <openssl/x509.h>
  861. #include <openssl/pem.h>
  862. #include <openssl/engine.h>
  863. #include <openssl/conf.h>
  864. #include <openssl/dh.h>
  865. #else
  866. /* SSL loaded dynamically from DLL.
  867. * I put the prototypes here to be independent from OpenSSL source
  868. * installation. */
  869. typedef struct ssl_st SSL;
  870. typedef struct ssl_method_st SSL_METHOD;
  871. typedef struct ssl_ctx_st SSL_CTX;
  872. typedef struct x509_store_ctx_st X509_STORE_CTX;
  873. typedef struct x509_name X509_NAME;
  874. typedef struct asn1_integer ASN1_INTEGER;
  875. typedef struct evp_md EVP_MD;
  876. typedef struct x509 X509;
  877. #define SSL_CTRL_OPTIONS (32)
  878. #define SSL_CTRL_CLEAR_OPTIONS (77)
  879. #define SSL_CTRL_SET_ECDH_AUTO (94)
  880. #define SSL_VERIFY_NONE (0)
  881. #define SSL_VERIFY_PEER (1)
  882. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  883. #define SSL_VERIFY_CLIENT_ONCE (4)
  884. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  885. #define SSL_OP_NO_SSLv2 (0x01000000L)
  886. #define SSL_OP_NO_SSLv3 (0x02000000L)
  887. #define SSL_OP_NO_TLSv1 (0x04000000L)
  888. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  889. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  890. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  891. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  892. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  893. #define SSL_ERROR_NONE (0)
  894. #define SSL_ERROR_SSL (1)
  895. #define SSL_ERROR_WANT_READ (2)
  896. #define SSL_ERROR_WANT_WRITE (3)
  897. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  898. #define SSL_ERROR_SYSCALL (5) /* see errno */
  899. #define SSL_ERROR_ZERO_RETURN (6)
  900. #define SSL_ERROR_WANT_CONNECT (7)
  901. #define SSL_ERROR_WANT_ACCEPT (8)
  902. struct ssl_func {
  903. const char *name; /* SSL function name */
  904. void (*ptr)(void); /* Function pointer */
  905. };
  906. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  907. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  908. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  909. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  910. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  911. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  912. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  913. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  914. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  915. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  916. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  917. #define SSL_CTX_use_PrivateKey_file \
  918. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  919. #define SSL_CTX_use_certificate_file \
  920. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  921. #define SSL_CTX_set_default_passwd_cb \
  922. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  923. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  924. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  925. #define SSL_CTX_use_certificate_chain_file \
  926. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  927. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  928. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  929. #define SSL_CTX_set_verify \
  930. (*(void (*)(SSL_CTX *, \
  931. int, \
  932. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  933. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  934. #define SSL_CTX_load_verify_locations \
  935. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  936. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  937. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  938. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  939. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  940. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  941. #define SSL_CIPHER_get_name \
  942. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  943. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  944. #define SSL_CTX_set_session_id_context \
  945. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  946. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  947. #define SSL_CTX_set_cipher_list \
  948. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  949. #define SSL_CTX_set_options(ctx, op) \
  950. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  951. #define SSL_CTX_clear_options(ctx, op) \
  952. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  953. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  954. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  955. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  956. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  957. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  958. #define CRYPTO_set_locking_callback \
  959. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  960. #define CRYPTO_set_id_callback \
  961. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  962. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  963. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  964. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  965. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  966. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  967. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  968. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  969. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  970. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  971. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  972. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  973. #define X509_NAME_oneline \
  974. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  975. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  976. #define i2c_ASN1_INTEGER \
  977. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  978. #define EVP_get_digestbyname \
  979. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  980. #define ASN1_digest \
  981. (*(int (*)(int (*)(), \
  982. const EVP_MD *, \
  983. char *, \
  984. unsigned char *, \
  985. unsigned int *))crypto_sw[18].ptr)
  986. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  987. /* set_ssl_option() function updates this array.
  988. * It loads SSL library dynamically and changes NULLs to the actual addresses
  989. * of respective functions. The macros above (like SSL_connect()) are really
  990. * just calling these functions indirectly via the pointer. */
  991. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  992. {"SSL_accept", NULL},
  993. {"SSL_connect", NULL},
  994. {"SSL_read", NULL},
  995. {"SSL_write", NULL},
  996. {"SSL_get_error", NULL},
  997. {"SSL_set_fd", NULL},
  998. {"SSL_new", NULL},
  999. {"SSL_CTX_new", NULL},
  1000. {"SSLv23_server_method", NULL},
  1001. {"SSL_library_init", NULL},
  1002. {"SSL_CTX_use_PrivateKey_file", NULL},
  1003. {"SSL_CTX_use_certificate_file", NULL},
  1004. {"SSL_CTX_set_default_passwd_cb", NULL},
  1005. {"SSL_CTX_free", NULL},
  1006. {"SSL_load_error_strings", NULL},
  1007. {"SSL_CTX_use_certificate_chain_file", NULL},
  1008. {"SSLv23_client_method", NULL},
  1009. {"SSL_pending", NULL},
  1010. {"SSL_CTX_set_verify", NULL},
  1011. {"SSL_shutdown", NULL},
  1012. {"SSL_CTX_load_verify_locations", NULL},
  1013. {"SSL_CTX_set_default_verify_paths", NULL},
  1014. {"SSL_CTX_set_verify_depth", NULL},
  1015. {"SSL_get_peer_certificate", NULL},
  1016. {"SSL_get_version", NULL},
  1017. {"SSL_get_current_cipher", NULL},
  1018. {"SSL_CIPHER_get_name", NULL},
  1019. {"SSL_CTX_check_private_key", NULL},
  1020. {"SSL_CTX_set_session_id_context", NULL},
  1021. {"SSL_CTX_ctrl", NULL},
  1022. {"SSL_CTX_set_cipher_list", NULL},
  1023. {NULL, NULL}};
  1024. /* Similar array as ssl_sw. These functions could be located in different
  1025. * lib. */
  1026. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1027. {"CRYPTO_set_locking_callback", NULL},
  1028. {"CRYPTO_set_id_callback", NULL},
  1029. {"ERR_get_error", NULL},
  1030. {"ERR_error_string", NULL},
  1031. {"ERR_remove_state", NULL},
  1032. {"ERR_free_strings", NULL},
  1033. {"ENGINE_cleanup", NULL},
  1034. {"CONF_modules_unload", NULL},
  1035. {"CRYPTO_cleanup_all_ex_data", NULL},
  1036. {"EVP_cleanup", NULL},
  1037. {"X509_free", NULL},
  1038. {"X509_get_subject_name", NULL},
  1039. {"X509_get_issuer_name", NULL},
  1040. {"X509_NAME_oneline", NULL},
  1041. {"X509_get_serialNumber", NULL},
  1042. {"i2c_ASN1_INTEGER", NULL},
  1043. {"EVP_get_digestbyname", NULL},
  1044. {"ASN1_digest", NULL},
  1045. {"i2d_X509", NULL},
  1046. {NULL, NULL}};
  1047. #endif /* NO_SSL_DL */
  1048. #endif /* NO_SSL */
  1049. #if !defined(NO_CACHING)
  1050. static const char *month_names[] = {"Jan",
  1051. "Feb",
  1052. "Mar",
  1053. "Apr",
  1054. "May",
  1055. "Jun",
  1056. "Jul",
  1057. "Aug",
  1058. "Sep",
  1059. "Oct",
  1060. "Nov",
  1061. "Dec"};
  1062. #endif /* !NO_CACHING */
  1063. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1064. * union u. */
  1065. union usa {
  1066. struct sockaddr sa;
  1067. struct sockaddr_in sin;
  1068. #if defined(USE_IPV6)
  1069. struct sockaddr_in6 sin6;
  1070. #endif
  1071. };
  1072. /* Describes a string (chunk of memory). */
  1073. struct vec {
  1074. const char *ptr;
  1075. size_t len;
  1076. };
  1077. struct file {
  1078. uint64_t size;
  1079. time_t last_modified;
  1080. FILE *fp;
  1081. const char *membuf; /* Non-NULL if file data is in memory */
  1082. int is_directory;
  1083. int gzipped; /* set to 1 if the content is gzipped
  1084. * in which case we need a content-encoding: gzip header */
  1085. };
  1086. #define STRUCT_FILE_INITIALIZER \
  1087. { \
  1088. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  1089. }
  1090. /* Describes listening socket, or socket which was accept()-ed by the master
  1091. * thread and queued for future handling by the worker thread. */
  1092. struct socket {
  1093. SOCKET sock; /* Listening socket */
  1094. union usa lsa; /* Local socket address */
  1095. union usa rsa; /* Remote socket address */
  1096. unsigned char is_ssl; /* Is port SSL-ed */
  1097. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1098. * port */
  1099. unsigned char in_use; /* Is valid */
  1100. };
  1101. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1102. enum {
  1103. CGI_EXTENSIONS,
  1104. CGI_ENVIRONMENT,
  1105. PUT_DELETE_PASSWORDS_FILE,
  1106. CGI_INTERPRETER,
  1107. PROTECT_URI,
  1108. AUTHENTICATION_DOMAIN,
  1109. SSI_EXTENSIONS,
  1110. THROTTLE,
  1111. ACCESS_LOG_FILE,
  1112. ENABLE_DIRECTORY_LISTING,
  1113. ERROR_LOG_FILE,
  1114. GLOBAL_PASSWORDS_FILE,
  1115. INDEX_FILES,
  1116. ENABLE_KEEP_ALIVE,
  1117. ACCESS_CONTROL_LIST,
  1118. EXTRA_MIME_TYPES,
  1119. LISTENING_PORTS,
  1120. DOCUMENT_ROOT,
  1121. SSL_CERTIFICATE,
  1122. NUM_THREADS,
  1123. RUN_AS_USER,
  1124. REWRITE,
  1125. HIDE_FILES,
  1126. REQUEST_TIMEOUT,
  1127. SSL_DO_VERIFY_PEER,
  1128. SSL_CA_PATH,
  1129. SSL_CA_FILE,
  1130. SSL_VERIFY_DEPTH,
  1131. SSL_DEFAULT_VERIFY_PATHS,
  1132. SSL_CIPHER_LIST,
  1133. SSL_PROTOCOL_VERSION,
  1134. SSL_SHORT_TRUST,
  1135. #if defined(USE_WEBSOCKET)
  1136. WEBSOCKET_TIMEOUT,
  1137. #endif
  1138. DECODE_URL,
  1139. #if defined(USE_LUA)
  1140. LUA_PRELOAD_FILE,
  1141. LUA_SCRIPT_EXTENSIONS,
  1142. LUA_SERVER_PAGE_EXTENSIONS,
  1143. #endif
  1144. #if defined(USE_DUKTAPE)
  1145. DUKTAPE_SCRIPT_EXTENSIONS,
  1146. #endif
  1147. #if defined(USE_WEBSOCKET)
  1148. WEBSOCKET_ROOT,
  1149. #endif
  1150. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1151. LUA_WEBSOCKET_EXTENSIONS,
  1152. #endif
  1153. ACCESS_CONTROL_ALLOW_ORIGIN,
  1154. ERROR_PAGES,
  1155. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1156. * socket option typedef TCP_NODELAY. */
  1157. #if !defined(NO_CACHING)
  1158. STATIC_FILE_MAX_AGE,
  1159. #endif
  1160. #if defined(__linux__)
  1161. ALLOW_SENDFILE_CALL,
  1162. #endif
  1163. NUM_OPTIONS
  1164. };
  1165. /* Config option name, config types, default value */
  1166. static struct mg_option config_options[] = {
  1167. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1168. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1169. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1170. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1171. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1172. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1173. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1174. {"throttle", CONFIG_TYPE_STRING, NULL},
  1175. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1176. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1177. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1178. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1179. {"index_files",
  1180. CONFIG_TYPE_STRING,
  1181. #ifdef USE_LUA
  1182. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1183. "index.shtml,index.php"},
  1184. #else
  1185. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1186. #endif
  1187. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1188. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1189. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1190. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1191. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1192. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1193. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1194. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1195. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1196. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1197. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1198. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1199. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1200. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1201. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1202. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1203. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1204. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1205. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1206. #if defined(USE_WEBSOCKET)
  1207. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1208. #endif
  1209. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1210. #if defined(USE_LUA)
  1211. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1212. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1213. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1214. #endif
  1215. #if defined(USE_DUKTAPE)
  1216. /* The support for duktape is still in alpha version state.
  1217. * The name of this config option might change. */
  1218. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1219. #endif
  1220. #if defined(USE_WEBSOCKET)
  1221. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1222. #endif
  1223. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1224. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1225. #endif
  1226. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1227. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1228. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1229. #if !defined(NO_CACHING)
  1230. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1231. #endif
  1232. #if defined(__linux__)
  1233. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1234. #endif
  1235. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1236. /* Check if the config_options and the corresponding enum have compatible
  1237. * sizes. */
  1238. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1239. == (NUM_OPTIONS + 1),
  1240. "config_options and enum not sync");
  1241. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1242. struct mg_handler_info {
  1243. /* Name/Pattern of the URI. */
  1244. char *uri;
  1245. size_t uri_len;
  1246. /* handler type */
  1247. int handler_type;
  1248. /* Handler for http/https or authorization requests. */
  1249. mg_request_handler handler;
  1250. /* Handler for ws/wss (websocket) requests. */
  1251. mg_websocket_connect_handler connect_handler;
  1252. mg_websocket_ready_handler ready_handler;
  1253. mg_websocket_data_handler data_handler;
  1254. mg_websocket_close_handler close_handler;
  1255. /* Handler for authorization requests */
  1256. mg_authorization_handler auth_handler;
  1257. /* User supplied argument for the handler function. */
  1258. void *cbdata;
  1259. /* next handler in a linked list */
  1260. struct mg_handler_info *next;
  1261. };
  1262. struct mg_context {
  1263. volatile int stop_flag; /* Should we stop event loop */
  1264. SSL_CTX *ssl_ctx; /* SSL context */
  1265. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1266. struct mg_callbacks callbacks; /* User-defined callback function */
  1267. void *user_data; /* User-defined data */
  1268. int context_type; /* 1 = server context, 2 = client context */
  1269. struct socket *listening_sockets;
  1270. struct pollfd *listening_socket_fds;
  1271. unsigned int num_listening_sockets;
  1272. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1273. #ifdef ALTERNATIVE_QUEUE
  1274. struct socket *client_socks;
  1275. void **client_wait_events;
  1276. #else
  1277. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1278. volatile int sq_head; /* Head of the socket queue */
  1279. volatile int sq_tail; /* Tail of the socket queue */
  1280. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1281. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1282. #endif
  1283. pthread_t masterthreadid; /* The master thread ID */
  1284. unsigned int
  1285. cfg_worker_threads; /* The number of configured worker threads. */
  1286. pthread_t *workerthreadids; /* The worker thread IDs */
  1287. time_t start_time; /* Server start time, used for authentication */
  1288. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1289. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1290. unsigned long nonce_count; /* Used nonces, used for authentication */
  1291. char *systemName; /* What operating system is running */
  1292. /* linked list of uri handlers */
  1293. struct mg_handler_info *handlers;
  1294. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1295. /* linked list of shared lua websockets */
  1296. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1297. #endif
  1298. #ifdef USE_TIMERS
  1299. struct ttimers *timers;
  1300. #endif
  1301. };
  1302. struct mg_connection {
  1303. struct mg_request_info request_info;
  1304. struct mg_context *ctx;
  1305. SSL *ssl; /* SSL descriptor */
  1306. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1307. struct socket client; /* Connected client */
  1308. time_t conn_birth_time; /* Time (wall clock) when connection was
  1309. * established */
  1310. struct timespec req_time; /* Time (since system start) when the request
  1311. * was received */
  1312. int64_t num_bytes_sent; /* Total bytes sent to client */
  1313. int64_t content_len; /* Content-Length header value */
  1314. int64_t consumed_content; /* How many bytes of content have been read */
  1315. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1316. * data available, 2: all data read */
  1317. size_t chunk_remainder; /* Unread data from the last chunk */
  1318. char *buf; /* Buffer for received data */
  1319. char *path_info; /* PATH_INFO part of the URL */
  1320. int must_close; /* 1 if connection must be closed */
  1321. int in_error_handler; /* 1 if in handler for user defined error
  1322. * pages */
  1323. int internal_error; /* 1 if an error occured while processing the
  1324. * request */
  1325. int buf_size; /* Buffer size */
  1326. int request_len; /* Size of the request + headers in a buffer */
  1327. int data_len; /* Total size of data in a buffer */
  1328. int status_code; /* HTTP reply status code, e.g. 200 */
  1329. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1330. * throttle */
  1331. time_t last_throttle_time; /* Last time throttled data was sent */
  1332. int64_t last_throttle_bytes; /* Bytes sent this second */
  1333. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1334. * atomic transmissions for websockets */
  1335. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1336. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1337. #endif
  1338. int thread_index; /* Thread index within ctx */
  1339. };
  1340. static pthread_key_t sTlsKey; /* Thread local storage index */
  1341. static int sTlsInit = 0;
  1342. static int thread_idx_max = 0;
  1343. struct mg_workerTLS {
  1344. int is_master;
  1345. unsigned long thread_idx;
  1346. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1347. HANDLE pthread_cond_helper_mutex;
  1348. struct mg_workerTLS *next_waiting_thread;
  1349. #endif
  1350. };
  1351. /* Directory entry */
  1352. struct de {
  1353. struct mg_connection *conn;
  1354. char *file_name;
  1355. struct file file;
  1356. };
  1357. #if defined(USE_WEBSOCKET)
  1358. static int is_websocket_protocol(const struct mg_connection *conn);
  1359. #else
  1360. #define is_websocket_protocol(conn) (0)
  1361. #endif
  1362. static int
  1363. mg_atomic_inc(volatile int *addr)
  1364. {
  1365. int ret;
  1366. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1367. /* Depending on the SDK, this function uses either
  1368. * (volatile unsigned int *) or (volatile LONG *),
  1369. * so whatever you use, the other SDK is likely to raise a warning. */
  1370. ret = InterlockedIncrement((volatile long *)addr);
  1371. #elif defined(__GNUC__) \
  1372. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1373. ret = __sync_add_and_fetch(addr, 1);
  1374. #else
  1375. ret = (++(*addr));
  1376. #endif
  1377. return ret;
  1378. }
  1379. static int
  1380. mg_atomic_dec(volatile int *addr)
  1381. {
  1382. int ret;
  1383. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1384. /* Depending on the SDK, this function uses either
  1385. * (volatile unsigned int *) or (volatile LONG *),
  1386. * so whatever you use, the other SDK is likely to raise a warning. */
  1387. ret = InterlockedDecrement((volatile long *)addr);
  1388. #elif defined(__GNUC__) \
  1389. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1390. ret = __sync_sub_and_fetch(addr, 1);
  1391. #else
  1392. ret = (--(*addr));
  1393. #endif
  1394. return ret;
  1395. }
  1396. #if !defined(NO_THREAD_NAME)
  1397. #if defined(_WIN32) && defined(_MSC_VER)
  1398. /* Set the thread name for debugging purposes in Visual Studio
  1399. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1400. */
  1401. #pragma pack(push, 8)
  1402. typedef struct tagTHREADNAME_INFO {
  1403. DWORD dwType; /* Must be 0x1000. */
  1404. LPCSTR szName; /* Pointer to name (in user addr space). */
  1405. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1406. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1407. } THREADNAME_INFO;
  1408. #pragma pack(pop)
  1409. #elif defined(__linux__)
  1410. #include <sys/prctl.h>
  1411. #include <sys/sendfile.h>
  1412. #include <sys/eventfd.h>
  1413. #if defined(ALTERNATIVE_QUEUE)
  1414. static void *
  1415. event_create(void)
  1416. {
  1417. int ret = eventfd(0, EFD_CLOEXEC);
  1418. if (ret == -1) {
  1419. /* Linux uses -1 on error, Windows NULL. */
  1420. /* However, Linux does not return 0 on success either. */
  1421. return 0;
  1422. }
  1423. return (void *)ret;
  1424. }
  1425. static int
  1426. event_wait(void *eventhdl)
  1427. {
  1428. uint64_t u;
  1429. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1430. if (s != sizeof(uint64_t)) {
  1431. /* error */
  1432. return 0;
  1433. }
  1434. (void)u; /* the value is not required */
  1435. return 1;
  1436. }
  1437. static int
  1438. event_signal(void *eventhdl)
  1439. {
  1440. uint64_t u = 1;
  1441. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1442. if (s != sizeof(uint64_t)) {
  1443. /* error */
  1444. return 0;
  1445. }
  1446. return 1;
  1447. }
  1448. static void
  1449. event_destroy(void *eventhdl)
  1450. {
  1451. close((int)eventhdl);
  1452. }
  1453. #endif
  1454. #endif
  1455. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1456. struct posix_event {
  1457. pthread_mutex_t mutex;
  1458. pthread_cond_t cond;
  1459. };
  1460. static void *
  1461. event_create(void)
  1462. {
  1463. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1464. if (ret == 0) {
  1465. /* out of memory */
  1466. return 0;
  1467. }
  1468. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1469. /* pthread mutex not available */
  1470. mg_free(ret);
  1471. return 0;
  1472. }
  1473. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1474. /* pthread cond not available */
  1475. pthread_mutex_destroy(&(ret->mutex));
  1476. mg_free(ret);
  1477. return 0;
  1478. }
  1479. return (void *)ret;
  1480. }
  1481. static int
  1482. event_wait(void *eventhdl)
  1483. {
  1484. struct posix_event *ev = (struct posix_event *)eventhdl;
  1485. pthread_mutex_lock(&(ev->mutex));
  1486. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1487. pthread_mutex_unlock(&(ev->mutex));
  1488. return 1;
  1489. }
  1490. static int
  1491. event_signal(void *eventhdl)
  1492. {
  1493. struct posix_event *ev = (struct posix_event *)eventhdl;
  1494. pthread_mutex_lock(&(ev->mutex));
  1495. pthread_cond_signal(&(ev->cond));
  1496. pthread_mutex_unlock(&(ev->mutex));
  1497. return 1;
  1498. }
  1499. static void
  1500. event_destroy(void *eventhdl)
  1501. {
  1502. struct posix_event *ev = (struct posix_event *)eventhdl;
  1503. pthread_cond_destroy(&(ev->cond));
  1504. pthread_mutex_destroy(&(ev->mutex));
  1505. mg_free(ev);
  1506. }
  1507. #endif
  1508. static void
  1509. mg_set_thread_name(const char *name)
  1510. {
  1511. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1512. mg_snprintf(
  1513. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1514. #if defined(_WIN32)
  1515. #if defined(_MSC_VER)
  1516. /* Windows and Visual Studio Compiler */
  1517. __try
  1518. {
  1519. THREADNAME_INFO info;
  1520. info.dwType = 0x1000;
  1521. info.szName = threadName;
  1522. info.dwThreadID = ~0U;
  1523. info.dwFlags = 0;
  1524. RaiseException(0x406D1388,
  1525. 0,
  1526. sizeof(info) / sizeof(ULONG_PTR),
  1527. (ULONG_PTR *)&info);
  1528. }
  1529. __except(EXCEPTION_EXECUTE_HANDLER)
  1530. {
  1531. }
  1532. #elif defined(__MINGW32__)
  1533. /* No option known to set thread name for MinGW */
  1534. #endif
  1535. #elif defined(__GLIBC__) \
  1536. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1537. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1538. (void)pthread_setname_np(pthread_self(), threadName);
  1539. #elif defined(__linux__)
  1540. /* on linux we can use the old prctl function */
  1541. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1542. #endif
  1543. }
  1544. #else /* !defined(NO_THREAD_NAME) */
  1545. void
  1546. mg_set_thread_name(const char *threadName)
  1547. {
  1548. }
  1549. #endif
  1550. #if defined(MG_LEGACY_INTERFACE)
  1551. const char **
  1552. mg_get_valid_option_names(void)
  1553. {
  1554. /* This function is deprecated. Use mg_get_valid_options instead. */
  1555. static const char *
  1556. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1557. int i;
  1558. for (i = 0; config_options[i].name != NULL; i++) {
  1559. data[i * 2] = config_options[i].name;
  1560. data[i * 2 + 1] = config_options[i].default_value;
  1561. }
  1562. return data;
  1563. }
  1564. #endif
  1565. const struct mg_option *
  1566. mg_get_valid_options(void)
  1567. {
  1568. return config_options;
  1569. }
  1570. static int
  1571. is_file_in_memory(const struct mg_connection *conn,
  1572. const char *path,
  1573. struct file *filep)
  1574. {
  1575. size_t size = 0;
  1576. if (!conn || !filep) {
  1577. return 0;
  1578. }
  1579. if (conn->ctx->callbacks.open_file) {
  1580. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1581. if (filep->membuf != NULL) {
  1582. /* NOTE: override filep->size only on success. Otherwise, it might
  1583. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1584. filep->size = size;
  1585. }
  1586. }
  1587. return filep->membuf != NULL;
  1588. }
  1589. static int
  1590. is_file_opened(const struct file *filep)
  1591. {
  1592. if (!filep) {
  1593. return 0;
  1594. }
  1595. return filep->membuf != NULL || filep->fp != NULL;
  1596. }
  1597. /* mg_fopen will open a file either in memory or on the disk.
  1598. * The input parameter path is a string in UTF-8 encoding.
  1599. * The input parameter mode is the same as for fopen.
  1600. * Either fp or membuf will be set in the output struct filep.
  1601. * The function returns 1 on success, 0 on error. */
  1602. static int
  1603. mg_fopen(const struct mg_connection *conn,
  1604. const char *path,
  1605. const char *mode,
  1606. struct file *filep)
  1607. {
  1608. struct stat st;
  1609. if (!filep) {
  1610. return 0;
  1611. }
  1612. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1613. * only get the file status. They should not work on different members of
  1614. * the same structure (bad cohesion). */
  1615. memset(filep, 0, sizeof(*filep));
  1616. if (stat(path, &st) == 0) {
  1617. filep->size = (uint64_t)(st.st_size);
  1618. }
  1619. if (!is_file_in_memory(conn, path, filep)) {
  1620. #ifdef _WIN32
  1621. wchar_t wbuf[PATH_MAX], wmode[20];
  1622. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1623. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1624. filep->fp = _wfopen(wbuf, wmode);
  1625. #else
  1626. /* Linux et al already use unicode. No need to convert. */
  1627. filep->fp = fopen(path, mode);
  1628. #endif
  1629. }
  1630. return is_file_opened(filep);
  1631. }
  1632. static void
  1633. mg_fclose(struct file *filep)
  1634. {
  1635. if (filep != NULL && filep->fp != NULL) {
  1636. fclose(filep->fp);
  1637. }
  1638. }
  1639. static void
  1640. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1641. {
  1642. for (; *src != '\0' && n > 1; n--) {
  1643. *dst++ = *src++;
  1644. }
  1645. *dst = '\0';
  1646. }
  1647. static int
  1648. lowercase(const char *s)
  1649. {
  1650. return tolower(*(const unsigned char *)s);
  1651. }
  1652. int
  1653. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1654. {
  1655. int diff = 0;
  1656. if (len > 0) {
  1657. do {
  1658. diff = lowercase(s1++) - lowercase(s2++);
  1659. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1660. }
  1661. return diff;
  1662. }
  1663. int
  1664. mg_strcasecmp(const char *s1, const char *s2)
  1665. {
  1666. int diff;
  1667. do {
  1668. diff = lowercase(s1++) - lowercase(s2++);
  1669. } while (diff == 0 && s1[-1] != '\0');
  1670. return diff;
  1671. }
  1672. static char *
  1673. mg_strndup(const char *ptr, size_t len)
  1674. {
  1675. char *p;
  1676. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1677. mg_strlcpy(p, ptr, len + 1);
  1678. }
  1679. return p;
  1680. }
  1681. static char *
  1682. mg_strdup(const char *str)
  1683. {
  1684. return mg_strndup(str, strlen(str));
  1685. }
  1686. static const char *
  1687. mg_strcasestr(const char *big_str, const char *small_str)
  1688. {
  1689. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1690. if (big_len >= small_len) {
  1691. for (i = 0; i <= (big_len - small_len); i++) {
  1692. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1693. return big_str + i;
  1694. }
  1695. }
  1696. }
  1697. return NULL;
  1698. }
  1699. /* Return null terminated string of given maximum length.
  1700. * Report errors if length is exceeded. */
  1701. static void
  1702. mg_vsnprintf(const struct mg_connection *conn,
  1703. int *truncated,
  1704. char *buf,
  1705. size_t buflen,
  1706. const char *fmt,
  1707. va_list ap)
  1708. {
  1709. int n, ok;
  1710. if (buflen == 0) {
  1711. return;
  1712. }
  1713. #ifdef __clang__
  1714. #pragma clang diagnostic push
  1715. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1716. /* Using fmt as a non-literal is intended here, since it is mostly called
  1717. * indirectly by mg_snprintf */
  1718. #endif
  1719. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1720. ok = (n >= 0) && ((size_t)n < buflen);
  1721. #ifdef __clang__
  1722. #pragma clang diagnostic pop
  1723. #endif
  1724. if (ok) {
  1725. if (truncated) {
  1726. *truncated = 0;
  1727. }
  1728. } else {
  1729. if (truncated) {
  1730. *truncated = 1;
  1731. }
  1732. mg_cry(conn,
  1733. "truncating vsnprintf buffer: [%.*s]",
  1734. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1735. buf);
  1736. n = (int)buflen - 1;
  1737. }
  1738. buf[n] = '\0';
  1739. }
  1740. static void
  1741. mg_snprintf(const struct mg_connection *conn,
  1742. int *truncated,
  1743. char *buf,
  1744. size_t buflen,
  1745. const char *fmt,
  1746. ...)
  1747. {
  1748. va_list ap;
  1749. va_start(ap, fmt);
  1750. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1751. va_end(ap);
  1752. }
  1753. static int
  1754. get_option_index(const char *name)
  1755. {
  1756. int i;
  1757. for (i = 0; config_options[i].name != NULL; i++) {
  1758. if (strcmp(config_options[i].name, name) == 0) {
  1759. return i;
  1760. }
  1761. }
  1762. return -1;
  1763. }
  1764. const char *
  1765. mg_get_option(const struct mg_context *ctx, const char *name)
  1766. {
  1767. int i;
  1768. if ((i = get_option_index(name)) == -1) {
  1769. return NULL;
  1770. } else if (!ctx || ctx->config[i] == NULL) {
  1771. return "";
  1772. } else {
  1773. return ctx->config[i];
  1774. }
  1775. }
  1776. struct mg_context *
  1777. mg_get_context(const struct mg_connection *conn)
  1778. {
  1779. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1780. }
  1781. void *
  1782. mg_get_user_data(const struct mg_context *ctx)
  1783. {
  1784. return (ctx == NULL) ? NULL : ctx->user_data;
  1785. }
  1786. void
  1787. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1788. {
  1789. if (conn != NULL) {
  1790. conn->request_info.conn_data = data;
  1791. }
  1792. }
  1793. void *
  1794. mg_get_user_connection_data(const struct mg_connection *conn)
  1795. {
  1796. if (conn != NULL) {
  1797. return conn->request_info.conn_data;
  1798. }
  1799. return NULL;
  1800. }
  1801. size_t
  1802. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1803. {
  1804. size_t i;
  1805. if (!ctx) {
  1806. return 0;
  1807. }
  1808. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1809. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1810. ports[i] =
  1811. #if defined(USE_IPV6)
  1812. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1813. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1814. :
  1815. #endif
  1816. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1817. }
  1818. return i;
  1819. }
  1820. int
  1821. mg_get_server_ports(const struct mg_context *ctx,
  1822. int size,
  1823. struct mg_server_ports *ports)
  1824. {
  1825. int i, cnt = 0;
  1826. if (size <= 0) {
  1827. return -1;
  1828. }
  1829. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1830. if (!ctx) {
  1831. return -1;
  1832. }
  1833. if (!ctx->listening_sockets) {
  1834. return -1;
  1835. }
  1836. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1837. ports[cnt].port =
  1838. #if defined(USE_IPV6)
  1839. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  1840. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  1841. :
  1842. #endif
  1843. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  1844. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1845. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1846. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1847. /* IPv4 */
  1848. ports[cnt].protocol = 1;
  1849. cnt++;
  1850. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1851. /* IPv6 */
  1852. ports[cnt].protocol = 3;
  1853. cnt++;
  1854. }
  1855. }
  1856. return cnt;
  1857. }
  1858. static void
  1859. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1860. {
  1861. buf[0] = '\0';
  1862. if (!usa) {
  1863. return;
  1864. }
  1865. if (usa->sa.sa_family == AF_INET) {
  1866. getnameinfo(&usa->sa,
  1867. sizeof(usa->sin),
  1868. buf,
  1869. (unsigned)len,
  1870. NULL,
  1871. 0,
  1872. NI_NUMERICHOST);
  1873. }
  1874. #if defined(USE_IPV6)
  1875. else if (usa->sa.sa_family == AF_INET6) {
  1876. getnameinfo(&usa->sa,
  1877. sizeof(usa->sin6),
  1878. buf,
  1879. (unsigned)len,
  1880. NULL,
  1881. 0,
  1882. NI_NUMERICHOST);
  1883. }
  1884. #endif
  1885. }
  1886. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1887. * included in all responses other than 100, 101, 5xx. */
  1888. static void
  1889. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1890. {
  1891. struct tm *tm;
  1892. tm = ((t != NULL) ? gmtime(t) : NULL);
  1893. if (tm != NULL) {
  1894. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1895. } else {
  1896. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1897. buf[buf_len - 1] = '\0';
  1898. }
  1899. }
  1900. /* difftime for struct timespec. Return value is in seconds. */
  1901. static double
  1902. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1903. {
  1904. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1905. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1906. }
  1907. /* Print error message to the opened error log stream. */
  1908. void
  1909. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1910. {
  1911. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1912. va_list ap;
  1913. struct file fi;
  1914. time_t timestamp;
  1915. va_start(ap, fmt);
  1916. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1917. va_end(ap);
  1918. buf[sizeof(buf) - 1] = 0;
  1919. if (!conn) {
  1920. puts(buf);
  1921. return;
  1922. }
  1923. /* Do not lock when getting the callback value, here and below.
  1924. * I suppose this is fine, since function cannot disappear in the
  1925. * same way string option can. */
  1926. if ((conn->ctx->callbacks.log_message == NULL)
  1927. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1928. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1929. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1930. == 0) {
  1931. fi.fp = NULL;
  1932. }
  1933. } else {
  1934. fi.fp = NULL;
  1935. }
  1936. if (fi.fp != NULL) {
  1937. flockfile(fi.fp);
  1938. timestamp = time(NULL);
  1939. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1940. fprintf(fi.fp,
  1941. "[%010lu] [error] [client %s] ",
  1942. (unsigned long)timestamp,
  1943. src_addr);
  1944. if (conn->request_info.request_method != NULL) {
  1945. fprintf(fi.fp,
  1946. "%s %s: ",
  1947. conn->request_info.request_method,
  1948. conn->request_info.request_uri);
  1949. }
  1950. fprintf(fi.fp, "%s", buf);
  1951. fputc('\n', fi.fp);
  1952. fflush(fi.fp);
  1953. funlockfile(fi.fp);
  1954. mg_fclose(&fi);
  1955. }
  1956. }
  1957. }
  1958. /* Return fake connection structure. Used for logging, if connection
  1959. * is not applicable at the moment of logging. */
  1960. static struct mg_connection *
  1961. fc(struct mg_context *ctx)
  1962. {
  1963. static struct mg_connection fake_connection;
  1964. fake_connection.ctx = ctx;
  1965. return &fake_connection;
  1966. }
  1967. const char *
  1968. mg_version(void)
  1969. {
  1970. return CIVETWEB_VERSION;
  1971. }
  1972. const struct mg_request_info *
  1973. mg_get_request_info(const struct mg_connection *conn)
  1974. {
  1975. if (!conn) {
  1976. return NULL;
  1977. }
  1978. return &conn->request_info;
  1979. }
  1980. /* Skip the characters until one of the delimiters characters found.
  1981. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1982. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1983. * Delimiters can be quoted with quotechar. */
  1984. static char *
  1985. skip_quoted(char **buf,
  1986. const char *delimiters,
  1987. const char *whitespace,
  1988. char quotechar)
  1989. {
  1990. char *p, *begin_word, *end_word, *end_whitespace;
  1991. begin_word = *buf;
  1992. end_word = begin_word + strcspn(begin_word, delimiters);
  1993. /* Check for quotechar */
  1994. if (end_word > begin_word) {
  1995. p = end_word - 1;
  1996. while (*p == quotechar) {
  1997. /* While the delimiter is quoted, look for the next delimiter. */
  1998. /* This happens, e.g., in calls from parse_auth_header,
  1999. * if the user name contains a " character. */
  2000. /* If there is anything beyond end_word, copy it. */
  2001. if (*end_word != '\0') {
  2002. size_t end_off = strcspn(end_word + 1, delimiters);
  2003. memmove(p, end_word, end_off + 1);
  2004. p += end_off; /* p must correspond to end_word - 1 */
  2005. end_word += end_off + 1;
  2006. } else {
  2007. *p = '\0';
  2008. break;
  2009. }
  2010. }
  2011. for (p++; p < end_word; p++) {
  2012. *p = '\0';
  2013. }
  2014. }
  2015. if (*end_word == '\0') {
  2016. *buf = end_word;
  2017. } else {
  2018. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  2019. for (p = end_word; p < end_whitespace; p++) {
  2020. *p = '\0';
  2021. }
  2022. *buf = end_whitespace;
  2023. }
  2024. return begin_word;
  2025. }
  2026. /* Simplified version of skip_quoted without quote char
  2027. * and whitespace == delimiters */
  2028. static char *
  2029. skip(char **buf, const char *delimiters)
  2030. {
  2031. return skip_quoted(buf, delimiters, delimiters, 0);
  2032. }
  2033. /* Return HTTP header value, or NULL if not found. */
  2034. static const char *
  2035. get_header(const struct mg_request_info *ri, const char *name)
  2036. {
  2037. int i;
  2038. if (ri) {
  2039. for (i = 0; i < ri->num_headers; i++) {
  2040. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2041. return ri->http_headers[i].value;
  2042. }
  2043. }
  2044. }
  2045. return NULL;
  2046. }
  2047. const char *
  2048. mg_get_header(const struct mg_connection *conn, const char *name)
  2049. {
  2050. if (!conn) {
  2051. return NULL;
  2052. }
  2053. return get_header(&conn->request_info, name);
  2054. }
  2055. /* A helper function for traversing a comma separated list of values.
  2056. * It returns a list pointer shifted to the next value, or NULL if the end
  2057. * of the list found.
  2058. * Value is stored in val vector. If value has form "x=y", then eq_val
  2059. * vector is initialized to point to the "y" part, and val vector length
  2060. * is adjusted to point only to "x". */
  2061. static const char *
  2062. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2063. {
  2064. int end;
  2065. reparse:
  2066. if (val == NULL || list == NULL || *list == '\0') {
  2067. /* End of the list */
  2068. list = NULL;
  2069. } else {
  2070. /* Skip over leading LWS */
  2071. while (*list == ' ' || *list == '\t')
  2072. list++;
  2073. val->ptr = list;
  2074. if ((list = strchr(val->ptr, ',')) != NULL) {
  2075. /* Comma found. Store length and shift the list ptr */
  2076. val->len = ((size_t)(list - val->ptr));
  2077. list++;
  2078. } else {
  2079. /* This value is the last one */
  2080. list = val->ptr + strlen(val->ptr);
  2081. val->len = ((size_t)(list - val->ptr));
  2082. }
  2083. /* Adjust length for trailing LWS */
  2084. end = (int)val->len - 1;
  2085. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2086. end--;
  2087. val->len = (size_t)(end + 1);
  2088. if (val->len == 0) {
  2089. /* Ignore any empty entries. */
  2090. goto reparse;
  2091. }
  2092. if (eq_val != NULL) {
  2093. /* Value has form "x=y", adjust pointers and lengths
  2094. * so that val points to "x", and eq_val points to "y". */
  2095. eq_val->len = 0;
  2096. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2097. if (eq_val->ptr != NULL) {
  2098. eq_val->ptr++; /* Skip over '=' character */
  2099. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2100. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2101. }
  2102. }
  2103. }
  2104. return list;
  2105. }
  2106. /* A helper function for checking if a comma separated list of values contains
  2107. * the given option (case insensitvely).
  2108. * 'header' can be NULL, in which case false is returned. */
  2109. static int
  2110. header_has_option(const char *header, const char *option)
  2111. {
  2112. struct vec opt_vec;
  2113. struct vec eq_vec;
  2114. assert(option != NULL);
  2115. assert(option[0] != '\0');
  2116. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2117. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2118. return 1;
  2119. }
  2120. return 0;
  2121. }
  2122. /* Perform case-insensitive match of string against pattern */
  2123. static int
  2124. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2125. {
  2126. const char *or_str;
  2127. size_t i;
  2128. int j, len, res;
  2129. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2130. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2131. return (res > 0) ? res : match_prefix(or_str + 1,
  2132. (size_t)((pattern + pattern_len)
  2133. - (or_str + 1)),
  2134. str);
  2135. }
  2136. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2137. if (pattern[i] == '?' && str[j] != '\0') {
  2138. continue;
  2139. } else if (pattern[i] == '$') {
  2140. return (str[j] == '\0') ? j : -1;
  2141. } else if (pattern[i] == '*') {
  2142. i++;
  2143. if (pattern[i] == '*') {
  2144. i++;
  2145. len = (int)strlen(str + j);
  2146. } else {
  2147. len = (int)strcspn(str + j, "/");
  2148. }
  2149. if (i == pattern_len) {
  2150. return j + len;
  2151. }
  2152. do {
  2153. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2154. } while (res == -1 && len-- > 0);
  2155. return (res == -1) ? -1 : j + res + len;
  2156. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2157. return -1;
  2158. }
  2159. }
  2160. return j;
  2161. }
  2162. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2163. * This function must tolerate situations when connection info is not
  2164. * set up, for example if request parsing failed. */
  2165. static int
  2166. should_keep_alive(const struct mg_connection *conn)
  2167. {
  2168. if (conn != NULL) {
  2169. const char *http_version = conn->request_info.http_version;
  2170. const char *header = mg_get_header(conn, "Connection");
  2171. if (conn->must_close || conn->internal_error || conn->status_code == 401
  2172. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2173. || (header != NULL && !header_has_option(header, "keep-alive"))
  2174. || (header == NULL && http_version
  2175. && 0 != strcmp(http_version, "1.1"))) {
  2176. return 0;
  2177. }
  2178. return 1;
  2179. }
  2180. return 0;
  2181. }
  2182. static int
  2183. should_decode_url(const struct mg_connection *conn)
  2184. {
  2185. if (!conn || !conn->ctx) {
  2186. return 0;
  2187. }
  2188. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2189. }
  2190. static const char *
  2191. suggest_connection_header(const struct mg_connection *conn)
  2192. {
  2193. return should_keep_alive(conn) ? "keep-alive" : "close";
  2194. }
  2195. static int
  2196. send_no_cache_header(struct mg_connection *conn)
  2197. {
  2198. /* Send all current and obsolete cache opt-out directives. */
  2199. return mg_printf(conn,
  2200. "Cache-Control: no-cache, no-store, "
  2201. "must-revalidate, private, max-age=0\r\n"
  2202. "Pragma: no-cache\r\n"
  2203. "Expires: 0\r\n");
  2204. }
  2205. static int
  2206. send_static_cache_header(struct mg_connection *conn)
  2207. {
  2208. #if !defined(NO_CACHING)
  2209. /* Read the server config to check how long a file may be cached.
  2210. * The configuration is in seconds. */
  2211. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2212. if (max_age <= 0) {
  2213. /* 0 means "do not cache". All values <0 are reserved
  2214. * and may be used differently in the future. */
  2215. /* If a file should not be cached, do not only send
  2216. * max-age=0, but also pragmas and Expires headers. */
  2217. return send_no_cache_header(conn);
  2218. }
  2219. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2220. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2221. /* See also https://www.mnot.net/cache_docs/ */
  2222. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2223. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2224. * year to 31622400 seconds. For the moment, we just send whatever has
  2225. * been configured, still the behavior for >1 year should be considered
  2226. * as undefined. */
  2227. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2228. #else /* NO_CACHING */
  2229. return send_no_cache_header(conn);
  2230. #endif /* !NO_CACHING */
  2231. }
  2232. static void handle_file_based_request(struct mg_connection *conn,
  2233. const char *path,
  2234. struct file *filep);
  2235. static int
  2236. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  2237. const char *
  2238. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2239. {
  2240. /* See IANA HTTP status code assignment:
  2241. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2242. */
  2243. switch (response_code) {
  2244. /* RFC2616 Section 10.1 - Informational 1xx */
  2245. case 100:
  2246. return "Continue"; /* RFC2616 Section 10.1.1 */
  2247. case 101:
  2248. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2249. case 102:
  2250. return "Processing"; /* RFC2518 Section 10.1 */
  2251. /* RFC2616 Section 10.2 - Successful 2xx */
  2252. case 200:
  2253. return "OK"; /* RFC2616 Section 10.2.1 */
  2254. case 201:
  2255. return "Created"; /* RFC2616 Section 10.2.2 */
  2256. case 202:
  2257. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2258. case 203:
  2259. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2260. case 204:
  2261. return "No Content"; /* RFC2616 Section 10.2.5 */
  2262. case 205:
  2263. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2264. case 206:
  2265. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2266. case 207:
  2267. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2268. case 208:
  2269. return "Already Reported"; /* RFC5842 Section 7.1 */
  2270. case 226:
  2271. return "IM used"; /* RFC3229 Section 10.4.1 */
  2272. /* RFC2616 Section 10.3 - Redirection 3xx */
  2273. case 300:
  2274. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2275. case 301:
  2276. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2277. case 302:
  2278. return "Found"; /* RFC2616 Section 10.3.3 */
  2279. case 303:
  2280. return "See Other"; /* RFC2616 Section 10.3.4 */
  2281. case 304:
  2282. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2283. case 305:
  2284. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2285. case 307:
  2286. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2287. case 308:
  2288. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2289. /* RFC2616 Section 10.4 - Client Error 4xx */
  2290. case 400:
  2291. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2292. case 401:
  2293. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2294. case 402:
  2295. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2296. case 403:
  2297. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2298. case 404:
  2299. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2300. case 405:
  2301. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2302. case 406:
  2303. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2304. case 407:
  2305. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2306. case 408:
  2307. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2308. case 409:
  2309. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2310. case 410:
  2311. return "Gone"; /* RFC2616 Section 10.4.11 */
  2312. case 411:
  2313. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2314. case 412:
  2315. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2316. case 413:
  2317. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2318. case 414:
  2319. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2320. case 415:
  2321. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2322. case 416:
  2323. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2324. case 417:
  2325. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2326. case 421:
  2327. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2328. case 422:
  2329. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2330. * Section 11.2 */
  2331. case 423:
  2332. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2333. case 424:
  2334. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2335. * Section 11.4 */
  2336. case 426:
  2337. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2338. case 428:
  2339. return "Precondition Required"; /* RFC 6585, Section 3 */
  2340. case 429:
  2341. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2342. case 431:
  2343. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2344. case 451:
  2345. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2346. * Section 3 */
  2347. /* RFC2616 Section 10.5 - Server Error 5xx */
  2348. case 500:
  2349. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2350. case 501:
  2351. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2352. case 502:
  2353. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2354. case 503:
  2355. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2356. case 504:
  2357. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2358. case 505:
  2359. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2360. case 506:
  2361. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2362. case 507:
  2363. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2364. * Section 11.5 */
  2365. case 508:
  2366. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2367. case 510:
  2368. return "Not Extended"; /* RFC 2774, Section 7 */
  2369. case 511:
  2370. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2371. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2372. * E.g., "de facto" standards due to common use, ... */
  2373. case 418:
  2374. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2375. case 419:
  2376. return "Authentication Timeout"; /* common use */
  2377. case 420:
  2378. return "Enhance Your Calm"; /* common use */
  2379. case 440:
  2380. return "Login Timeout"; /* common use */
  2381. case 509:
  2382. return "Bandwidth Limit Exceeded"; /* common use */
  2383. default:
  2384. /* This error code is unknown. This should not happen. */
  2385. if (conn) {
  2386. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2387. }
  2388. /* Return at least a category according to RFC 2616 Section 10. */
  2389. if (response_code >= 100 && response_code < 200) {
  2390. /* Unknown informational status code */
  2391. return "Information";
  2392. }
  2393. if (response_code >= 200 && response_code < 300) {
  2394. /* Unknown success code */
  2395. return "Success";
  2396. }
  2397. if (response_code >= 300 && response_code < 400) {
  2398. /* Unknown redirection code */
  2399. return "Redirection";
  2400. }
  2401. if (response_code >= 400 && response_code < 500) {
  2402. /* Unknown request error code */
  2403. return "Client Error";
  2404. }
  2405. if (response_code >= 500 && response_code < 600) {
  2406. /* Unknown server error code */
  2407. return "Server Error";
  2408. }
  2409. /* Response code not even within reasonable range */
  2410. return "";
  2411. }
  2412. }
  2413. static void send_http_error(struct mg_connection *,
  2414. int,
  2415. PRINTF_FORMAT_STRING(const char *fmt),
  2416. ...) PRINTF_ARGS(3, 4);
  2417. static void
  2418. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2419. {
  2420. char buf[MG_BUF_LEN];
  2421. va_list ap;
  2422. int len, i, page_handler_found, scope, truncated, has_body;
  2423. char date[64];
  2424. time_t curtime = time(NULL);
  2425. const char *error_handler = NULL;
  2426. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2427. const char *error_page_file_ext, *tstr;
  2428. const char *status_text = mg_get_response_code_text(conn, status);
  2429. if (conn == NULL) {
  2430. return;
  2431. }
  2432. conn->status_code = status;
  2433. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2434. || conn->ctx->callbacks.http_error(conn, status)) {
  2435. if (!conn->in_error_handler) {
  2436. /* Send user defined error pages, if defined */
  2437. error_handler = conn->ctx->config[ERROR_PAGES];
  2438. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2439. page_handler_found = 0;
  2440. if (error_handler != NULL) {
  2441. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2442. switch (scope) {
  2443. case 1: /* Handler for specific error, e.g. 404 error */
  2444. mg_snprintf(conn,
  2445. &truncated,
  2446. buf,
  2447. sizeof(buf) - 32,
  2448. "%serror%03u.",
  2449. error_handler,
  2450. status);
  2451. break;
  2452. case 2: /* Handler for error group, e.g., 5xx error handler
  2453. * for all server errors (500-599) */
  2454. mg_snprintf(conn,
  2455. &truncated,
  2456. buf,
  2457. sizeof(buf) - 32,
  2458. "%serror%01uxx.",
  2459. error_handler,
  2460. status / 100);
  2461. break;
  2462. default: /* Handler for all errors */
  2463. mg_snprintf(conn,
  2464. &truncated,
  2465. buf,
  2466. sizeof(buf) - 32,
  2467. "%serror.",
  2468. error_handler);
  2469. break;
  2470. }
  2471. /* String truncation in buf may only occur if error_handler
  2472. * is too long. This string is from the config, not from a
  2473. * client. */
  2474. (void)truncated;
  2475. len = (int)strlen(buf);
  2476. tstr = strchr(error_page_file_ext, '.');
  2477. while (tstr) {
  2478. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2479. i++)
  2480. buf[len + i - 1] = tstr[i];
  2481. buf[len + i - 1] = 0;
  2482. if (mg_stat(conn, buf, &error_page_file)) {
  2483. page_handler_found = 1;
  2484. break;
  2485. }
  2486. tstr = strchr(tstr + i, '.');
  2487. }
  2488. }
  2489. }
  2490. if (page_handler_found) {
  2491. conn->in_error_handler = 1;
  2492. handle_file_based_request(conn, buf, &error_page_file);
  2493. conn->in_error_handler = 0;
  2494. return;
  2495. }
  2496. }
  2497. /* No custom error page. Send default error page. */
  2498. gmt_time_string(date, sizeof(date), &curtime);
  2499. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2500. has_body = (status > 199 && status != 204 && status != 304);
  2501. conn->must_close = 1;
  2502. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2503. send_no_cache_header(conn);
  2504. if (has_body) {
  2505. mg_printf(conn,
  2506. "%s",
  2507. "Content-Type: text/plain; charset=utf-8\r\n");
  2508. }
  2509. mg_printf(conn,
  2510. "Date: %s\r\n"
  2511. "Connection: close\r\n\r\n",
  2512. date);
  2513. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2514. if (has_body) {
  2515. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2516. if (fmt != NULL) {
  2517. va_start(ap, fmt);
  2518. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2519. va_end(ap);
  2520. mg_write(conn, buf, strlen(buf));
  2521. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2522. }
  2523. } else {
  2524. /* No body allowed. Close the connection. */
  2525. DEBUG_TRACE("Error %i", status);
  2526. }
  2527. }
  2528. }
  2529. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2530. /* Create substitutes for POSIX functions in Win32. */
  2531. #if defined(__MINGW32__)
  2532. /* Show no warning in case system functions are not used. */
  2533. #pragma GCC diagnostic push
  2534. #pragma GCC diagnostic ignored "-Wunused-function"
  2535. #endif
  2536. static int
  2537. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2538. {
  2539. (void)unused;
  2540. *mutex = CreateMutex(NULL, FALSE, NULL);
  2541. return (*mutex == NULL) ? -1 : 0;
  2542. }
  2543. static int
  2544. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2545. {
  2546. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2547. }
  2548. static int
  2549. pthread_mutex_lock(pthread_mutex_t *mutex)
  2550. {
  2551. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2552. }
  2553. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2554. static int
  2555. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2556. {
  2557. switch (WaitForSingleObject(*mutex, 0)) {
  2558. case WAIT_OBJECT_0:
  2559. return 0;
  2560. case WAIT_TIMEOUT:
  2561. return -2; /* EBUSY */
  2562. }
  2563. return -1;
  2564. }
  2565. #endif
  2566. static int
  2567. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2568. {
  2569. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2570. }
  2571. #ifndef WIN_PTHREADS_TIME_H
  2572. static int
  2573. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2574. {
  2575. FILETIME ft;
  2576. ULARGE_INTEGER li;
  2577. BOOL ok = FALSE;
  2578. double d;
  2579. static double perfcnt_per_sec = 0.0;
  2580. if (tp) {
  2581. memset(tp, 0, sizeof(*tp));
  2582. if (clk_id == CLOCK_REALTIME) {
  2583. GetSystemTimeAsFileTime(&ft);
  2584. li.LowPart = ft.dwLowDateTime;
  2585. li.HighPart = ft.dwHighDateTime;
  2586. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2587. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2588. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2589. ok = TRUE;
  2590. } else if (clk_id == CLOCK_MONOTONIC) {
  2591. if (perfcnt_per_sec == 0.0) {
  2592. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2593. perfcnt_per_sec = 1.0 / li.QuadPart;
  2594. }
  2595. if (perfcnt_per_sec != 0.0) {
  2596. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2597. d = li.QuadPart * perfcnt_per_sec;
  2598. tp->tv_sec = (time_t)d;
  2599. d -= tp->tv_sec;
  2600. tp->tv_nsec = (long)(d * 1.0E9);
  2601. ok = TRUE;
  2602. }
  2603. }
  2604. }
  2605. return ok ? 0 : -1;
  2606. }
  2607. #endif
  2608. static int
  2609. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2610. {
  2611. (void)unused;
  2612. InitializeCriticalSection(&cv->threadIdSec);
  2613. cv->waiting_thread = NULL;
  2614. return 0;
  2615. }
  2616. static int
  2617. pthread_cond_timedwait(pthread_cond_t *cv,
  2618. pthread_mutex_t *mutex,
  2619. const struct timespec *abstime)
  2620. {
  2621. struct mg_workerTLS **ptls,
  2622. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2623. int ok;
  2624. struct timespec tsnow;
  2625. int64_t nsnow, nswaitabs, nswaitrel;
  2626. DWORD mswaitrel;
  2627. EnterCriticalSection(&cv->threadIdSec);
  2628. /* Add this thread to cv's waiting list */
  2629. ptls = &cv->waiting_thread;
  2630. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2631. ;
  2632. tls->next_waiting_thread = NULL;
  2633. *ptls = tls;
  2634. LeaveCriticalSection(&cv->threadIdSec);
  2635. if (abstime) {
  2636. clock_gettime(CLOCK_REALTIME, &tsnow);
  2637. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2638. nswaitabs =
  2639. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2640. nswaitrel = nswaitabs - nsnow;
  2641. if (nswaitrel < 0) {
  2642. nswaitrel = 0;
  2643. }
  2644. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2645. } else {
  2646. mswaitrel = INFINITE;
  2647. }
  2648. pthread_mutex_unlock(mutex);
  2649. ok = (WAIT_OBJECT_0
  2650. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2651. if (!ok) {
  2652. ok = 1;
  2653. EnterCriticalSection(&cv->threadIdSec);
  2654. ptls = &cv->waiting_thread;
  2655. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2656. if (*ptls == tls) {
  2657. *ptls = tls->next_waiting_thread;
  2658. ok = 0;
  2659. break;
  2660. }
  2661. }
  2662. LeaveCriticalSection(&cv->threadIdSec);
  2663. if (ok) {
  2664. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2665. }
  2666. }
  2667. /* This thread has been removed from cv's waiting list */
  2668. pthread_mutex_lock(mutex);
  2669. return ok ? 0 : -1;
  2670. }
  2671. static int
  2672. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2673. {
  2674. return pthread_cond_timedwait(cv, mutex, NULL);
  2675. }
  2676. static int
  2677. pthread_cond_signal(pthread_cond_t *cv)
  2678. {
  2679. HANDLE wkup = NULL;
  2680. BOOL ok = FALSE;
  2681. EnterCriticalSection(&cv->threadIdSec);
  2682. if (cv->waiting_thread) {
  2683. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2684. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2685. ok = SetEvent(wkup);
  2686. assert(ok);
  2687. }
  2688. LeaveCriticalSection(&cv->threadIdSec);
  2689. return ok ? 0 : 1;
  2690. }
  2691. static int
  2692. pthread_cond_broadcast(pthread_cond_t *cv)
  2693. {
  2694. EnterCriticalSection(&cv->threadIdSec);
  2695. while (cv->waiting_thread) {
  2696. pthread_cond_signal(cv);
  2697. }
  2698. LeaveCriticalSection(&cv->threadIdSec);
  2699. return 0;
  2700. }
  2701. static int
  2702. pthread_cond_destroy(pthread_cond_t *cv)
  2703. {
  2704. EnterCriticalSection(&cv->threadIdSec);
  2705. assert(cv->waiting_thread == NULL);
  2706. LeaveCriticalSection(&cv->threadIdSec);
  2707. DeleteCriticalSection(&cv->threadIdSec);
  2708. return 0;
  2709. }
  2710. #ifdef ALTERNATIVE_QUEUE
  2711. static void *
  2712. event_create(void)
  2713. {
  2714. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2715. }
  2716. static int
  2717. event_wait(void *eventhdl)
  2718. {
  2719. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2720. return (res == WAIT_OBJECT_0);
  2721. }
  2722. static int
  2723. event_signal(void *eventhdl)
  2724. {
  2725. return (int)SetEvent((HANDLE)eventhdl);
  2726. }
  2727. static void
  2728. event_destroy(void *eventhdl)
  2729. {
  2730. CloseHandle((HANDLE)eventhdl);
  2731. }
  2732. #endif
  2733. #if defined(__MINGW32__)
  2734. /* Enable unused function warning again */
  2735. #pragma GCC diagnostic pop
  2736. #endif
  2737. /* For Windows, change all slashes to backslashes in path names. */
  2738. static void
  2739. change_slashes_to_backslashes(char *path)
  2740. {
  2741. int i;
  2742. for (i = 0; path[i] != '\0'; i++) {
  2743. if (path[i] == '/') {
  2744. path[i] = '\\';
  2745. }
  2746. /* remove double backslash (check i > 0 to preserve UNC paths,
  2747. * like \\server\file.txt) */
  2748. if ((path[i] == '\\') && (i > 0)) {
  2749. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2750. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2751. }
  2752. }
  2753. }
  2754. }
  2755. static int
  2756. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2757. {
  2758. int diff;
  2759. do {
  2760. diff = tolower(*s1) - tolower(*s2);
  2761. s1++;
  2762. s2++;
  2763. } while (diff == 0 && s1[-1] != '\0');
  2764. return diff;
  2765. }
  2766. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2767. * wbuf and wbuf_len is a target buffer and its length. */
  2768. static void
  2769. path_to_unicode(const struct mg_connection *conn,
  2770. const char *path,
  2771. wchar_t *wbuf,
  2772. size_t wbuf_len)
  2773. {
  2774. char buf[PATH_MAX], buf2[PATH_MAX];
  2775. wchar_t wbuf2[MAX_PATH + 1];
  2776. DWORD long_len, err;
  2777. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  2778. mg_strlcpy(buf, path, sizeof(buf));
  2779. change_slashes_to_backslashes(buf);
  2780. /* Convert to Unicode and back. If doubly-converted string does not
  2781. * match the original, something is fishy, reject. */
  2782. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2783. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2784. WideCharToMultiByte(
  2785. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2786. if (strcmp(buf, buf2) != 0) {
  2787. wbuf[0] = L'\0';
  2788. }
  2789. /* TODO: Add a configuration to switch between case sensitive and
  2790. * case insensitive URIs for Windows server. */
  2791. /*
  2792. if (conn) {
  2793. if (conn->ctx->config[WINDOWS_CASE_SENSITIVE]) {
  2794. fcompare = wcscmp;
  2795. }
  2796. }
  2797. */
  2798. (void)conn; /* conn is currently unused */
  2799. #if !defined(_WIN32_WCE)
  2800. /* Only accept a full file path, not a Windows short (8.3) path. */
  2801. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  2802. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  2803. if (long_len == 0) {
  2804. err = GetLastError();
  2805. if (err == ERROR_FILE_NOT_FOUND) {
  2806. /* File does not exist. This is not always a problem here. */
  2807. return;
  2808. }
  2809. }
  2810. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  2811. /* Short name is used. */
  2812. wbuf[0] = L'\0';
  2813. }
  2814. #else
  2815. (void)long_len;
  2816. (void)wbuf2;
  2817. (void)err;
  2818. if (strchr(path, '~')) {
  2819. wbuf[0] = L'\0';
  2820. }
  2821. #endif
  2822. }
  2823. /* Windows happily opens files with some garbage at the end of file name.
  2824. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2825. * "a.cgi", despite one would expect an error back.
  2826. * This function returns non-0 if path ends with some garbage. */
  2827. static int
  2828. path_cannot_disclose_cgi(const char *path)
  2829. {
  2830. static const char *allowed_last_characters = "_-";
  2831. int last = path[strlen(path) - 1];
  2832. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2833. }
  2834. static int
  2835. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2836. {
  2837. wchar_t wbuf[PATH_MAX];
  2838. WIN32_FILE_ATTRIBUTE_DATA info;
  2839. time_t creation_time;
  2840. if (!filep) {
  2841. return 0;
  2842. }
  2843. memset(filep, 0, sizeof(*filep));
  2844. if (conn && is_file_in_memory(conn, path, filep)) {
  2845. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2846. * memset */
  2847. filep->last_modified = time(NULL);
  2848. /* last_modified = now ... assumes the file may change during runtime,
  2849. * so every mg_fopen call may return different data */
  2850. /* last_modified = conn->ctx.start_time;
  2851. * May be used it the data does not change during runtime. This allows
  2852. * browser caching. Since we do not know, we have to assume the file
  2853. * in memory may change. */
  2854. return 1;
  2855. }
  2856. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2857. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2858. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2859. filep->last_modified =
  2860. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2861. info.ftLastWriteTime.dwHighDateTime);
  2862. /* On Windows, the file creation time can be higher than the
  2863. * modification time, e.g. when a file is copied.
  2864. * Since the Last-Modified timestamp is used for caching
  2865. * it should be based on the most recent timestamp. */
  2866. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2867. info.ftCreationTime.dwHighDateTime);
  2868. if (creation_time > filep->last_modified) {
  2869. filep->last_modified = creation_time;
  2870. }
  2871. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2872. /* If file name is fishy, reset the file structure and return
  2873. * error.
  2874. * Note it is important to reset, not just return the error, cause
  2875. * functions like is_file_opened() check the struct. */
  2876. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2877. memset(filep, 0, sizeof(*filep));
  2878. return 0;
  2879. }
  2880. return 1;
  2881. }
  2882. return 0;
  2883. }
  2884. static int
  2885. mg_remove(const struct mg_connection *conn, const char *path)
  2886. {
  2887. wchar_t wbuf[PATH_MAX];
  2888. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2889. return DeleteFileW(wbuf) ? 0 : -1;
  2890. }
  2891. static int
  2892. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  2893. {
  2894. wchar_t wbuf[PATH_MAX];
  2895. (void)mode;
  2896. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2897. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2898. }
  2899. /* Create substitutes for POSIX functions in Win32. */
  2900. #if defined(__MINGW32__)
  2901. /* Show no warning in case system functions are not used. */
  2902. #pragma GCC diagnostic push
  2903. #pragma GCC diagnostic ignored "-Wunused-function"
  2904. #endif
  2905. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2906. static DIR *
  2907. mg_opendir(const struct mg_connection *conn, const char *name)
  2908. {
  2909. DIR *dir = NULL;
  2910. wchar_t wpath[PATH_MAX];
  2911. DWORD attrs;
  2912. if (name == NULL) {
  2913. SetLastError(ERROR_BAD_ARGUMENTS);
  2914. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2915. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2916. } else {
  2917. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  2918. attrs = GetFileAttributesW(wpath);
  2919. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2920. == FILE_ATTRIBUTE_DIRECTORY)) {
  2921. (void)wcscat(wpath, L"\\*");
  2922. dir->handle = FindFirstFileW(wpath, &dir->info);
  2923. dir->result.d_name[0] = '\0';
  2924. } else {
  2925. mg_free(dir);
  2926. dir = NULL;
  2927. }
  2928. }
  2929. return dir;
  2930. }
  2931. static int
  2932. mg_closedir(DIR *dir)
  2933. {
  2934. int result = 0;
  2935. if (dir != NULL) {
  2936. if (dir->handle != INVALID_HANDLE_VALUE)
  2937. result = FindClose(dir->handle) ? 0 : -1;
  2938. mg_free(dir);
  2939. } else {
  2940. result = -1;
  2941. SetLastError(ERROR_BAD_ARGUMENTS);
  2942. }
  2943. return result;
  2944. }
  2945. static struct dirent *
  2946. mg_readdir(DIR *dir)
  2947. {
  2948. struct dirent *result = 0;
  2949. if (dir) {
  2950. if (dir->handle != INVALID_HANDLE_VALUE) {
  2951. result = &dir->result;
  2952. (void)WideCharToMultiByte(CP_UTF8,
  2953. 0,
  2954. dir->info.cFileName,
  2955. -1,
  2956. result->d_name,
  2957. sizeof(result->d_name),
  2958. NULL,
  2959. NULL);
  2960. if (!FindNextFileW(dir->handle, &dir->info)) {
  2961. (void)FindClose(dir->handle);
  2962. dir->handle = INVALID_HANDLE_VALUE;
  2963. }
  2964. } else {
  2965. SetLastError(ERROR_FILE_NOT_FOUND);
  2966. }
  2967. } else {
  2968. SetLastError(ERROR_BAD_ARGUMENTS);
  2969. }
  2970. return result;
  2971. }
  2972. #ifndef HAVE_POLL
  2973. static int
  2974. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2975. {
  2976. struct timeval tv;
  2977. fd_set set;
  2978. unsigned int i;
  2979. int result;
  2980. SOCKET maxfd = 0;
  2981. memset(&tv, 0, sizeof(tv));
  2982. tv.tv_sec = milliseconds / 1000;
  2983. tv.tv_usec = (milliseconds % 1000) * 1000;
  2984. FD_ZERO(&set);
  2985. for (i = 0; i < n; i++) {
  2986. FD_SET((SOCKET)pfd[i].fd, &set);
  2987. pfd[i].revents = 0;
  2988. if (pfd[i].fd > maxfd) {
  2989. maxfd = pfd[i].fd;
  2990. }
  2991. }
  2992. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2993. for (i = 0; i < n; i++) {
  2994. if (FD_ISSET(pfd[i].fd, &set)) {
  2995. pfd[i].revents = POLLIN;
  2996. }
  2997. }
  2998. }
  2999. return result;
  3000. }
  3001. #endif /* HAVE_POLL */
  3002. #if defined(__MINGW32__)
  3003. /* Enable unused function warning again */
  3004. #pragma GCC diagnostic pop
  3005. #endif
  3006. static void
  3007. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3008. {
  3009. (void)conn; /* Unused. */
  3010. #if defined(_WIN32_WCE)
  3011. (void)sock;
  3012. #else
  3013. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3014. #endif
  3015. }
  3016. int
  3017. mg_start_thread(mg_thread_func_t f, void *p)
  3018. {
  3019. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3020. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3021. */
  3022. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3023. == ((uintptr_t)(-1L)))
  3024. ? -1
  3025. : 0);
  3026. #else
  3027. return (
  3028. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3029. ? -1
  3030. : 0);
  3031. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3032. }
  3033. /* Start a thread storing the thread context. */
  3034. static int
  3035. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3036. void *p,
  3037. pthread_t *threadidptr)
  3038. {
  3039. uintptr_t uip;
  3040. HANDLE threadhandle;
  3041. int result = -1;
  3042. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3043. threadhandle = (HANDLE)uip;
  3044. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3045. *threadidptr = threadhandle;
  3046. result = 0;
  3047. }
  3048. return result;
  3049. }
  3050. /* Wait for a thread to finish. */
  3051. static int
  3052. mg_join_thread(pthread_t threadid)
  3053. {
  3054. int result;
  3055. DWORD dwevent;
  3056. result = -1;
  3057. dwevent = WaitForSingleObject(threadid, INFINITE);
  3058. if (dwevent == WAIT_FAILED) {
  3059. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3060. } else {
  3061. if (dwevent == WAIT_OBJECT_0) {
  3062. CloseHandle(threadid);
  3063. result = 0;
  3064. }
  3065. }
  3066. return result;
  3067. }
  3068. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3069. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3070. /* Create substitutes for POSIX functions in Win32. */
  3071. #if defined(__MINGW32__)
  3072. /* Show no warning in case system functions are not used. */
  3073. #pragma GCC diagnostic push
  3074. #pragma GCC diagnostic ignored "-Wunused-function"
  3075. #endif
  3076. static HANDLE
  3077. dlopen(const char *dll_name, int flags)
  3078. {
  3079. wchar_t wbuf[PATH_MAX];
  3080. (void)flags;
  3081. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3082. return LoadLibraryW(wbuf);
  3083. }
  3084. static int
  3085. dlclose(void *handle)
  3086. {
  3087. int result;
  3088. if (FreeLibrary((HMODULE)handle) != 0) {
  3089. result = 0;
  3090. } else {
  3091. result = -1;
  3092. }
  3093. return result;
  3094. }
  3095. #if defined(__MINGW32__)
  3096. /* Enable unused function warning again */
  3097. #pragma GCC diagnostic pop
  3098. #endif
  3099. #endif
  3100. #if !defined(NO_CGI)
  3101. #define SIGKILL (0)
  3102. static int
  3103. kill(pid_t pid, int sig_num)
  3104. {
  3105. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3106. (void)CloseHandle((HANDLE)pid);
  3107. return 0;
  3108. }
  3109. static void
  3110. trim_trailing_whitespaces(char *s)
  3111. {
  3112. char *e = s + strlen(s) - 1;
  3113. while (e > s && isspace(*(unsigned char *)e)) {
  3114. *e-- = '\0';
  3115. }
  3116. }
  3117. static pid_t
  3118. spawn_process(struct mg_connection *conn,
  3119. const char *prog,
  3120. char *envblk,
  3121. char *envp[],
  3122. int fdin[2],
  3123. int fdout[2],
  3124. int fderr[2],
  3125. const char *dir)
  3126. {
  3127. HANDLE me;
  3128. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3129. cmdline[PATH_MAX], buf[PATH_MAX];
  3130. int truncated;
  3131. struct file file = STRUCT_FILE_INITIALIZER;
  3132. STARTUPINFOA si;
  3133. PROCESS_INFORMATION pi = {0};
  3134. (void)envp;
  3135. memset(&si, 0, sizeof(si));
  3136. si.cb = sizeof(si);
  3137. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3138. si.wShowWindow = SW_HIDE;
  3139. me = GetCurrentProcess();
  3140. DuplicateHandle(me,
  3141. (HANDLE)_get_osfhandle(fdin[0]),
  3142. me,
  3143. &si.hStdInput,
  3144. 0,
  3145. TRUE,
  3146. DUPLICATE_SAME_ACCESS);
  3147. DuplicateHandle(me,
  3148. (HANDLE)_get_osfhandle(fdout[1]),
  3149. me,
  3150. &si.hStdOutput,
  3151. 0,
  3152. TRUE,
  3153. DUPLICATE_SAME_ACCESS);
  3154. DuplicateHandle(me,
  3155. (HANDLE)_get_osfhandle(fderr[1]),
  3156. me,
  3157. &si.hStdError,
  3158. 0,
  3159. TRUE,
  3160. DUPLICATE_SAME_ACCESS);
  3161. /* Mark handles that should not be inherited. See
  3162. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3163. */
  3164. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3165. HANDLE_FLAG_INHERIT,
  3166. 0);
  3167. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3168. HANDLE_FLAG_INHERIT,
  3169. 0);
  3170. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3171. HANDLE_FLAG_INHERIT,
  3172. 0);
  3173. /* If CGI file is a script, try to read the interpreter line */
  3174. interp = conn->ctx->config[CGI_INTERPRETER];
  3175. if (interp == NULL) {
  3176. buf[0] = buf[1] = '\0';
  3177. /* Read the first line of the script into the buffer */
  3178. mg_snprintf(
  3179. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3180. if (truncated) {
  3181. pi.hProcess = (pid_t)-1;
  3182. goto spawn_cleanup;
  3183. }
  3184. if (mg_fopen(conn, cmdline, "r", &file)) {
  3185. p = (char *)file.membuf;
  3186. mg_fgets(buf, sizeof(buf), &file, &p);
  3187. mg_fclose(&file);
  3188. buf[sizeof(buf) - 1] = '\0';
  3189. }
  3190. if (buf[0] == '#' && buf[1] == '!') {
  3191. trim_trailing_whitespaces(buf + 2);
  3192. } else {
  3193. buf[2] = '\0';
  3194. }
  3195. interp = buf + 2;
  3196. }
  3197. if (interp[0] != '\0') {
  3198. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3199. interp = full_interp;
  3200. }
  3201. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3202. if (interp[0] != '\0') {
  3203. mg_snprintf(conn,
  3204. &truncated,
  3205. cmdline,
  3206. sizeof(cmdline),
  3207. "\"%s\" \"%s\\%s\"",
  3208. interp,
  3209. full_dir,
  3210. prog);
  3211. } else {
  3212. mg_snprintf(conn,
  3213. &truncated,
  3214. cmdline,
  3215. sizeof(cmdline),
  3216. "\"%s\\%s\"",
  3217. full_dir,
  3218. prog);
  3219. }
  3220. if (truncated) {
  3221. pi.hProcess = (pid_t)-1;
  3222. goto spawn_cleanup;
  3223. }
  3224. DEBUG_TRACE("Running [%s]", cmdline);
  3225. if (CreateProcessA(NULL,
  3226. cmdline,
  3227. NULL,
  3228. NULL,
  3229. TRUE,
  3230. CREATE_NEW_PROCESS_GROUP,
  3231. envblk,
  3232. NULL,
  3233. &si,
  3234. &pi) == 0) {
  3235. mg_cry(
  3236. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3237. pi.hProcess = (pid_t)-1;
  3238. /* goto spawn_cleanup; */
  3239. }
  3240. spawn_cleanup:
  3241. (void)CloseHandle(si.hStdOutput);
  3242. (void)CloseHandle(si.hStdError);
  3243. (void)CloseHandle(si.hStdInput);
  3244. if (pi.hThread != NULL) {
  3245. (void)CloseHandle(pi.hThread);
  3246. }
  3247. return (pid_t)pi.hProcess;
  3248. }
  3249. #endif /* !NO_CGI */
  3250. static int
  3251. set_non_blocking_mode(SOCKET sock)
  3252. {
  3253. unsigned long on = 1;
  3254. return ioctlsocket(sock, (long)FIONBIO, &on);
  3255. }
  3256. #else
  3257. static int
  3258. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  3259. {
  3260. struct stat st;
  3261. if (!filep) {
  3262. return 0;
  3263. }
  3264. memset(filep, 0, sizeof(*filep));
  3265. if (conn && is_file_in_memory(conn, path, filep)) {
  3266. return 1;
  3267. }
  3268. if (0 == stat(path, &st)) {
  3269. filep->size = (uint64_t)(st.st_size);
  3270. filep->last_modified = st.st_mtime;
  3271. filep->is_directory = S_ISDIR(st.st_mode);
  3272. return 1;
  3273. }
  3274. return 0;
  3275. }
  3276. static void
  3277. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3278. {
  3279. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3280. if (conn) {
  3281. mg_cry(conn,
  3282. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3283. __func__,
  3284. strerror(ERRNO));
  3285. }
  3286. }
  3287. }
  3288. int
  3289. mg_start_thread(mg_thread_func_t func, void *param)
  3290. {
  3291. pthread_t thread_id;
  3292. pthread_attr_t attr;
  3293. int result;
  3294. (void)pthread_attr_init(&attr);
  3295. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3296. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3297. /* Compile-time option to control stack size,
  3298. * e.g. -DUSE_STACK_SIZE=16384 */
  3299. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3300. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3301. result = pthread_create(&thread_id, &attr, func, param);
  3302. pthread_attr_destroy(&attr);
  3303. return result;
  3304. }
  3305. /* Start a thread storing the thread context. */
  3306. static int
  3307. mg_start_thread_with_id(mg_thread_func_t func,
  3308. void *param,
  3309. pthread_t *threadidptr)
  3310. {
  3311. pthread_t thread_id;
  3312. pthread_attr_t attr;
  3313. int result;
  3314. (void)pthread_attr_init(&attr);
  3315. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3316. /* Compile-time option to control stack size,
  3317. * e.g. -DUSE_STACK_SIZE=16384 */
  3318. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3319. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3320. result = pthread_create(&thread_id, &attr, func, param);
  3321. pthread_attr_destroy(&attr);
  3322. if ((result == 0) && (threadidptr != NULL)) {
  3323. *threadidptr = thread_id;
  3324. }
  3325. return result;
  3326. }
  3327. /* Wait for a thread to finish. */
  3328. static int
  3329. mg_join_thread(pthread_t threadid)
  3330. {
  3331. int result;
  3332. result = pthread_join(threadid, NULL);
  3333. return result;
  3334. }
  3335. #ifndef NO_CGI
  3336. static pid_t
  3337. spawn_process(struct mg_connection *conn,
  3338. const char *prog,
  3339. char *envblk,
  3340. char *envp[],
  3341. int fdin[2],
  3342. int fdout[2],
  3343. int fderr[2],
  3344. const char *dir)
  3345. {
  3346. pid_t pid;
  3347. const char *interp;
  3348. (void)envblk;
  3349. if (conn == NULL) {
  3350. return 0;
  3351. }
  3352. if ((pid = fork()) == -1) {
  3353. /* Parent */
  3354. send_http_error(conn,
  3355. 500,
  3356. "Error: Creating CGI process\nfork(): %s",
  3357. strerror(ERRNO));
  3358. } else if (pid == 0) {
  3359. /* Child */
  3360. if (chdir(dir) != 0) {
  3361. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3362. } else if (dup2(fdin[0], 0) == -1) {
  3363. mg_cry(conn,
  3364. "%s: dup2(%d, 0): %s",
  3365. __func__,
  3366. fdin[0],
  3367. strerror(ERRNO));
  3368. } else if (dup2(fdout[1], 1) == -1) {
  3369. mg_cry(conn,
  3370. "%s: dup2(%d, 1): %s",
  3371. __func__,
  3372. fdout[1],
  3373. strerror(ERRNO));
  3374. } else if (dup2(fderr[1], 2) == -1) {
  3375. mg_cry(conn,
  3376. "%s: dup2(%d, 2): %s",
  3377. __func__,
  3378. fderr[1],
  3379. strerror(ERRNO));
  3380. } else {
  3381. /* Keep stderr and stdout in two different pipes.
  3382. * Stdout will be sent back to the client,
  3383. * stderr should go into a server error log. */
  3384. (void)close(fdin[0]);
  3385. (void)close(fdout[1]);
  3386. (void)close(fderr[1]);
  3387. /* Close write end fdin and read end fdout and fderr */
  3388. (void)close(fdin[1]);
  3389. (void)close(fdout[0]);
  3390. (void)close(fderr[0]);
  3391. /* After exec, all signal handlers are restored to their default
  3392. * values, with one exception of SIGCHLD. According to
  3393. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3394. * leave unchanged after exec if it was set to be ignored. Restore
  3395. * it to default action. */
  3396. signal(SIGCHLD, SIG_DFL);
  3397. interp = conn->ctx->config[CGI_INTERPRETER];
  3398. if (interp == NULL) {
  3399. (void)execle(prog, prog, NULL, envp);
  3400. mg_cry(conn,
  3401. "%s: execle(%s): %s",
  3402. __func__,
  3403. prog,
  3404. strerror(ERRNO));
  3405. } else {
  3406. (void)execle(interp, interp, prog, NULL, envp);
  3407. mg_cry(conn,
  3408. "%s: execle(%s %s): %s",
  3409. __func__,
  3410. interp,
  3411. prog,
  3412. strerror(ERRNO));
  3413. }
  3414. }
  3415. exit(EXIT_FAILURE);
  3416. }
  3417. return pid;
  3418. }
  3419. #endif /* !NO_CGI */
  3420. static int
  3421. set_non_blocking_mode(SOCKET sock)
  3422. {
  3423. int flags;
  3424. flags = fcntl(sock, F_GETFL, 0);
  3425. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3426. return 0;
  3427. }
  3428. #endif /* _WIN32 */
  3429. /* End of initial operating system specific define block. */
  3430. /* Get a random number (independent of C rand function) */
  3431. static uint64_t
  3432. get_random(void)
  3433. {
  3434. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3435. static uint64_t lcg = 0; /* Linear congruential generator */
  3436. struct timespec now;
  3437. memset(&now, 0, sizeof(now));
  3438. clock_gettime(CLOCK_MONOTONIC, &now);
  3439. if (lfsr == 0) {
  3440. /* lfsr will be only 0 if has not been initialized,
  3441. * so this code is called only once. */
  3442. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3443. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3444. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3445. + (uint64_t)(ptrdiff_t)&now;
  3446. } else {
  3447. /* Get the next step of both random number generators. */
  3448. lfsr = (lfsr >> 1)
  3449. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3450. << 63);
  3451. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3452. }
  3453. /* Combining two pseudo-random number generators and a high resolution part
  3454. * of the current server time will make it hard (impossible?) to guess the
  3455. * next number. */
  3456. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3457. }
  3458. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3459. * descriptor. Return number of bytes written. */
  3460. static int
  3461. push(struct mg_context *ctx,
  3462. FILE *fp,
  3463. SOCKET sock,
  3464. SSL *ssl,
  3465. const char *buf,
  3466. int len,
  3467. double timeout)
  3468. {
  3469. struct timespec start, now;
  3470. int n, err;
  3471. #ifdef _WIN32
  3472. typedef int len_t;
  3473. #else
  3474. typedef size_t len_t;
  3475. #endif
  3476. if (timeout > 0) {
  3477. memset(&start, 0, sizeof(start));
  3478. memset(&now, 0, sizeof(now));
  3479. clock_gettime(CLOCK_MONOTONIC, &start);
  3480. }
  3481. if (ctx == NULL) {
  3482. return -1;
  3483. }
  3484. #ifdef NO_SSL
  3485. if (ssl) {
  3486. return -1;
  3487. }
  3488. #endif
  3489. do {
  3490. #ifndef NO_SSL
  3491. if (ssl != NULL) {
  3492. n = SSL_write(ssl, buf, len);
  3493. if (n <= 0) {
  3494. err = SSL_get_error(ssl, n);
  3495. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3496. err = ERRNO;
  3497. } else if ((err == SSL_ERROR_WANT_READ)
  3498. || (err == SSL_ERROR_WANT_WRITE)) {
  3499. n = 0;
  3500. } else {
  3501. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3502. return -1;
  3503. }
  3504. } else {
  3505. err = 0;
  3506. }
  3507. } else
  3508. #endif
  3509. if (fp != NULL) {
  3510. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3511. if (ferror(fp)) {
  3512. n = -1;
  3513. err = ERRNO;
  3514. } else {
  3515. err = 0;
  3516. }
  3517. } else {
  3518. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3519. err = (n < 0) ? ERRNO : 0;
  3520. if (n == 0) {
  3521. /* shutdown of the socket at client side */
  3522. return -1;
  3523. }
  3524. }
  3525. if (ctx->stop_flag) {
  3526. return -1;
  3527. }
  3528. if ((n > 0) || (n == 0 && len == 0)) {
  3529. /* some data has been read, or no data was requested */
  3530. return n;
  3531. }
  3532. if (n < 0) {
  3533. /* socket error - check errno */
  3534. DEBUG_TRACE("send() failed, error %d", err);
  3535. /* TODO: error handling depending on the error code.
  3536. * These codes are different between Windows and Linux.
  3537. */
  3538. return -1;
  3539. }
  3540. /* This code is not reached in the moment.
  3541. * ==> Fix the TODOs above first. */
  3542. if (timeout > 0) {
  3543. clock_gettime(CLOCK_MONOTONIC, &now);
  3544. }
  3545. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3546. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3547. used */
  3548. return -1;
  3549. }
  3550. static int64_t
  3551. push_all(struct mg_context *ctx,
  3552. FILE *fp,
  3553. SOCKET sock,
  3554. SSL *ssl,
  3555. const char *buf,
  3556. int64_t len)
  3557. {
  3558. double timeout = -1.0;
  3559. int64_t n, nwritten = 0;
  3560. if (ctx == NULL) {
  3561. return -1;
  3562. }
  3563. if (ctx->config[REQUEST_TIMEOUT]) {
  3564. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3565. }
  3566. while (len > 0 && ctx->stop_flag == 0) {
  3567. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3568. if (n < 0) {
  3569. if (nwritten == 0) {
  3570. nwritten = n; /* Propagate the error */
  3571. }
  3572. break;
  3573. } else if (n == 0) {
  3574. break; /* No more data to write */
  3575. } else {
  3576. nwritten += n;
  3577. len -= n;
  3578. }
  3579. }
  3580. return nwritten;
  3581. }
  3582. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3583. * Return negative value on error, or number of bytes read on success. */
  3584. static int
  3585. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3586. {
  3587. int nread, err;
  3588. struct timespec start, now;
  3589. #ifdef _WIN32
  3590. typedef int len_t;
  3591. #else
  3592. typedef size_t len_t;
  3593. #endif
  3594. if (timeout > 0) {
  3595. memset(&start, 0, sizeof(start));
  3596. memset(&now, 0, sizeof(now));
  3597. clock_gettime(CLOCK_MONOTONIC, &start);
  3598. }
  3599. do {
  3600. if (fp != NULL) {
  3601. #if !defined(_WIN32_WCE)
  3602. /* Use read() instead of fread(), because if we're reading from the
  3603. * CGI pipe, fread() may block until IO buffer is filled up. We
  3604. * cannot afford to block and must pass all read bytes immediately
  3605. * to the client. */
  3606. nread = (int)read(fileno(fp), buf, (size_t)len);
  3607. #else
  3608. /* WinCE does not support CGI pipes */
  3609. nread = (int)fread(buf, 1, (size_t)len, fp);
  3610. #endif
  3611. err = (nread < 0) ? ERRNO : 0;
  3612. #ifndef NO_SSL
  3613. } else if (conn->ssl != NULL) {
  3614. nread = SSL_read(conn->ssl, buf, len);
  3615. if (nread <= 0) {
  3616. err = SSL_get_error(conn->ssl, nread);
  3617. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3618. err = ERRNO;
  3619. } else if ((err == SSL_ERROR_WANT_READ)
  3620. || (err == SSL_ERROR_WANT_WRITE)) {
  3621. nread = 0;
  3622. } else {
  3623. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3624. return -1;
  3625. }
  3626. } else {
  3627. err = 0;
  3628. }
  3629. #endif
  3630. } else {
  3631. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3632. err = (nread < 0) ? ERRNO : 0;
  3633. if (nread == 0) {
  3634. /* shutdown of the socket at client side */
  3635. return -1;
  3636. }
  3637. }
  3638. if (conn->ctx->stop_flag) {
  3639. return -1;
  3640. }
  3641. if ((nread > 0) || (nread == 0 && len == 0)) {
  3642. /* some data has been read, or no data was requested */
  3643. return nread;
  3644. }
  3645. if (nread < 0) {
  3646. /* socket error - check errno */
  3647. #ifdef _WIN32
  3648. if (err == WSAEWOULDBLOCK) {
  3649. /* standard case if called from close_socket_gracefully */
  3650. return -1;
  3651. } else if (err == WSAETIMEDOUT) {
  3652. /* timeout is handled by the while loop */
  3653. } else {
  3654. DEBUG_TRACE("recv() failed, error %d", err);
  3655. return -1;
  3656. }
  3657. #else
  3658. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3659. * if the timeout is reached and if the socket was set to non-
  3660. * blocking in close_socket_gracefully, so we can not distinguish
  3661. * here. We have to wait for the timeout in both cases for now.
  3662. */
  3663. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3664. /* EAGAIN/EWOULDBLOCK:
  3665. * standard case if called from close_socket_gracefully
  3666. * => should return -1 */
  3667. /* or timeout occured
  3668. * => the code must stay in the while loop */
  3669. /* EINTR can be generated on a socket with a timeout set even
  3670. * when SA_RESTART is effective for all relevant signals
  3671. * (see signal(7)).
  3672. * => stay in the while loop */
  3673. } else {
  3674. DEBUG_TRACE("recv() failed, error %d", err);
  3675. return -1;
  3676. }
  3677. #endif
  3678. }
  3679. if (timeout > 0) {
  3680. clock_gettime(CLOCK_MONOTONIC, &now);
  3681. }
  3682. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3683. /* Timeout occured, but no data available. */
  3684. return -1;
  3685. }
  3686. static int
  3687. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3688. {
  3689. int n, nread = 0;
  3690. double timeout = -1.0;
  3691. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3692. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3693. }
  3694. while (len > 0 && conn->ctx->stop_flag == 0) {
  3695. n = pull(fp, conn, buf + nread, len, timeout);
  3696. if (n < 0) {
  3697. if (nread == 0) {
  3698. nread = n; /* Propagate the error */
  3699. }
  3700. break;
  3701. } else if (n == 0) {
  3702. break; /* No more data to read */
  3703. } else {
  3704. conn->consumed_content += n;
  3705. nread += n;
  3706. len -= n;
  3707. }
  3708. }
  3709. return nread;
  3710. }
  3711. static void
  3712. discard_unread_request_data(struct mg_connection *conn)
  3713. {
  3714. char buf[MG_BUF_LEN];
  3715. size_t to_read;
  3716. int nread;
  3717. if (conn == NULL) {
  3718. return;
  3719. }
  3720. to_read = sizeof(buf);
  3721. if (conn->is_chunked) {
  3722. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3723. * completely */
  3724. while (conn->is_chunked == 1) {
  3725. nread = mg_read(conn, buf, to_read);
  3726. if (nread <= 0) {
  3727. break;
  3728. }
  3729. }
  3730. } else {
  3731. /* Not chunked: content length is known */
  3732. while (conn->consumed_content < conn->content_len) {
  3733. if (to_read
  3734. > (size_t)(conn->content_len - conn->consumed_content)) {
  3735. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3736. }
  3737. nread = mg_read(conn, buf, to_read);
  3738. if (nread <= 0) {
  3739. break;
  3740. }
  3741. }
  3742. }
  3743. }
  3744. static int
  3745. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3746. {
  3747. int64_t n, buffered_len, nread;
  3748. int64_t len64 =
  3749. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  3750. * int, we may not read more
  3751. * bytes */
  3752. const char *body;
  3753. if (conn == NULL) {
  3754. return 0;
  3755. }
  3756. /* If Content-Length is not set for a PUT or POST request, read until
  3757. * socket is closed */
  3758. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3759. conn->content_len = INT64_MAX;
  3760. conn->must_close = 1;
  3761. }
  3762. nread = 0;
  3763. if (conn->consumed_content < conn->content_len) {
  3764. /* Adjust number of bytes to read. */
  3765. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3766. if (left_to_read < len64) {
  3767. /* Do not read more than the total content length of the request.
  3768. */
  3769. len64 = left_to_read;
  3770. }
  3771. /* Return buffered data */
  3772. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3773. - conn->consumed_content;
  3774. if (buffered_len > 0) {
  3775. if (len64 < buffered_len) {
  3776. buffered_len = len64;
  3777. }
  3778. body = conn->buf + conn->request_len + conn->consumed_content;
  3779. memcpy(buf, body, (size_t)buffered_len);
  3780. len64 -= buffered_len;
  3781. conn->consumed_content += buffered_len;
  3782. nread += buffered_len;
  3783. buf = (char *)buf + buffered_len;
  3784. }
  3785. /* We have returned all buffered data. Read new data from the remote
  3786. * socket.
  3787. */
  3788. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3789. nread += n;
  3790. } else {
  3791. nread = ((nread > 0) ? nread : n);
  3792. }
  3793. }
  3794. return (int)nread;
  3795. }
  3796. static char
  3797. mg_getc(struct mg_connection *conn)
  3798. {
  3799. char c;
  3800. if (conn == NULL) {
  3801. return 0;
  3802. }
  3803. conn->content_len++;
  3804. if (mg_read_inner(conn, &c, 1) <= 0) {
  3805. return (char)0;
  3806. }
  3807. return c;
  3808. }
  3809. int
  3810. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3811. {
  3812. if (len > INT_MAX) {
  3813. len = INT_MAX;
  3814. }
  3815. if (conn == NULL) {
  3816. return 0;
  3817. }
  3818. if (conn->is_chunked) {
  3819. size_t all_read = 0;
  3820. while (len > 0) {
  3821. if (conn->is_chunked == 2) {
  3822. /* No more data left to read */
  3823. return 0;
  3824. }
  3825. if (conn->chunk_remainder) {
  3826. /* copy from the remainder of the last received chunk */
  3827. long read_ret;
  3828. size_t read_now =
  3829. ((conn->chunk_remainder > len) ? (len)
  3830. : (conn->chunk_remainder));
  3831. conn->content_len += (int)read_now;
  3832. read_ret =
  3833. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3834. all_read += (size_t)read_ret;
  3835. conn->chunk_remainder -= read_now;
  3836. len -= read_now;
  3837. if (conn->chunk_remainder == 0) {
  3838. /* the rest of the data in the current chunk has been read
  3839. */
  3840. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3841. /* Protocol violation */
  3842. return -1;
  3843. }
  3844. }
  3845. } else {
  3846. /* fetch a new chunk */
  3847. int i = 0;
  3848. char lenbuf[64];
  3849. char *end = 0;
  3850. unsigned long chunkSize = 0;
  3851. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3852. lenbuf[i] = mg_getc(conn);
  3853. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3854. continue;
  3855. }
  3856. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3857. lenbuf[i + 1] = 0;
  3858. chunkSize = strtoul(lenbuf, &end, 16);
  3859. if (chunkSize == 0) {
  3860. /* regular end of content */
  3861. conn->is_chunked = 2;
  3862. }
  3863. break;
  3864. }
  3865. if (!isalnum(lenbuf[i])) {
  3866. /* illegal character for chunk length */
  3867. return -1;
  3868. }
  3869. }
  3870. if ((end == NULL) || (*end != '\r')) {
  3871. /* chunksize not set correctly */
  3872. return -1;
  3873. }
  3874. if (chunkSize == 0) {
  3875. break;
  3876. }
  3877. conn->chunk_remainder = chunkSize;
  3878. }
  3879. }
  3880. return (int)all_read;
  3881. }
  3882. return mg_read_inner(conn, buf, len);
  3883. }
  3884. int
  3885. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3886. {
  3887. time_t now;
  3888. int64_t n, total, allowed;
  3889. if (conn == NULL) {
  3890. return 0;
  3891. }
  3892. if (conn->throttle > 0) {
  3893. if ((now = time(NULL)) != conn->last_throttle_time) {
  3894. conn->last_throttle_time = now;
  3895. conn->last_throttle_bytes = 0;
  3896. }
  3897. allowed = conn->throttle - conn->last_throttle_bytes;
  3898. if (allowed > (int64_t)len) {
  3899. allowed = (int64_t)len;
  3900. }
  3901. if ((total = push_all(conn->ctx,
  3902. NULL,
  3903. conn->client.sock,
  3904. conn->ssl,
  3905. (const char *)buf,
  3906. (int64_t)allowed)) == allowed) {
  3907. buf = (const char *)buf + total;
  3908. conn->last_throttle_bytes += total;
  3909. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3910. allowed = (conn->throttle > ((int64_t)len - total))
  3911. ? (int64_t)len - total
  3912. : conn->throttle;
  3913. if ((n = push_all(conn->ctx,
  3914. NULL,
  3915. conn->client.sock,
  3916. conn->ssl,
  3917. (const char *)buf,
  3918. (int64_t)allowed)) != allowed) {
  3919. break;
  3920. }
  3921. sleep(1);
  3922. conn->last_throttle_bytes = allowed;
  3923. conn->last_throttle_time = time(NULL);
  3924. buf = (const char *)buf + n;
  3925. total += n;
  3926. }
  3927. }
  3928. } else {
  3929. total = push_all(conn->ctx,
  3930. NULL,
  3931. conn->client.sock,
  3932. conn->ssl,
  3933. (const char *)buf,
  3934. (int64_t)len);
  3935. }
  3936. return (int)total;
  3937. }
  3938. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3939. static int
  3940. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3941. {
  3942. va_list ap_copy;
  3943. size_t size = MG_BUF_LEN / 4;
  3944. int len = -1;
  3945. *buf = NULL;
  3946. while (len < 0) {
  3947. if (*buf) {
  3948. mg_free(*buf);
  3949. }
  3950. size *= 4;
  3951. *buf = (char *)mg_malloc(size);
  3952. if (!*buf) {
  3953. break;
  3954. }
  3955. va_copy(ap_copy, ap);
  3956. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3957. va_end(ap_copy);
  3958. (*buf)[size - 1] = 0;
  3959. }
  3960. return len;
  3961. }
  3962. /* Print message to buffer. If buffer is large enough to hold the message,
  3963. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3964. * and return allocated buffer. */
  3965. static int
  3966. alloc_vprintf(char **out_buf,
  3967. char *prealloc_buf,
  3968. size_t prealloc_size,
  3969. const char *fmt,
  3970. va_list ap)
  3971. {
  3972. va_list ap_copy;
  3973. int len;
  3974. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3975. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3976. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3977. * Therefore, we make two passes: on first pass, get required message
  3978. * length.
  3979. * On second pass, actually print the message. */
  3980. va_copy(ap_copy, ap);
  3981. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3982. va_end(ap_copy);
  3983. if (len < 0) {
  3984. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3985. * Switch to alternative code path that uses incremental allocations.
  3986. */
  3987. va_copy(ap_copy, ap);
  3988. len = alloc_vprintf2(out_buf, fmt, ap);
  3989. va_end(ap_copy);
  3990. } else if ((size_t)(len) >= prealloc_size) {
  3991. /* The pre-allocated buffer not large enough. */
  3992. /* Allocate a new buffer. */
  3993. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3994. if (!*out_buf) {
  3995. /* Allocation failed. Return -1 as "out of memory" error. */
  3996. return -1;
  3997. }
  3998. /* Buffer allocation successful. Store the string there. */
  3999. va_copy(ap_copy, ap);
  4000. IGNORE_UNUSED_RESULT(
  4001. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4002. va_end(ap_copy);
  4003. } else {
  4004. /* The pre-allocated buffer is large enough.
  4005. * Use it to store the string and return the address. */
  4006. va_copy(ap_copy, ap);
  4007. IGNORE_UNUSED_RESULT(
  4008. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4009. va_end(ap_copy);
  4010. *out_buf = prealloc_buf;
  4011. }
  4012. return len;
  4013. }
  4014. static int
  4015. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4016. {
  4017. char mem[MG_BUF_LEN];
  4018. char *buf = NULL;
  4019. int len;
  4020. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4021. len = mg_write(conn, buf, (size_t)len);
  4022. }
  4023. if (buf != mem && buf != NULL) {
  4024. mg_free(buf);
  4025. }
  4026. return len;
  4027. }
  4028. int
  4029. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4030. {
  4031. va_list ap;
  4032. int result;
  4033. va_start(ap, fmt);
  4034. result = mg_vprintf(conn, fmt, ap);
  4035. va_end(ap);
  4036. return result;
  4037. }
  4038. int
  4039. mg_url_decode(const char *src,
  4040. int src_len,
  4041. char *dst,
  4042. int dst_len,
  4043. int is_form_url_encoded)
  4044. {
  4045. int i, j, a, b;
  4046. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4047. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4048. if (i < src_len - 2 && src[i] == '%'
  4049. && isxdigit(*(const unsigned char *)(src + i + 1))
  4050. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4051. a = tolower(*(const unsigned char *)(src + i + 1));
  4052. b = tolower(*(const unsigned char *)(src + i + 2));
  4053. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4054. i += 2;
  4055. } else if (is_form_url_encoded && src[i] == '+') {
  4056. dst[j] = ' ';
  4057. } else {
  4058. dst[j] = src[i];
  4059. }
  4060. }
  4061. dst[j] = '\0'; /* Null-terminate the destination */
  4062. return (i >= src_len) ? j : -1;
  4063. }
  4064. int
  4065. mg_get_var(const char *data,
  4066. size_t data_len,
  4067. const char *name,
  4068. char *dst,
  4069. size_t dst_len)
  4070. {
  4071. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4072. }
  4073. int
  4074. mg_get_var2(const char *data,
  4075. size_t data_len,
  4076. const char *name,
  4077. char *dst,
  4078. size_t dst_len,
  4079. size_t occurrence)
  4080. {
  4081. const char *p, *e, *s;
  4082. size_t name_len;
  4083. int len;
  4084. if (dst == NULL || dst_len == 0) {
  4085. len = -2;
  4086. } else if (data == NULL || name == NULL || data_len == 0) {
  4087. len = -1;
  4088. dst[0] = '\0';
  4089. } else {
  4090. name_len = strlen(name);
  4091. e = data + data_len;
  4092. len = -1;
  4093. dst[0] = '\0';
  4094. /* data is "var1=val1&var2=val2...". Find variable first */
  4095. for (p = data; p + name_len < e; p++) {
  4096. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4097. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4098. /* Point p to variable value */
  4099. p += name_len + 1;
  4100. /* Point s to the end of the value */
  4101. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4102. if (s == NULL) {
  4103. s = e;
  4104. }
  4105. /* assert(s >= p); */
  4106. if (s < p) {
  4107. return -3;
  4108. }
  4109. /* Decode variable into destination buffer */
  4110. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4111. /* Redirect error code from -1 to -2 (destination buffer too
  4112. * small). */
  4113. if (len == -1) {
  4114. len = -2;
  4115. }
  4116. break;
  4117. }
  4118. }
  4119. }
  4120. return len;
  4121. }
  4122. /* HCP24: some changes to compare hole var_name */
  4123. int
  4124. mg_get_cookie(const char *cookie_header,
  4125. const char *var_name,
  4126. char *dst,
  4127. size_t dst_size)
  4128. {
  4129. const char *s, *p, *end;
  4130. int name_len, len = -1;
  4131. if (dst == NULL || dst_size == 0) {
  4132. return -2;
  4133. }
  4134. dst[0] = '\0';
  4135. if (var_name == NULL || (s = cookie_header) == NULL) {
  4136. return -1;
  4137. }
  4138. name_len = (int)strlen(var_name);
  4139. end = s + strlen(s);
  4140. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4141. if (s[name_len] == '=') {
  4142. /* HCP24: now check is it a substring or a full cookie name */
  4143. if ((s == cookie_header) || (s[-1] == ' ')) {
  4144. s += name_len + 1;
  4145. if ((p = strchr(s, ' ')) == NULL) {
  4146. p = end;
  4147. }
  4148. if (p[-1] == ';') {
  4149. p--;
  4150. }
  4151. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4152. s++;
  4153. p--;
  4154. }
  4155. if ((size_t)(p - s) < dst_size) {
  4156. len = (int)(p - s);
  4157. mg_strlcpy(dst, s, (size_t)len + 1);
  4158. } else {
  4159. len = -3;
  4160. }
  4161. break;
  4162. }
  4163. }
  4164. }
  4165. return len;
  4166. }
  4167. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4168. static void
  4169. base64_encode(const unsigned char *src, int src_len, char *dst)
  4170. {
  4171. static const char *b64 =
  4172. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4173. int i, j, a, b, c;
  4174. for (i = j = 0; i < src_len; i += 3) {
  4175. a = src[i];
  4176. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4177. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4178. dst[j++] = b64[a >> 2];
  4179. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4180. if (i + 1 < src_len) {
  4181. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4182. }
  4183. if (i + 2 < src_len) {
  4184. dst[j++] = b64[c & 63];
  4185. }
  4186. }
  4187. while (j % 4 != 0) {
  4188. dst[j++] = '=';
  4189. }
  4190. dst[j++] = '\0';
  4191. }
  4192. #endif
  4193. #if defined(USE_LUA)
  4194. static unsigned char
  4195. b64reverse(char letter)
  4196. {
  4197. if (letter >= 'A' && letter <= 'Z') {
  4198. return letter - 'A';
  4199. }
  4200. if (letter >= 'a' && letter <= 'z') {
  4201. return letter - 'a' + 26;
  4202. }
  4203. if (letter >= '0' && letter <= '9') {
  4204. return letter - '0' + 52;
  4205. }
  4206. if (letter == '+') {
  4207. return 62;
  4208. }
  4209. if (letter == '/') {
  4210. return 63;
  4211. }
  4212. if (letter == '=') {
  4213. return 255; /* normal end */
  4214. }
  4215. return 254; /* error */
  4216. }
  4217. static int
  4218. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4219. {
  4220. int i;
  4221. unsigned char a, b, c, d;
  4222. *dst_len = 0;
  4223. for (i = 0; i < src_len; i += 4) {
  4224. a = b64reverse(src[i]);
  4225. if (a >= 254) {
  4226. return i;
  4227. }
  4228. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4229. if (b >= 254) {
  4230. return i + 1;
  4231. }
  4232. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4233. if (c == 254) {
  4234. return i + 2;
  4235. }
  4236. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4237. if (d == 254) {
  4238. return i + 3;
  4239. }
  4240. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4241. if (c != 255) {
  4242. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4243. if (d != 255) {
  4244. dst[(*dst_len)++] = (c << 6) + d;
  4245. }
  4246. }
  4247. }
  4248. return -1;
  4249. }
  4250. #endif
  4251. static int
  4252. is_put_or_delete_method(const struct mg_connection *conn)
  4253. {
  4254. if (conn) {
  4255. const char *s = conn->request_info.request_method;
  4256. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4257. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4258. }
  4259. return 0;
  4260. }
  4261. static void
  4262. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4263. char *filename, /* out: filename */
  4264. size_t filename_buf_len, /* in: size of filename buffer */
  4265. struct file *filep, /* out: file structure */
  4266. int *is_found, /* out: file is found (directly) */
  4267. int *is_script_resource, /* out: handled by a script? */
  4268. int *is_websocket_request, /* out: websocket connetion? */
  4269. int *is_put_or_delete_request /* out: put/delete a file? */
  4270. )
  4271. {
  4272. /* TODO (high): Restructure this function */
  4273. #if !defined(NO_FILES)
  4274. const char *uri = conn->request_info.local_uri;
  4275. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4276. const char *rewrite;
  4277. struct vec a, b;
  4278. int match_len;
  4279. char gz_path[PATH_MAX];
  4280. char const *accept_encoding;
  4281. int truncated;
  4282. #if !defined(NO_CGI) || defined(USE_LUA)
  4283. char *p;
  4284. #endif
  4285. #else
  4286. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4287. #endif
  4288. memset(filep, 0, sizeof(*filep));
  4289. *filename = 0;
  4290. *is_found = 0;
  4291. *is_script_resource = 0;
  4292. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4293. #if defined(USE_WEBSOCKET)
  4294. *is_websocket_request = is_websocket_protocol(conn);
  4295. #if !defined(NO_FILES)
  4296. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4297. root = conn->ctx->config[WEBSOCKET_ROOT];
  4298. }
  4299. #endif /* !NO_FILES */
  4300. #else /* USE_WEBSOCKET */
  4301. *is_websocket_request = 0;
  4302. #endif /* USE_WEBSOCKET */
  4303. #if !defined(NO_FILES)
  4304. /* Note that root == NULL is a regular use case here. This occurs,
  4305. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4306. * config is not required. */
  4307. if (root == NULL) {
  4308. /* all file related outputs have already been set to 0, just return
  4309. */
  4310. return;
  4311. }
  4312. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4313. * of the path one byte on the right.
  4314. * If document_root is NULL, leave the file empty. */
  4315. mg_snprintf(
  4316. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4317. if (truncated) {
  4318. goto interpret_cleanup;
  4319. }
  4320. rewrite = conn->ctx->config[REWRITE];
  4321. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4322. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4323. mg_snprintf(conn,
  4324. &truncated,
  4325. filename,
  4326. filename_buf_len - 1,
  4327. "%.*s%s",
  4328. (int)b.len,
  4329. b.ptr,
  4330. uri + match_len);
  4331. break;
  4332. }
  4333. }
  4334. if (truncated) {
  4335. goto interpret_cleanup;
  4336. }
  4337. /* Local file path and name, corresponding to requested URI
  4338. * is now stored in "filename" variable. */
  4339. if (mg_stat(conn, filename, filep)) {
  4340. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4341. /* File exists. Check if it is a script type. */
  4342. if (0
  4343. #if !defined(NO_CGI)
  4344. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4345. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4346. filename) > 0
  4347. #endif
  4348. #if defined(USE_LUA)
  4349. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4350. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4351. filename) > 0
  4352. #endif
  4353. #if defined(USE_DUKTAPE)
  4354. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4355. strlen(
  4356. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4357. filename) > 0
  4358. #endif
  4359. ) {
  4360. /* The request addresses a CGI script or a Lua script. The URI
  4361. * corresponds to the script itself (like /path/script.cgi),
  4362. * and there is no additional resource path
  4363. * (like /path/script.cgi/something).
  4364. * Requests that modify (replace or delete) a resource, like
  4365. * PUT and DELETE requests, should replace/delete the script
  4366. * file.
  4367. * Requests that read or write from/to a resource, like GET and
  4368. * POST requests, should call the script and return the
  4369. * generated response. */
  4370. *is_script_resource = !*is_put_or_delete_request;
  4371. }
  4372. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4373. *is_found = 1;
  4374. return;
  4375. }
  4376. /* If we can't find the actual file, look for the file
  4377. * with the same name but a .gz extension. If we find it,
  4378. * use that and set the gzipped flag in the file struct
  4379. * to indicate that the response need to have the content-
  4380. * encoding: gzip header.
  4381. * We can only do this if the browser declares support. */
  4382. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4383. if (strstr(accept_encoding, "gzip") != NULL) {
  4384. mg_snprintf(
  4385. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4386. if (truncated) {
  4387. goto interpret_cleanup;
  4388. }
  4389. if (mg_stat(conn, gz_path, filep)) {
  4390. if (filep) {
  4391. filep->gzipped = 1;
  4392. *is_found = 1;
  4393. }
  4394. /* Currently gz files can not be scripts. */
  4395. return;
  4396. }
  4397. }
  4398. }
  4399. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4400. /* Support PATH_INFO for CGI scripts. */
  4401. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4402. if (*p == '/') {
  4403. *p = '\0';
  4404. if ((0
  4405. #if !defined(NO_CGI)
  4406. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4407. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4408. filename) > 0
  4409. #endif
  4410. #if defined(USE_LUA)
  4411. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4412. strlen(
  4413. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4414. filename) > 0
  4415. #endif
  4416. #if defined(USE_DUKTAPE)
  4417. || match_prefix(
  4418. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4419. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4420. filename) > 0
  4421. #endif
  4422. ) && mg_stat(conn, filename, filep)) {
  4423. /* Shift PATH_INFO block one character right, e.g.
  4424. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4425. * conn->path_info is pointing to the local variable "path"
  4426. * declared in handle_request(), so PATH_INFO is not valid
  4427. * after handle_request returns. */
  4428. conn->path_info = p + 1;
  4429. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4430. * trailing \0 */
  4431. p[1] = '/';
  4432. *is_script_resource = 1;
  4433. break;
  4434. } else {
  4435. *p = '/';
  4436. }
  4437. }
  4438. }
  4439. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4440. #endif /* !defined(NO_FILES) */
  4441. return;
  4442. #if !defined(NO_FILES)
  4443. /* Reset all outputs */
  4444. interpret_cleanup:
  4445. memset(filep, 0, sizeof(*filep));
  4446. *filename = 0;
  4447. *is_found = 0;
  4448. *is_script_resource = 0;
  4449. *is_websocket_request = 0;
  4450. *is_put_or_delete_request = 0;
  4451. #endif /* !defined(NO_FILES) */
  4452. }
  4453. /* Check whether full request is buffered. Return:
  4454. * -1 if request is malformed
  4455. * 0 if request is not yet fully buffered
  4456. * >0 actual request length, including last \r\n\r\n */
  4457. static int
  4458. get_request_len(const char *buf, int buflen)
  4459. {
  4460. const char *s, *e;
  4461. int len = 0;
  4462. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4463. /* Control characters are not allowed but >=128 is. */
  4464. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4465. && *(const unsigned char *)s < 128) {
  4466. len = -1;
  4467. break; /* [i_a] abort scan as soon as one malformed character is
  4468. * found; */
  4469. /* don't let subsequent \r\n\r\n win us over anyhow */
  4470. } else if (s[0] == '\n' && s[1] == '\n') {
  4471. len = (int)(s - buf) + 2;
  4472. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4473. len = (int)(s - buf) + 3;
  4474. }
  4475. return len;
  4476. }
  4477. #if !defined(NO_CACHING)
  4478. /* Convert month to the month number. Return -1 on error, or month number */
  4479. static int
  4480. get_month_index(const char *s)
  4481. {
  4482. size_t i;
  4483. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4484. if (!strcmp(s, month_names[i])) {
  4485. return (int)i;
  4486. }
  4487. }
  4488. return -1;
  4489. }
  4490. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4491. static time_t
  4492. parse_date_string(const char *datetime)
  4493. {
  4494. char month_str[32] = {0};
  4495. int second, minute, hour, day, month, year;
  4496. time_t result = (time_t)0;
  4497. struct tm tm;
  4498. if ((sscanf(datetime,
  4499. "%d/%3s/%d %d:%d:%d",
  4500. &day,
  4501. month_str,
  4502. &year,
  4503. &hour,
  4504. &minute,
  4505. &second) == 6) || (sscanf(datetime,
  4506. "%d %3s %d %d:%d:%d",
  4507. &day,
  4508. month_str,
  4509. &year,
  4510. &hour,
  4511. &minute,
  4512. &second) == 6)
  4513. || (sscanf(datetime,
  4514. "%*3s, %d %3s %d %d:%d:%d",
  4515. &day,
  4516. month_str,
  4517. &year,
  4518. &hour,
  4519. &minute,
  4520. &second) == 6) || (sscanf(datetime,
  4521. "%d-%3s-%d %d:%d:%d",
  4522. &day,
  4523. month_str,
  4524. &year,
  4525. &hour,
  4526. &minute,
  4527. &second) == 6)) {
  4528. month = get_month_index(month_str);
  4529. if ((month >= 0) && (year >= 1970)) {
  4530. memset(&tm, 0, sizeof(tm));
  4531. tm.tm_year = year - 1900;
  4532. tm.tm_mon = month;
  4533. tm.tm_mday = day;
  4534. tm.tm_hour = hour;
  4535. tm.tm_min = minute;
  4536. tm.tm_sec = second;
  4537. result = timegm(&tm);
  4538. }
  4539. }
  4540. return result;
  4541. }
  4542. #endif /* !NO_CACHING */
  4543. /* Protect against directory disclosure attack by removing '..',
  4544. * excessive '/' and '\' characters */
  4545. static void
  4546. remove_double_dots_and_double_slashes(char *s)
  4547. {
  4548. char *p = s;
  4549. while ((s[0] == '.') && (s[1] == '.')) {
  4550. s++;
  4551. }
  4552. while (*s != '\0') {
  4553. *p++ = *s++;
  4554. if (s[-1] == '/' || s[-1] == '\\') {
  4555. /* Skip all following slashes, backslashes and double-dots */
  4556. while (s[0] != '\0') {
  4557. if (s[0] == '/' || s[0] == '\\') {
  4558. s++;
  4559. } else if (s[0] == '.' && s[1] == '.') {
  4560. s += 2;
  4561. } else {
  4562. break;
  4563. }
  4564. }
  4565. }
  4566. }
  4567. *p = '\0';
  4568. }
  4569. static const struct {
  4570. const char *extension;
  4571. size_t ext_len;
  4572. const char *mime_type;
  4573. } builtin_mime_types[] = {
  4574. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4575. * application types */
  4576. {".doc", 4, "application/msword"},
  4577. {".eps", 4, "application/postscript"},
  4578. {".exe", 4, "application/octet-stream"},
  4579. {".js", 3, "application/javascript"},
  4580. {".json", 5, "application/json"},
  4581. {".pdf", 4, "application/pdf"},
  4582. {".ps", 3, "application/postscript"},
  4583. {".rtf", 4, "application/rtf"},
  4584. {".xhtml", 6, "application/xhtml+xml"},
  4585. {".xsl", 4, "application/xml"},
  4586. {".xslt", 5, "application/xml"},
  4587. /* fonts */
  4588. {".ttf", 4, "application/font-sfnt"},
  4589. {".cff", 4, "application/font-sfnt"},
  4590. {".otf", 4, "application/font-sfnt"},
  4591. {".aat", 4, "application/font-sfnt"},
  4592. {".sil", 4, "application/font-sfnt"},
  4593. {".pfr", 4, "application/font-tdpfr"},
  4594. {".woff", 5, "application/font-woff"},
  4595. /* audio */
  4596. {".mp3", 4, "audio/mpeg"},
  4597. {".oga", 4, "audio/ogg"},
  4598. {".ogg", 4, "audio/ogg"},
  4599. /* image */
  4600. {".gif", 4, "image/gif"},
  4601. {".ief", 4, "image/ief"},
  4602. {".jpeg", 5, "image/jpeg"},
  4603. {".jpg", 4, "image/jpeg"},
  4604. {".jpm", 4, "image/jpm"},
  4605. {".jpx", 4, "image/jpx"},
  4606. {".png", 4, "image/png"},
  4607. {".svg", 4, "image/svg+xml"},
  4608. {".tif", 4, "image/tiff"},
  4609. {".tiff", 5, "image/tiff"},
  4610. /* model */
  4611. {".wrl", 4, "model/vrml"},
  4612. /* text */
  4613. {".css", 4, "text/css"},
  4614. {".csv", 4, "text/csv"},
  4615. {".htm", 4, "text/html"},
  4616. {".html", 5, "text/html"},
  4617. {".sgm", 4, "text/sgml"},
  4618. {".shtm", 5, "text/html"},
  4619. {".shtml", 6, "text/html"},
  4620. {".txt", 4, "text/plain"},
  4621. {".xml", 4, "text/xml"},
  4622. /* video */
  4623. {".mov", 4, "video/quicktime"},
  4624. {".mp4", 4, "video/mp4"},
  4625. {".mpeg", 5, "video/mpeg"},
  4626. {".mpg", 4, "video/mpeg"},
  4627. {".ogv", 4, "video/ogg"},
  4628. {".qt", 3, "video/quicktime"},
  4629. /* not registered types
  4630. * (http://reference.sitepoint.com/html/mime-types-full,
  4631. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4632. {".arj", 4, "application/x-arj-compressed"},
  4633. {".gz", 3, "application/x-gunzip"},
  4634. {".rar", 4, "application/x-arj-compressed"},
  4635. {".swf", 4, "application/x-shockwave-flash"},
  4636. {".tar", 4, "application/x-tar"},
  4637. {".tgz", 4, "application/x-tar-gz"},
  4638. {".torrent", 8, "application/x-bittorrent"},
  4639. {".ppt", 4, "application/x-mspowerpoint"},
  4640. {".xls", 4, "application/x-msexcel"},
  4641. {".zip", 4, "application/x-zip-compressed"},
  4642. {".aac",
  4643. 4,
  4644. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4645. {".aif", 4, "audio/x-aif"},
  4646. {".m3u", 4, "audio/x-mpegurl"},
  4647. {".mid", 4, "audio/x-midi"},
  4648. {".ra", 3, "audio/x-pn-realaudio"},
  4649. {".ram", 4, "audio/x-pn-realaudio"},
  4650. {".wav", 4, "audio/x-wav"},
  4651. {".bmp", 4, "image/bmp"},
  4652. {".ico", 4, "image/x-icon"},
  4653. {".pct", 4, "image/x-pct"},
  4654. {".pict", 5, "image/pict"},
  4655. {".rgb", 4, "image/x-rgb"},
  4656. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4657. {".asf", 4, "video/x-ms-asf"},
  4658. {".avi", 4, "video/x-msvideo"},
  4659. {".m4v", 4, "video/x-m4v"},
  4660. {NULL, 0, NULL}};
  4661. const char *
  4662. mg_get_builtin_mime_type(const char *path)
  4663. {
  4664. const char *ext;
  4665. size_t i, path_len;
  4666. path_len = strlen(path);
  4667. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4668. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4669. if (path_len > builtin_mime_types[i].ext_len
  4670. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4671. return builtin_mime_types[i].mime_type;
  4672. }
  4673. }
  4674. return "text/plain";
  4675. }
  4676. /* Look at the "path" extension and figure what mime type it has.
  4677. * Store mime type in the vector. */
  4678. static void
  4679. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4680. {
  4681. struct vec ext_vec, mime_vec;
  4682. const char *list, *ext;
  4683. size_t path_len;
  4684. path_len = strlen(path);
  4685. if (ctx == NULL || vec == NULL) {
  4686. return;
  4687. }
  4688. /* Scan user-defined mime types first, in case user wants to
  4689. * override default mime types. */
  4690. list = ctx->config[EXTRA_MIME_TYPES];
  4691. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4692. /* ext now points to the path suffix */
  4693. ext = path + path_len - ext_vec.len;
  4694. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4695. *vec = mime_vec;
  4696. return;
  4697. }
  4698. }
  4699. vec->ptr = mg_get_builtin_mime_type(path);
  4700. vec->len = strlen(vec->ptr);
  4701. }
  4702. /* Stringify binary data. Output buffer must be twice as big as input,
  4703. * because each byte takes 2 bytes in string representation */
  4704. static void
  4705. bin2str(char *to, const unsigned char *p, size_t len)
  4706. {
  4707. static const char *hex = "0123456789abcdef";
  4708. for (; len--; p++) {
  4709. *to++ = hex[p[0] >> 4];
  4710. *to++ = hex[p[0] & 0x0f];
  4711. }
  4712. *to = '\0';
  4713. }
  4714. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4715. char *
  4716. mg_md5(char buf[33], ...)
  4717. {
  4718. md5_byte_t hash[16];
  4719. const char *p;
  4720. va_list ap;
  4721. md5_state_t ctx;
  4722. md5_init(&ctx);
  4723. va_start(ap, buf);
  4724. while ((p = va_arg(ap, const char *)) != NULL) {
  4725. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4726. }
  4727. va_end(ap);
  4728. md5_finish(&ctx, hash);
  4729. bin2str(buf, hash, sizeof(hash));
  4730. return buf;
  4731. }
  4732. /* Check the user's password, return 1 if OK */
  4733. static int
  4734. check_password(const char *method,
  4735. const char *ha1,
  4736. const char *uri,
  4737. const char *nonce,
  4738. const char *nc,
  4739. const char *cnonce,
  4740. const char *qop,
  4741. const char *response)
  4742. {
  4743. char ha2[32 + 1], expected_response[32 + 1];
  4744. /* Some of the parameters may be NULL */
  4745. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4746. || qop == NULL
  4747. || response == NULL) {
  4748. return 0;
  4749. }
  4750. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4751. if (strlen(response) != 32) {
  4752. return 0;
  4753. }
  4754. mg_md5(ha2, method, ":", uri, NULL);
  4755. mg_md5(expected_response,
  4756. ha1,
  4757. ":",
  4758. nonce,
  4759. ":",
  4760. nc,
  4761. ":",
  4762. cnonce,
  4763. ":",
  4764. qop,
  4765. ":",
  4766. ha2,
  4767. NULL);
  4768. return mg_strcasecmp(response, expected_response) == 0;
  4769. }
  4770. /* Use the global passwords file, if specified by auth_gpass option,
  4771. * or search for .htpasswd in the requested directory. */
  4772. static void
  4773. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4774. {
  4775. if (conn != NULL && conn->ctx != NULL) {
  4776. char name[PATH_MAX];
  4777. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4778. struct file file = STRUCT_FILE_INITIALIZER;
  4779. int truncated;
  4780. if (gpass != NULL) {
  4781. /* Use global passwords file */
  4782. if (!mg_fopen(conn, gpass, "r", filep)) {
  4783. #ifdef DEBUG
  4784. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4785. #endif
  4786. }
  4787. /* Important: using local struct file to test path for is_directory
  4788. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4789. * was opened. */
  4790. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4791. mg_snprintf(conn,
  4792. &truncated,
  4793. name,
  4794. sizeof(name),
  4795. "%s/%s",
  4796. path,
  4797. PASSWORDS_FILE_NAME);
  4798. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4799. #ifdef DEBUG
  4800. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4801. #endif
  4802. }
  4803. } else {
  4804. /* Try to find .htpasswd in requested directory. */
  4805. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4806. if (e[0] == '/') {
  4807. break;
  4808. }
  4809. }
  4810. mg_snprintf(conn,
  4811. &truncated,
  4812. name,
  4813. sizeof(name),
  4814. "%.*s/%s",
  4815. (int)(e - p),
  4816. p,
  4817. PASSWORDS_FILE_NAME);
  4818. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4819. #ifdef DEBUG
  4820. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4821. #endif
  4822. }
  4823. }
  4824. }
  4825. }
  4826. /* Parsed Authorization header */
  4827. struct ah {
  4828. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4829. };
  4830. /* Return 1 on success. Always initializes the ah structure. */
  4831. static int
  4832. parse_auth_header(struct mg_connection *conn,
  4833. char *buf,
  4834. size_t buf_size,
  4835. struct ah *ah)
  4836. {
  4837. char *name, *value, *s;
  4838. const char *auth_header;
  4839. uint64_t nonce;
  4840. if (!ah || !conn) {
  4841. return 0;
  4842. }
  4843. (void)memset(ah, 0, sizeof(*ah));
  4844. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4845. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4846. return 0;
  4847. }
  4848. /* Make modifiable copy of the auth header */
  4849. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4850. s = buf;
  4851. /* Parse authorization header */
  4852. for (;;) {
  4853. /* Gobble initial spaces */
  4854. while (isspace(*(unsigned char *)s)) {
  4855. s++;
  4856. }
  4857. name = skip_quoted(&s, "=", " ", 0);
  4858. /* Value is either quote-delimited, or ends at first comma or space. */
  4859. if (s[0] == '\"') {
  4860. s++;
  4861. value = skip_quoted(&s, "\"", " ", '\\');
  4862. if (s[0] == ',') {
  4863. s++;
  4864. }
  4865. } else {
  4866. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4867. * spaces */
  4868. }
  4869. if (*name == '\0') {
  4870. break;
  4871. }
  4872. if (!strcmp(name, "username")) {
  4873. ah->user = value;
  4874. } else if (!strcmp(name, "cnonce")) {
  4875. ah->cnonce = value;
  4876. } else if (!strcmp(name, "response")) {
  4877. ah->response = value;
  4878. } else if (!strcmp(name, "uri")) {
  4879. ah->uri = value;
  4880. } else if (!strcmp(name, "qop")) {
  4881. ah->qop = value;
  4882. } else if (!strcmp(name, "nc")) {
  4883. ah->nc = value;
  4884. } else if (!strcmp(name, "nonce")) {
  4885. ah->nonce = value;
  4886. }
  4887. }
  4888. #ifndef NO_NONCE_CHECK
  4889. /* Read the nonce from the response. */
  4890. if (ah->nonce == NULL) {
  4891. return 0;
  4892. }
  4893. s = NULL;
  4894. nonce = strtoull(ah->nonce, &s, 10);
  4895. if ((s == NULL) || (*s != 0)) {
  4896. return 0;
  4897. }
  4898. /* Convert the nonce from the client to a number. */
  4899. nonce ^= conn->ctx->auth_nonce_mask;
  4900. /* The converted number corresponds to the time the nounce has been
  4901. * created. This should not be earlier than the server start. */
  4902. /* Server side nonce check is valuable in all situations but one:
  4903. * if the server restarts frequently, but the client should not see
  4904. * that, so the server should accept nonces from previous starts. */
  4905. /* However, the reasonable default is to not accept a nonce from a
  4906. * previous start, so if anyone changed the access rights between
  4907. * two restarts, a new login is required. */
  4908. if (nonce < (uint64_t)conn->ctx->start_time) {
  4909. /* nonce is from a previous start of the server and no longer valid
  4910. * (replay attack?) */
  4911. return 0;
  4912. }
  4913. /* Check if the nonce is too high, so it has not (yet) been used by the
  4914. * server. */
  4915. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4916. return 0;
  4917. }
  4918. #else
  4919. (void)nonce;
  4920. #endif
  4921. /* CGI needs it as REMOTE_USER */
  4922. if (ah->user != NULL) {
  4923. conn->request_info.remote_user = mg_strdup(ah->user);
  4924. } else {
  4925. return 0;
  4926. }
  4927. return 1;
  4928. }
  4929. static const char *
  4930. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4931. {
  4932. const char *eof;
  4933. size_t len;
  4934. const char *memend;
  4935. if (!filep) {
  4936. return NULL;
  4937. }
  4938. if (filep->membuf != NULL && *p != NULL) {
  4939. memend = (const char *)&filep->membuf[filep->size];
  4940. /* Search for \n from p till the end of stream */
  4941. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4942. if (eof != NULL) {
  4943. eof += 1; /* Include \n */
  4944. } else {
  4945. eof = memend; /* Copy remaining data */
  4946. }
  4947. len =
  4948. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  4949. memcpy(buf, *p, len);
  4950. buf[len] = '\0';
  4951. *p += len;
  4952. return len ? eof : NULL;
  4953. } else if (filep->fp != NULL) {
  4954. return fgets(buf, (int)size, filep->fp);
  4955. } else {
  4956. return NULL;
  4957. }
  4958. }
  4959. struct read_auth_file_struct {
  4960. struct mg_connection *conn;
  4961. struct ah ah;
  4962. char *domain;
  4963. char buf[256 + 256 + 40];
  4964. char *f_user;
  4965. char *f_domain;
  4966. char *f_ha1;
  4967. };
  4968. static int
  4969. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4970. {
  4971. char *p;
  4972. int is_authorized = 0;
  4973. struct file fp;
  4974. size_t l;
  4975. if (!filep || !workdata) {
  4976. return 0;
  4977. }
  4978. /* Loop over passwords file */
  4979. p = (char *)filep->membuf;
  4980. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4981. l = strlen(workdata->buf);
  4982. while (l > 0) {
  4983. if (isspace(workdata->buf[l - 1])
  4984. || iscntrl(workdata->buf[l - 1])) {
  4985. l--;
  4986. workdata->buf[l] = 0;
  4987. } else
  4988. break;
  4989. }
  4990. if (l < 1) {
  4991. continue;
  4992. }
  4993. workdata->f_user = workdata->buf;
  4994. if (workdata->f_user[0] == ':') {
  4995. /* user names may not contain a ':' and may not be empty,
  4996. * so lines starting with ':' may be used for a special purpose */
  4997. if (workdata->f_user[1] == '#') {
  4998. /* :# is a comment */
  4999. continue;
  5000. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5001. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  5002. is_authorized = read_auth_file(&fp, workdata);
  5003. mg_fclose(&fp);
  5004. } else {
  5005. mg_cry(workdata->conn,
  5006. "%s: cannot open authorization file: %s",
  5007. __func__,
  5008. workdata->buf);
  5009. }
  5010. continue;
  5011. }
  5012. /* everything is invalid for the moment (might change in the
  5013. * future) */
  5014. mg_cry(workdata->conn,
  5015. "%s: syntax error in authorization file: %s",
  5016. __func__,
  5017. workdata->buf);
  5018. continue;
  5019. }
  5020. workdata->f_domain = strchr(workdata->f_user, ':');
  5021. if (workdata->f_domain == NULL) {
  5022. mg_cry(workdata->conn,
  5023. "%s: syntax error in authorization file: %s",
  5024. __func__,
  5025. workdata->buf);
  5026. continue;
  5027. }
  5028. *(workdata->f_domain) = 0;
  5029. (workdata->f_domain)++;
  5030. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5031. if (workdata->f_ha1 == NULL) {
  5032. mg_cry(workdata->conn,
  5033. "%s: syntax error in authorization file: %s",
  5034. __func__,
  5035. workdata->buf);
  5036. continue;
  5037. }
  5038. *(workdata->f_ha1) = 0;
  5039. (workdata->f_ha1)++;
  5040. if (!strcmp(workdata->ah.user, workdata->f_user)
  5041. && !strcmp(workdata->domain, workdata->f_domain)) {
  5042. return check_password(workdata->conn->request_info.request_method,
  5043. workdata->f_ha1,
  5044. workdata->ah.uri,
  5045. workdata->ah.nonce,
  5046. workdata->ah.nc,
  5047. workdata->ah.cnonce,
  5048. workdata->ah.qop,
  5049. workdata->ah.response);
  5050. }
  5051. }
  5052. return is_authorized;
  5053. }
  5054. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5055. static int
  5056. authorize(struct mg_connection *conn, struct file *filep)
  5057. {
  5058. struct read_auth_file_struct workdata;
  5059. char buf[MG_BUF_LEN];
  5060. if (!conn || !conn->ctx) {
  5061. return 0;
  5062. }
  5063. memset(&workdata, 0, sizeof(workdata));
  5064. workdata.conn = conn;
  5065. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5066. return 0;
  5067. }
  5068. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5069. return read_auth_file(filep, &workdata);
  5070. }
  5071. /* Return 1 if request is authorised, 0 otherwise. */
  5072. static int
  5073. check_authorization(struct mg_connection *conn, const char *path)
  5074. {
  5075. char fname[PATH_MAX];
  5076. struct vec uri_vec, filename_vec;
  5077. const char *list;
  5078. struct file file = STRUCT_FILE_INITIALIZER;
  5079. int authorized = 1, truncated;
  5080. if (!conn || !conn->ctx) {
  5081. return 0;
  5082. }
  5083. list = conn->ctx->config[PROTECT_URI];
  5084. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5085. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5086. mg_snprintf(conn,
  5087. &truncated,
  5088. fname,
  5089. sizeof(fname),
  5090. "%.*s",
  5091. (int)filename_vec.len,
  5092. filename_vec.ptr);
  5093. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  5094. mg_cry(conn,
  5095. "%s: cannot open %s: %s",
  5096. __func__,
  5097. fname,
  5098. strerror(errno));
  5099. }
  5100. break;
  5101. }
  5102. }
  5103. if (!is_file_opened(&file)) {
  5104. open_auth_file(conn, path, &file);
  5105. }
  5106. if (is_file_opened(&file)) {
  5107. authorized = authorize(conn, &file);
  5108. mg_fclose(&file);
  5109. }
  5110. return authorized;
  5111. }
  5112. static void
  5113. send_authorization_request(struct mg_connection *conn)
  5114. {
  5115. char date[64];
  5116. time_t curtime = time(NULL);
  5117. if (conn && conn->ctx) {
  5118. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5119. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5120. nonce += conn->ctx->nonce_count;
  5121. ++conn->ctx->nonce_count;
  5122. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5123. nonce ^= conn->ctx->auth_nonce_mask;
  5124. conn->status_code = 401;
  5125. conn->must_close = 1;
  5126. gmt_time_string(date, sizeof(date), &curtime);
  5127. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5128. send_no_cache_header(conn);
  5129. mg_printf(conn,
  5130. "Date: %s\r\n"
  5131. "Connection: %s\r\n"
  5132. "Content-Length: 0\r\n"
  5133. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5134. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5135. date,
  5136. suggest_connection_header(conn),
  5137. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5138. nonce);
  5139. }
  5140. }
  5141. #if !defined(NO_FILES)
  5142. static int
  5143. is_authorized_for_put(struct mg_connection *conn)
  5144. {
  5145. if (conn) {
  5146. struct file file = STRUCT_FILE_INITIALIZER;
  5147. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5148. int ret = 0;
  5149. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  5150. ret = authorize(conn, &file);
  5151. mg_fclose(&file);
  5152. }
  5153. return ret;
  5154. }
  5155. return 0;
  5156. }
  5157. #endif
  5158. int
  5159. mg_modify_passwords_file(const char *fname,
  5160. const char *domain,
  5161. const char *user,
  5162. const char *pass)
  5163. {
  5164. int found, i;
  5165. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5166. FILE *fp, *fp2;
  5167. found = 0;
  5168. fp = fp2 = NULL;
  5169. /* Regard empty password as no password - remove user record. */
  5170. if (pass != NULL && pass[0] == '\0') {
  5171. pass = NULL;
  5172. }
  5173. /* Other arguments must not be empty */
  5174. if (fname == NULL || domain == NULL || user == NULL) {
  5175. return 0;
  5176. }
  5177. /* Using the given file format, user name and domain must not contain ':'
  5178. */
  5179. if (strchr(user, ':') != NULL) {
  5180. return 0;
  5181. }
  5182. if (strchr(domain, ':') != NULL) {
  5183. return 0;
  5184. }
  5185. /* Do not allow control characters like newline in user name and domain.
  5186. * Do not allow excessively long names either. */
  5187. for (i = 0; i < 255 && user[i] != 0; i++) {
  5188. if (iscntrl(user[i])) {
  5189. return 0;
  5190. }
  5191. }
  5192. if (user[i]) {
  5193. return 0;
  5194. }
  5195. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5196. if (iscntrl(domain[i])) {
  5197. return 0;
  5198. }
  5199. }
  5200. if (domain[i]) {
  5201. return 0;
  5202. }
  5203. /* The maximum length of the path to the password file is limited */
  5204. if ((strlen(fname) + 4) >= PATH_MAX) {
  5205. return 0;
  5206. }
  5207. /* Create a temporary file name. Length has been checked before. */
  5208. strcpy(tmp, fname);
  5209. strcat(tmp, ".tmp");
  5210. /* Create the file if does not exist */
  5211. /* Use of fopen here is OK, since fname is only ASCII */
  5212. if ((fp = fopen(fname, "a+")) != NULL) {
  5213. (void)fclose(fp);
  5214. }
  5215. /* Open the given file and temporary file */
  5216. if ((fp = fopen(fname, "r")) == NULL) {
  5217. return 0;
  5218. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5219. fclose(fp);
  5220. return 0;
  5221. }
  5222. /* Copy the stuff to temporary file */
  5223. while (fgets(line, sizeof(line), fp) != NULL) {
  5224. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5225. continue;
  5226. }
  5227. u[255] = 0;
  5228. d[255] = 0;
  5229. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5230. found++;
  5231. if (pass != NULL) {
  5232. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5233. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5234. }
  5235. } else {
  5236. fprintf(fp2, "%s", line);
  5237. }
  5238. }
  5239. /* If new user, just add it */
  5240. if (!found && pass != NULL) {
  5241. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5242. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5243. }
  5244. /* Close files */
  5245. fclose(fp);
  5246. fclose(fp2);
  5247. /* Put the temp file in place of real file */
  5248. IGNORE_UNUSED_RESULT(remove(fname));
  5249. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5250. return 1;
  5251. }
  5252. static int
  5253. is_valid_port(unsigned long port)
  5254. {
  5255. return port < 0xffff;
  5256. }
  5257. static int
  5258. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5259. {
  5260. struct addrinfo hints, *res, *ressave;
  5261. int func_ret = 0;
  5262. int gai_ret;
  5263. memset(&hints, 0, sizeof(struct addrinfo));
  5264. hints.ai_family = af;
  5265. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5266. if (gai_ret != 0) {
  5267. /* gai_strerror could be used to convert gai_ret to a string */
  5268. /* POSIX return values: see
  5269. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5270. */
  5271. /* Windows return values: see
  5272. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5273. */
  5274. return 0;
  5275. }
  5276. ressave = res;
  5277. while (res) {
  5278. if (dstlen >= res->ai_addrlen) {
  5279. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5280. func_ret = 1;
  5281. }
  5282. res = res->ai_next;
  5283. }
  5284. freeaddrinfo(ressave);
  5285. return func_ret;
  5286. }
  5287. static int
  5288. connect_socket(struct mg_context *ctx /* may be NULL */,
  5289. const char *host,
  5290. int port,
  5291. int use_ssl,
  5292. char *ebuf,
  5293. size_t ebuf_len,
  5294. SOCKET *sock /* output: socket, must not be NULL */,
  5295. union usa *sa /* output: socket address, must not be NULL */
  5296. )
  5297. {
  5298. int ip_ver = 0;
  5299. *sock = INVALID_SOCKET;
  5300. memset(sa, 0, sizeof(*sa));
  5301. if (ebuf_len > 0) {
  5302. *ebuf = 0;
  5303. }
  5304. if (host == NULL) {
  5305. mg_snprintf(NULL,
  5306. NULL, /* No truncation check for ebuf */
  5307. ebuf,
  5308. ebuf_len,
  5309. "%s",
  5310. "NULL host");
  5311. return 0;
  5312. }
  5313. if (port < 0 || !is_valid_port((unsigned)port)) {
  5314. mg_snprintf(NULL,
  5315. NULL, /* No truncation check for ebuf */
  5316. ebuf,
  5317. ebuf_len,
  5318. "%s",
  5319. "invalid port");
  5320. return 0;
  5321. }
  5322. #if !defined(NO_SSL)
  5323. if (use_ssl && (SSLv23_client_method == NULL)) {
  5324. mg_snprintf(NULL,
  5325. NULL, /* No truncation check for ebuf */
  5326. ebuf,
  5327. ebuf_len,
  5328. "%s",
  5329. "SSL is not initialized");
  5330. return 0;
  5331. }
  5332. #else
  5333. (void)use_ssl;
  5334. #endif
  5335. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5336. sa->sin.sin_port = htons((uint16_t)port);
  5337. ip_ver = 4;
  5338. #ifdef USE_IPV6
  5339. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5340. sa->sin6.sin6_port = htons((uint16_t)port);
  5341. ip_ver = 6;
  5342. } else if (host[0] == '[') {
  5343. /* While getaddrinfo on Windows will work with [::1],
  5344. * getaddrinfo on Linux only works with ::1 (without []). */
  5345. size_t l = strlen(host + 1);
  5346. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5347. if (h) {
  5348. h[l - 1] = 0;
  5349. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5350. sa->sin6.sin6_port = htons((uint16_t)port);
  5351. ip_ver = 6;
  5352. }
  5353. mg_free(h);
  5354. }
  5355. #endif
  5356. }
  5357. if (ip_ver == 0) {
  5358. mg_snprintf(NULL,
  5359. NULL, /* No truncation check for ebuf */
  5360. ebuf,
  5361. ebuf_len,
  5362. "%s",
  5363. "host not found");
  5364. return 0;
  5365. }
  5366. if (ip_ver == 4) {
  5367. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5368. }
  5369. #ifdef USE_IPV6
  5370. else if (ip_ver == 6) {
  5371. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5372. }
  5373. #endif
  5374. if (*sock == INVALID_SOCKET) {
  5375. mg_snprintf(NULL,
  5376. NULL, /* No truncation check for ebuf */
  5377. ebuf,
  5378. ebuf_len,
  5379. "socket(): %s",
  5380. strerror(ERRNO));
  5381. return 0;
  5382. }
  5383. set_close_on_exec(*sock, fc(ctx));
  5384. if ((ip_ver == 4)
  5385. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5386. == 0)) {
  5387. /* connected with IPv4 */
  5388. return 1;
  5389. }
  5390. #ifdef USE_IPV6
  5391. if ((ip_ver == 6)
  5392. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5393. == 0)) {
  5394. /* connected with IPv6 */
  5395. return 1;
  5396. }
  5397. #endif
  5398. /* Not connected */
  5399. mg_snprintf(NULL,
  5400. NULL, /* No truncation check for ebuf */
  5401. ebuf,
  5402. ebuf_len,
  5403. "connect(%s:%d): %s",
  5404. host,
  5405. port,
  5406. strerror(ERRNO));
  5407. closesocket(*sock);
  5408. *sock = INVALID_SOCKET;
  5409. return 0;
  5410. }
  5411. int
  5412. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5413. {
  5414. static const char *dont_escape = "._-$,;~()";
  5415. static const char *hex = "0123456789abcdef";
  5416. char *pos = dst;
  5417. const char *end = dst + dst_len - 1;
  5418. for (; *src != '\0' && pos < end; src++, pos++) {
  5419. if (isalnum(*(const unsigned char *)src)
  5420. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5421. *pos = *src;
  5422. } else if (pos + 2 < end) {
  5423. pos[0] = '%';
  5424. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5425. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5426. pos += 2;
  5427. } else {
  5428. break;
  5429. }
  5430. }
  5431. *pos = '\0';
  5432. return (*src == '\0') ? (int)(pos - dst) : -1;
  5433. }
  5434. static void
  5435. print_dir_entry(struct de *de)
  5436. {
  5437. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5438. struct tm *tm;
  5439. if (de->file.is_directory) {
  5440. mg_snprintf(de->conn,
  5441. NULL, /* Buffer is big enough */
  5442. size,
  5443. sizeof(size),
  5444. "%s",
  5445. "[DIRECTORY]");
  5446. } else {
  5447. /* We use (signed) cast below because MSVC 6 compiler cannot
  5448. * convert unsigned __int64 to double. Sigh. */
  5449. if (de->file.size < 1024) {
  5450. mg_snprintf(de->conn,
  5451. NULL, /* Buffer is big enough */
  5452. size,
  5453. sizeof(size),
  5454. "%d",
  5455. (int)de->file.size);
  5456. } else if (de->file.size < 0x100000) {
  5457. mg_snprintf(de->conn,
  5458. NULL, /* Buffer is big enough */
  5459. size,
  5460. sizeof(size),
  5461. "%.1fk",
  5462. (double)de->file.size / 1024.0);
  5463. } else if (de->file.size < 0x40000000) {
  5464. mg_snprintf(de->conn,
  5465. NULL, /* Buffer is big enough */
  5466. size,
  5467. sizeof(size),
  5468. "%.1fM",
  5469. (double)de->file.size / 1048576);
  5470. } else {
  5471. mg_snprintf(de->conn,
  5472. NULL, /* Buffer is big enough */
  5473. size,
  5474. sizeof(size),
  5475. "%.1fG",
  5476. (double)de->file.size / 1073741824);
  5477. }
  5478. }
  5479. /* Note: mg_snprintf will not cause a buffer overflow above.
  5480. * So, string truncation checks are not required here. */
  5481. tm = localtime(&de->file.last_modified);
  5482. if (tm != NULL) {
  5483. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5484. } else {
  5485. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5486. mod[sizeof(mod) - 1] = '\0';
  5487. }
  5488. mg_url_encode(de->file_name, href, sizeof(href));
  5489. de->conn->num_bytes_sent +=
  5490. mg_printf(de->conn,
  5491. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5492. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5493. de->conn->request_info.local_uri,
  5494. href,
  5495. de->file.is_directory ? "/" : "",
  5496. de->file_name,
  5497. de->file.is_directory ? "/" : "",
  5498. mod,
  5499. size);
  5500. }
  5501. /* This function is called from send_directory() and used for
  5502. * sorting directory entries by size, or name, or modification time.
  5503. * On windows, __cdecl specification is needed in case if project is built
  5504. * with __stdcall convention. qsort always requires __cdels callback. */
  5505. static int WINCDECL
  5506. compare_dir_entries(const void *p1, const void *p2)
  5507. {
  5508. if (p1 && p2) {
  5509. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5510. const char *query_string = a->conn->request_info.query_string;
  5511. int cmp_result = 0;
  5512. if (query_string == NULL) {
  5513. query_string = "na";
  5514. }
  5515. if (a->file.is_directory && !b->file.is_directory) {
  5516. return -1; /* Always put directories on top */
  5517. } else if (!a->file.is_directory && b->file.is_directory) {
  5518. return 1; /* Always put directories on top */
  5519. } else if (*query_string == 'n') {
  5520. cmp_result = strcmp(a->file_name, b->file_name);
  5521. } else if (*query_string == 's') {
  5522. cmp_result = (a->file.size == b->file.size)
  5523. ? 0
  5524. : ((a->file.size > b->file.size) ? 1 : -1);
  5525. } else if (*query_string == 'd') {
  5526. cmp_result =
  5527. (a->file.last_modified == b->file.last_modified)
  5528. ? 0
  5529. : ((a->file.last_modified > b->file.last_modified) ? 1
  5530. : -1);
  5531. }
  5532. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5533. }
  5534. return 0;
  5535. }
  5536. static int
  5537. must_hide_file(struct mg_connection *conn, const char *path)
  5538. {
  5539. if (conn && conn->ctx) {
  5540. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5541. const char *pattern = conn->ctx->config[HIDE_FILES];
  5542. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5543. || (pattern != NULL
  5544. && match_prefix(pattern, strlen(pattern), path) > 0);
  5545. }
  5546. return 0;
  5547. }
  5548. static int
  5549. scan_directory(struct mg_connection *conn,
  5550. const char *dir,
  5551. void *data,
  5552. void (*cb)(struct de *, void *))
  5553. {
  5554. char path[PATH_MAX];
  5555. struct dirent *dp;
  5556. DIR *dirp;
  5557. struct de de;
  5558. int truncated;
  5559. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5560. return 0;
  5561. } else {
  5562. de.conn = conn;
  5563. while ((dp = mg_readdir(dirp)) != NULL) {
  5564. /* Do not show current dir and hidden files */
  5565. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5566. || must_hide_file(conn, dp->d_name)) {
  5567. continue;
  5568. }
  5569. mg_snprintf(
  5570. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5571. /* If we don't memset stat structure to zero, mtime will have
  5572. * garbage and strftime() will segfault later on in
  5573. * print_dir_entry(). memset is required only if mg_stat()
  5574. * fails. For more details, see
  5575. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5576. memset(&de.file, 0, sizeof(de.file));
  5577. if (truncated) {
  5578. /* If the path is not complete, skip processing. */
  5579. continue;
  5580. }
  5581. if (!mg_stat(conn, path, &de.file)) {
  5582. mg_cry(conn,
  5583. "%s: mg_stat(%s) failed: %s",
  5584. __func__,
  5585. path,
  5586. strerror(ERRNO));
  5587. }
  5588. de.file_name = dp->d_name;
  5589. cb(&de, data);
  5590. }
  5591. (void)mg_closedir(dirp);
  5592. }
  5593. return 1;
  5594. }
  5595. #if !defined(NO_FILES)
  5596. static int
  5597. remove_directory(struct mg_connection *conn, const char *dir)
  5598. {
  5599. char path[PATH_MAX];
  5600. struct dirent *dp;
  5601. DIR *dirp;
  5602. struct de de;
  5603. int truncated;
  5604. int ok = 1;
  5605. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5606. return 0;
  5607. } else {
  5608. de.conn = conn;
  5609. while ((dp = mg_readdir(dirp)) != NULL) {
  5610. /* Do not show current dir (but show hidden files as they will
  5611. * also be removed) */
  5612. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5613. continue;
  5614. }
  5615. mg_snprintf(
  5616. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5617. /* If we don't memset stat structure to zero, mtime will have
  5618. * garbage and strftime() will segfault later on in
  5619. * print_dir_entry(). memset is required only if mg_stat()
  5620. * fails. For more details, see
  5621. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5622. memset(&de.file, 0, sizeof(de.file));
  5623. if (truncated) {
  5624. /* Do not delete anything shorter */
  5625. ok = 0;
  5626. continue;
  5627. }
  5628. if (!mg_stat(conn, path, &de.file)) {
  5629. mg_cry(conn,
  5630. "%s: mg_stat(%s) failed: %s",
  5631. __func__,
  5632. path,
  5633. strerror(ERRNO));
  5634. ok = 0;
  5635. }
  5636. if (de.file.membuf == NULL) {
  5637. /* file is not in memory */
  5638. if (de.file.is_directory) {
  5639. if (remove_directory(conn, path) == 0) {
  5640. ok = 0;
  5641. }
  5642. } else {
  5643. if (mg_remove(conn, path) == 0) {
  5644. ok = 0;
  5645. }
  5646. }
  5647. } else {
  5648. /* file is in memory. It can not be deleted. */
  5649. ok = 0;
  5650. }
  5651. }
  5652. (void)mg_closedir(dirp);
  5653. IGNORE_UNUSED_RESULT(rmdir(dir));
  5654. }
  5655. return ok;
  5656. }
  5657. #endif
  5658. struct dir_scan_data {
  5659. struct de *entries;
  5660. unsigned int num_entries;
  5661. unsigned int arr_size;
  5662. };
  5663. /* Behaves like realloc(), but frees original pointer on failure */
  5664. static void *
  5665. realloc2(void *ptr, size_t size)
  5666. {
  5667. void *new_ptr = mg_realloc(ptr, size);
  5668. if (new_ptr == NULL) {
  5669. mg_free(ptr);
  5670. }
  5671. return new_ptr;
  5672. }
  5673. static void
  5674. dir_scan_callback(struct de *de, void *data)
  5675. {
  5676. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5677. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5678. dsd->arr_size *= 2;
  5679. dsd->entries =
  5680. (struct de *)realloc2(dsd->entries,
  5681. dsd->arr_size * sizeof(dsd->entries[0]));
  5682. }
  5683. if (dsd->entries == NULL) {
  5684. /* TODO(lsm, low): propagate an error to the caller */
  5685. dsd->num_entries = 0;
  5686. } else {
  5687. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5688. dsd->entries[dsd->num_entries].file = de->file;
  5689. dsd->entries[dsd->num_entries].conn = de->conn;
  5690. dsd->num_entries++;
  5691. }
  5692. }
  5693. static void
  5694. handle_directory_request(struct mg_connection *conn, const char *dir)
  5695. {
  5696. unsigned int i;
  5697. int sort_direction;
  5698. struct dir_scan_data data = {NULL, 0, 128};
  5699. char date[64];
  5700. time_t curtime = time(NULL);
  5701. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5702. send_http_error(conn,
  5703. 500,
  5704. "Error: Cannot open directory\nopendir(%s): %s",
  5705. dir,
  5706. strerror(ERRNO));
  5707. return;
  5708. }
  5709. gmt_time_string(date, sizeof(date), &curtime);
  5710. if (!conn) {
  5711. return;
  5712. }
  5713. sort_direction = ((conn->request_info.query_string != NULL)
  5714. && (conn->request_info.query_string[1] == 'd'))
  5715. ? 'a'
  5716. : 'd';
  5717. conn->must_close = 1;
  5718. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5719. send_static_cache_header(conn);
  5720. mg_printf(conn,
  5721. "Date: %s\r\n"
  5722. "Connection: close\r\n"
  5723. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5724. date);
  5725. conn->num_bytes_sent +=
  5726. mg_printf(conn,
  5727. "<html><head><title>Index of %s</title>"
  5728. "<style>th {text-align: left;}</style></head>"
  5729. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5730. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5731. "<th><a href=\"?d%c\">Modified</a></th>"
  5732. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5733. "<tr><td colspan=\"3\"><hr></td></tr>",
  5734. conn->request_info.local_uri,
  5735. conn->request_info.local_uri,
  5736. sort_direction,
  5737. sort_direction,
  5738. sort_direction);
  5739. /* Print first entry - link to a parent directory */
  5740. conn->num_bytes_sent +=
  5741. mg_printf(conn,
  5742. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5743. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5744. conn->request_info.local_uri,
  5745. "..",
  5746. "Parent directory",
  5747. "-",
  5748. "-");
  5749. /* Sort and print directory entries */
  5750. if (data.entries != NULL) {
  5751. qsort(data.entries,
  5752. (size_t)data.num_entries,
  5753. sizeof(data.entries[0]),
  5754. compare_dir_entries);
  5755. for (i = 0; i < data.num_entries; i++) {
  5756. print_dir_entry(&data.entries[i]);
  5757. mg_free(data.entries[i].file_name);
  5758. }
  5759. mg_free(data.entries);
  5760. }
  5761. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5762. conn->status_code = 200;
  5763. }
  5764. /* Send len bytes from the opened file to the client. */
  5765. static void
  5766. send_file_data(struct mg_connection *conn,
  5767. struct file *filep,
  5768. int64_t offset,
  5769. int64_t len)
  5770. {
  5771. char buf[MG_BUF_LEN];
  5772. int to_read, num_read, num_written;
  5773. int64_t size;
  5774. if (!filep || !conn) {
  5775. return;
  5776. }
  5777. /* Sanity check the offset */
  5778. size = (filep->size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->size);
  5779. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  5780. if (len > 0 && filep->membuf != NULL && size > 0) {
  5781. /* file stored in memory */
  5782. if (len > size - offset) {
  5783. len = size - offset;
  5784. }
  5785. mg_write(conn, filep->membuf + offset, (size_t)len);
  5786. } else if (len > 0 && filep->fp != NULL) {
  5787. /* file stored on disk */
  5788. #if defined(__linux__)
  5789. /* sendfile is only available for Linux */
  5790. if ((conn->ssl == 0) && (conn->throttle == 0)
  5791. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  5792. "yes"))) {
  5793. off_t sf_offs = (off_t)offset;
  5794. ssize_t sf_sent;
  5795. int sf_file = fileno(filep->fp);
  5796. int loop_cnt = 0;
  5797. do {
  5798. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5799. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5800. size_t sf_tosend =
  5801. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5802. sf_sent =
  5803. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5804. if (sf_sent > 0) {
  5805. conn->num_bytes_sent += sf_sent;
  5806. len -= sf_sent;
  5807. offset += sf_sent;
  5808. } else if (loop_cnt == 0) {
  5809. /* This file can not be sent using sendfile.
  5810. * This might be the case for pseudo-files in the
  5811. * /sys/ and /proc/ file system.
  5812. * Use the regular user mode copy code instead. */
  5813. break;
  5814. } else if (sf_sent == 0) {
  5815. /* No error, but 0 bytes sent. May be EOF? */
  5816. return;
  5817. }
  5818. loop_cnt++;
  5819. } while ((len > 0) && (sf_sent >= 0));
  5820. if (sf_sent > 0) {
  5821. return; /* OK */
  5822. }
  5823. /* sf_sent<0 means error, thus fall back to the classic way */
  5824. /* This is always the case, if sf_file is not a "normal" file,
  5825. * e.g., for sending data from the output of a CGI process. */
  5826. offset = (int64_t)sf_offs;
  5827. }
  5828. #endif
  5829. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5830. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5831. send_http_error(
  5832. conn,
  5833. 500,
  5834. "%s",
  5835. "Error: Unable to access file at requested position.");
  5836. } else {
  5837. while (len > 0) {
  5838. /* Calculate how much to read from the file in the buffer */
  5839. to_read = sizeof(buf);
  5840. if ((int64_t)to_read > len) {
  5841. to_read = (int)len;
  5842. }
  5843. /* Read from file, exit the loop on error */
  5844. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5845. <= 0) {
  5846. break;
  5847. }
  5848. /* Send read bytes to the client, exit the loop on error */
  5849. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5850. != num_read) {
  5851. break;
  5852. }
  5853. /* Both read and were successful, adjust counters */
  5854. conn->num_bytes_sent += num_written;
  5855. len -= num_written;
  5856. }
  5857. }
  5858. }
  5859. }
  5860. static int
  5861. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5862. {
  5863. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5864. }
  5865. static void
  5866. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5867. {
  5868. if (filep != NULL && buf != NULL) {
  5869. mg_snprintf(NULL,
  5870. NULL, /* All calls to construct_etag use 64 byte buffer */
  5871. buf,
  5872. buf_len,
  5873. "\"%lx.%" INT64_FMT "\"",
  5874. (unsigned long)filep->last_modified,
  5875. filep->size);
  5876. }
  5877. }
  5878. static void
  5879. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5880. {
  5881. if (filep != NULL && filep->fp != NULL) {
  5882. #ifdef _WIN32
  5883. (void)conn; /* Unused. */
  5884. #else
  5885. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5886. mg_cry(conn,
  5887. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5888. __func__,
  5889. strerror(ERRNO));
  5890. }
  5891. #endif
  5892. }
  5893. }
  5894. static void
  5895. handle_static_file_request(struct mg_connection *conn,
  5896. const char *path,
  5897. struct file *filep,
  5898. const char *mime_type,
  5899. const char *additional_headers)
  5900. {
  5901. char date[64], lm[64], etag[64];
  5902. char range[128]; /* large enough, so there will be no overflow */
  5903. const char *msg = "OK", *hdr;
  5904. time_t curtime = time(NULL);
  5905. int64_t cl, r1, r2;
  5906. struct vec mime_vec;
  5907. int n, truncated;
  5908. char gz_path[PATH_MAX];
  5909. const char *encoding = "";
  5910. const char *cors1, *cors2, *cors3;
  5911. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5912. return;
  5913. }
  5914. if (mime_type == NULL) {
  5915. get_mime_type(conn->ctx, path, &mime_vec);
  5916. } else {
  5917. mime_vec.ptr = mime_type;
  5918. mime_vec.len = strlen(mime_type);
  5919. }
  5920. if (filep->size > INT64_MAX) {
  5921. send_http_error(conn,
  5922. 500,
  5923. "Error: File size is too large to send\n%" INT64_FMT,
  5924. filep->size);
  5925. }
  5926. cl = (int64_t)filep->size;
  5927. conn->status_code = 200;
  5928. range[0] = '\0';
  5929. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5930. * it's important to rewrite the filename after resolving
  5931. * the mime type from it, to preserve the actual file's type */
  5932. if (filep->gzipped) {
  5933. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5934. if (truncated) {
  5935. send_http_error(conn,
  5936. 500,
  5937. "Error: Path of zipped file too long (%s)",
  5938. path);
  5939. return;
  5940. }
  5941. path = gz_path;
  5942. encoding = "Content-Encoding: gzip\r\n";
  5943. }
  5944. if (!mg_fopen(conn, path, "rb", filep)) {
  5945. send_http_error(conn,
  5946. 500,
  5947. "Error: Cannot open file\nfopen(%s): %s",
  5948. path,
  5949. strerror(ERRNO));
  5950. return;
  5951. }
  5952. fclose_on_exec(filep, conn);
  5953. /* If Range: header specified, act accordingly */
  5954. r1 = r2 = 0;
  5955. hdr = mg_get_header(conn, "Range");
  5956. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5957. && r2 >= 0) {
  5958. /* actually, range requests don't play well with a pre-gzipped
  5959. * file (since the range is specified in the uncompressed space) */
  5960. if (filep->gzipped) {
  5961. send_http_error(
  5962. conn,
  5963. 501,
  5964. "%s",
  5965. "Error: Range requests in gzipped files are not supported");
  5966. mg_fclose(filep);
  5967. return;
  5968. }
  5969. conn->status_code = 206;
  5970. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  5971. mg_snprintf(conn,
  5972. NULL, /* range buffer is big enough */
  5973. range,
  5974. sizeof(range),
  5975. "Content-Range: bytes "
  5976. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5977. r1,
  5978. r1 + cl - 1,
  5979. filep->size);
  5980. msg = "Partial Content";
  5981. }
  5982. hdr = mg_get_header(conn, "Origin");
  5983. if (hdr) {
  5984. /* Cross-origin resource sharing (CORS), see
  5985. * http://www.html5rocks.com/en/tutorials/cors/,
  5986. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5987. * preflight is not supported for files. */
  5988. cors1 = "Access-Control-Allow-Origin: ";
  5989. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5990. cors3 = "\r\n";
  5991. } else {
  5992. cors1 = cors2 = cors3 = "";
  5993. }
  5994. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5995. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5996. gmt_time_string(date, sizeof(date), &curtime);
  5997. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5998. construct_etag(etag, sizeof(etag), filep);
  5999. (void)mg_printf(conn,
  6000. "HTTP/1.1 %d %s\r\n"
  6001. "%s%s%s"
  6002. "Date: %s\r\n",
  6003. conn->status_code,
  6004. msg,
  6005. cors1,
  6006. cors2,
  6007. cors3,
  6008. date);
  6009. send_static_cache_header(conn);
  6010. (void)mg_printf(conn,
  6011. "Last-Modified: %s\r\n"
  6012. "Etag: %s\r\n"
  6013. "Content-Type: %.*s\r\n"
  6014. "Content-Length: %" INT64_FMT "\r\n"
  6015. "Connection: %s\r\n"
  6016. "Accept-Ranges: bytes\r\n"
  6017. "%s%s",
  6018. lm,
  6019. etag,
  6020. (int)mime_vec.len,
  6021. mime_vec.ptr,
  6022. cl,
  6023. suggest_connection_header(conn),
  6024. range,
  6025. encoding);
  6026. /* The previous code must not add any header starting with X- to make
  6027. * sure no one of the additional_headers is included twice */
  6028. if (additional_headers != NULL) {
  6029. (void)mg_printf(conn,
  6030. "%.*s\r\n\r\n",
  6031. (int)strlen(additional_headers),
  6032. additional_headers);
  6033. } else {
  6034. (void)mg_printf(conn, "\r\n");
  6035. }
  6036. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6037. send_file_data(conn, filep, r1, cl);
  6038. }
  6039. mg_fclose(filep);
  6040. }
  6041. #if !defined(NO_CACHING)
  6042. static void
  6043. handle_not_modified_static_file_request(struct mg_connection *conn,
  6044. struct file *filep)
  6045. {
  6046. char date[64], lm[64], etag[64];
  6047. time_t curtime = time(NULL);
  6048. if (conn == NULL || filep == NULL) {
  6049. return;
  6050. }
  6051. conn->status_code = 304;
  6052. gmt_time_string(date, sizeof(date), &curtime);
  6053. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  6054. construct_etag(etag, sizeof(etag), filep);
  6055. (void)mg_printf(conn,
  6056. "HTTP/1.1 %d %s\r\n"
  6057. "Date: %s\r\n",
  6058. conn->status_code,
  6059. mg_get_response_code_text(conn, conn->status_code),
  6060. date);
  6061. send_static_cache_header(conn);
  6062. (void)mg_printf(conn,
  6063. "Last-Modified: %s\r\n"
  6064. "Etag: %s\r\n"
  6065. "Connection: %s\r\n"
  6066. "\r\n",
  6067. lm,
  6068. etag,
  6069. suggest_connection_header(conn));
  6070. }
  6071. #endif
  6072. void
  6073. mg_send_file(struct mg_connection *conn, const char *path)
  6074. {
  6075. mg_send_mime_file(conn, path, NULL);
  6076. }
  6077. void
  6078. mg_send_mime_file(struct mg_connection *conn,
  6079. const char *path,
  6080. const char *mime_type)
  6081. {
  6082. mg_send_mime_file2(conn, path, mime_type, NULL);
  6083. }
  6084. void
  6085. mg_send_mime_file2(struct mg_connection *conn,
  6086. const char *path,
  6087. const char *mime_type,
  6088. const char *additional_headers)
  6089. {
  6090. struct file file = STRUCT_FILE_INITIALIZER;
  6091. if (mg_stat(conn, path, &file)) {
  6092. if (file.is_directory) {
  6093. if (!conn) {
  6094. return;
  6095. }
  6096. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6097. "yes")) {
  6098. handle_directory_request(conn, path);
  6099. } else {
  6100. send_http_error(conn,
  6101. 403,
  6102. "%s",
  6103. "Error: Directory listing denied");
  6104. }
  6105. } else {
  6106. handle_static_file_request(
  6107. conn, path, &file, mime_type, additional_headers);
  6108. }
  6109. } else {
  6110. send_http_error(conn, 404, "%s", "Error: File not found");
  6111. }
  6112. }
  6113. /* For a given PUT path, create all intermediate subdirectories.
  6114. * Return 0 if the path itself is a directory.
  6115. * Return 1 if the path leads to a file.
  6116. * Return -1 for if the path is too long.
  6117. * Return -2 if path can not be created.
  6118. */
  6119. static int
  6120. put_dir(struct mg_connection *conn, const char *path)
  6121. {
  6122. char buf[PATH_MAX];
  6123. const char *s, *p;
  6124. struct file file = STRUCT_FILE_INITIALIZER;
  6125. size_t len;
  6126. int res = 1;
  6127. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6128. len = (size_t)(p - path);
  6129. if (len >= sizeof(buf)) {
  6130. /* path too long */
  6131. res = -1;
  6132. break;
  6133. }
  6134. memcpy(buf, path, len);
  6135. buf[len] = '\0';
  6136. /* Try to create intermediate directory */
  6137. DEBUG_TRACE("mkdir(%s)", buf);
  6138. if (!mg_stat(conn, buf, &file) && mg_mkdir(conn, buf, 0755) != 0) {
  6139. /* path does not exixt and can not be created */
  6140. res = -2;
  6141. break;
  6142. }
  6143. /* Is path itself a directory? */
  6144. if (p[1] == '\0') {
  6145. res = 0;
  6146. }
  6147. }
  6148. return res;
  6149. }
  6150. static void
  6151. remove_bad_file(const struct mg_connection *conn, const char *path)
  6152. {
  6153. int r = mg_remove(conn, path);
  6154. if (r != 0) {
  6155. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6156. }
  6157. }
  6158. long long
  6159. mg_store_body(struct mg_connection *conn, const char *path)
  6160. {
  6161. char buf[MG_BUF_LEN];
  6162. long long len = 0;
  6163. int ret, n;
  6164. struct file fi;
  6165. if (conn->consumed_content != 0) {
  6166. mg_cry(conn, "%s: Contents already consumed", __func__);
  6167. return -11;
  6168. }
  6169. ret = put_dir(conn, path);
  6170. if (ret < 0) {
  6171. /* -1 for path too long,
  6172. * -2 for path can not be created. */
  6173. return ret;
  6174. }
  6175. if (ret != 1) {
  6176. /* Return 0 means, path itself is a directory. */
  6177. return 0;
  6178. }
  6179. if (mg_fopen(conn, path, "w", &fi) == 0) {
  6180. return -12;
  6181. }
  6182. ret = mg_read(conn, buf, sizeof(buf));
  6183. while (ret > 0) {
  6184. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  6185. if (n != ret) {
  6186. mg_fclose(&fi);
  6187. remove_bad_file(conn, path);
  6188. return -13;
  6189. }
  6190. ret = mg_read(conn, buf, sizeof(buf));
  6191. }
  6192. /* TODO: mg_fclose should return an error,
  6193. * and every caller should check and handle it. */
  6194. if (fclose(fi.fp) != 0) {
  6195. remove_bad_file(conn, path);
  6196. return -14;
  6197. }
  6198. return len;
  6199. }
  6200. /* Parse HTTP headers from the given buffer, advance buf pointer
  6201. * to the point where parsing stopped.
  6202. * All parameters must be valid pointers (not NULL).
  6203. * Return <0 on error. */
  6204. static int
  6205. parse_http_headers(char **buf, struct mg_request_info *ri)
  6206. {
  6207. int i;
  6208. ri->num_headers = 0;
  6209. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6210. char *dp = *buf;
  6211. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6212. dp++;
  6213. }
  6214. if (dp == *buf) {
  6215. /* End of headers reached. */
  6216. break;
  6217. }
  6218. if (*dp != ':') {
  6219. /* This is not a valid field. */
  6220. return -1;
  6221. }
  6222. /* End of header key (*dp == ':') */
  6223. /* Truncate here and set the key name */
  6224. *dp = 0;
  6225. ri->http_headers[i].name = *buf;
  6226. do {
  6227. dp++;
  6228. } while (*dp == ' ');
  6229. /* The rest of the line is the value */
  6230. ri->http_headers[i].value = dp;
  6231. *buf = dp + strcspn(dp, "\r\n");
  6232. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6233. *buf = NULL;
  6234. }
  6235. ri->num_headers = i + 1;
  6236. if (*buf) {
  6237. (*buf)[0] = 0;
  6238. (*buf)[1] = 0;
  6239. *buf += 2;
  6240. } else {
  6241. *buf = dp;
  6242. break;
  6243. }
  6244. if ((*buf)[0] == '\r') {
  6245. /* This is the end of the header */
  6246. break;
  6247. }
  6248. }
  6249. return ri->num_headers;
  6250. }
  6251. static int
  6252. is_valid_http_method(const char *method)
  6253. {
  6254. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6255. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6256. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6257. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6258. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6259. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6260. /* TRACE method (RFC 2616) is not supported for security reasons */
  6261. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6262. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6263. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6264. /* Unsupported WEBDAV Methods: */
  6265. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6266. /* + 11 methods from RFC 3253 */
  6267. /* ORDERPATCH (RFC 3648) */
  6268. /* ACL (RFC 3744) */
  6269. /* SEARCH (RFC 5323) */
  6270. /* + MicroSoft extensions
  6271. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6272. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6273. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6274. }
  6275. /* Parse HTTP request, fill in mg_request_info structure.
  6276. * This function modifies the buffer by NUL-terminating
  6277. * HTTP request components, header names and header values.
  6278. * Parameters:
  6279. * buf (in/out): pointer to the HTTP header to parse and split
  6280. * len (in): length of HTTP header buffer
  6281. * re (out): parsed header as mg_request_info
  6282. * buf and ri must be valid pointers (not NULL), len>0.
  6283. * Returns <0 on error. */
  6284. static int
  6285. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6286. {
  6287. int is_request, request_length;
  6288. char *start_line;
  6289. request_length = get_request_len(buf, len);
  6290. if (request_length > 0) {
  6291. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6292. * remote_port */
  6293. ri->remote_user = ri->request_method = ri->request_uri =
  6294. ri->http_version = NULL;
  6295. ri->num_headers = 0;
  6296. buf[request_length - 1] = '\0';
  6297. /* RFC says that all initial whitespaces should be ingored */
  6298. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6299. buf++;
  6300. }
  6301. start_line = skip(&buf, "\r\n");
  6302. ri->request_method = skip(&start_line, " ");
  6303. ri->request_uri = skip(&start_line, " ");
  6304. ri->http_version = start_line;
  6305. /* HTTP message could be either HTTP request:
  6306. * "GET / HTTP/1.0 ..."
  6307. * or a HTTP response:
  6308. * "HTTP/1.0 200 OK ..."
  6309. * otherwise it is invalid.
  6310. */
  6311. is_request = is_valid_http_method(ri->request_method);
  6312. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6313. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6314. /* Not a valid request or response: invalid */
  6315. return -1;
  6316. }
  6317. if (is_request) {
  6318. ri->http_version += 5;
  6319. }
  6320. if (parse_http_headers(&buf, ri) < 0) {
  6321. /* Error while parsing headers */
  6322. return -1;
  6323. }
  6324. }
  6325. return request_length;
  6326. }
  6327. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6328. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6329. * buffer (which marks the end of HTTP request). Buffer buf may already
  6330. * have some data. The length of the data is stored in nread.
  6331. * Upon every read operation, increase nread by the number of bytes read. */
  6332. static int
  6333. read_request(FILE *fp,
  6334. struct mg_connection *conn,
  6335. char *buf,
  6336. int bufsiz,
  6337. int *nread)
  6338. {
  6339. int request_len, n = 0;
  6340. struct timespec last_action_time;
  6341. double request_timeout;
  6342. if (!conn) {
  6343. return 0;
  6344. }
  6345. memset(&last_action_time, 0, sizeof(last_action_time));
  6346. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6347. /* value of request_timeout is in seconds, config in milliseconds */
  6348. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6349. } else {
  6350. request_timeout = -1.0;
  6351. }
  6352. request_len = get_request_len(buf, *nread);
  6353. /* first time reading from this connection */
  6354. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6355. while (
  6356. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  6357. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  6358. <= request_timeout) || (request_timeout < 0))
  6359. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  6360. > 0)) {
  6361. *nread += n;
  6362. /* assert(*nread <= bufsiz); */
  6363. if (*nread > bufsiz) {
  6364. return -2;
  6365. }
  6366. request_len = get_request_len(buf, *nread);
  6367. if (request_timeout > 0.0) {
  6368. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6369. }
  6370. }
  6371. return ((request_len <= 0) && (n <= 0)) ? -1 : request_len;
  6372. }
  6373. #if !defined(NO_FILES)
  6374. /* For given directory path, substitute it to valid index file.
  6375. * Return 1 if index file has been found, 0 if not found.
  6376. * If the file is found, it's stats is returned in stp. */
  6377. static int
  6378. substitute_index_file(struct mg_connection *conn,
  6379. char *path,
  6380. size_t path_len,
  6381. struct file *filep)
  6382. {
  6383. if (conn && conn->ctx) {
  6384. const char *list = conn->ctx->config[INDEX_FILES];
  6385. struct file file = STRUCT_FILE_INITIALIZER;
  6386. struct vec filename_vec;
  6387. size_t n = strlen(path);
  6388. int found = 0;
  6389. /* The 'path' given to us points to the directory. Remove all trailing
  6390. * directory separator characters from the end of the path, and
  6391. * then append single directory separator character. */
  6392. while (n > 0 && path[n - 1] == '/') {
  6393. n--;
  6394. }
  6395. path[n] = '/';
  6396. /* Traverse index files list. For each entry, append it to the given
  6397. * path and see if the file exists. If it exists, break the loop */
  6398. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6399. /* Ignore too long entries that may overflow path buffer */
  6400. if (filename_vec.len > path_len - (n + 2)) {
  6401. continue;
  6402. }
  6403. /* Prepare full path to the index file */
  6404. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6405. /* Does it exist? */
  6406. if (mg_stat(conn, path, &file)) {
  6407. /* Yes it does, break the loop */
  6408. *filep = file;
  6409. found = 1;
  6410. break;
  6411. }
  6412. }
  6413. /* If no index file exists, restore directory path */
  6414. if (!found) {
  6415. path[n] = '\0';
  6416. }
  6417. return found;
  6418. }
  6419. return 0;
  6420. }
  6421. #endif
  6422. #if !defined(NO_CACHING)
  6423. /* Return True if we should reply 304 Not Modified. */
  6424. static int
  6425. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  6426. {
  6427. char etag[64];
  6428. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6429. const char *inm = mg_get_header(conn, "If-None-Match");
  6430. construct_etag(etag, sizeof(etag), filep);
  6431. if (!filep) {
  6432. return 0;
  6433. }
  6434. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6435. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  6436. }
  6437. #endif /* !NO_CACHING */
  6438. #if !defined(NO_CGI) || !defined(NO_FILES)
  6439. static int
  6440. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6441. {
  6442. const char *expect, *body;
  6443. char buf[MG_BUF_LEN];
  6444. int to_read, nread, success = 0;
  6445. int64_t buffered_len;
  6446. double timeout = -1.0;
  6447. if (!conn) {
  6448. return 0;
  6449. }
  6450. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6451. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6452. }
  6453. expect = mg_get_header(conn, "Expect");
  6454. /* assert(fp != NULL); */
  6455. if (!fp) {
  6456. send_http_error(conn, 500, "%s", "Error: NULL File");
  6457. return 0;
  6458. }
  6459. if (conn->content_len == -1 && !conn->is_chunked) {
  6460. /* Content length is not specified by the client. */
  6461. send_http_error(conn,
  6462. 411,
  6463. "%s",
  6464. "Error: Client did not specify content length");
  6465. } else if ((expect != NULL)
  6466. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6467. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6468. send_http_error(conn,
  6469. 417,
  6470. "Error: Can not fulfill expectation %s",
  6471. expect);
  6472. } else {
  6473. if (expect != NULL) {
  6474. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6475. conn->status_code = 100;
  6476. } else {
  6477. conn->status_code = 200;
  6478. }
  6479. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6480. - conn->consumed_content;
  6481. /* assert(buffered_len >= 0); */
  6482. /* assert(conn->consumed_content == 0); */
  6483. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6484. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6485. return 0;
  6486. }
  6487. if (buffered_len > 0) {
  6488. if ((int64_t)buffered_len > conn->content_len) {
  6489. buffered_len = (int)conn->content_len;
  6490. }
  6491. body = conn->buf + conn->request_len + conn->consumed_content;
  6492. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6493. conn->consumed_content += buffered_len;
  6494. }
  6495. nread = 0;
  6496. while (conn->consumed_content < conn->content_len) {
  6497. to_read = sizeof(buf);
  6498. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6499. to_read = (int)(conn->content_len - conn->consumed_content);
  6500. }
  6501. nread = pull(NULL, conn, buf, to_read, timeout);
  6502. if (nread <= 0
  6503. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6504. break;
  6505. }
  6506. conn->consumed_content += nread;
  6507. }
  6508. if (conn->consumed_content == conn->content_len) {
  6509. success = (nread >= 0);
  6510. }
  6511. /* Each error code path in this function must send an error */
  6512. if (!success) {
  6513. /* NOTE: Maybe some data has already been sent. */
  6514. /* TODO (low): If some data has been sent, a correct error
  6515. * reply can no longer be sent, so just close the connection */
  6516. send_http_error(conn, 500, "%s", "");
  6517. }
  6518. }
  6519. return success;
  6520. }
  6521. #endif
  6522. #if !defined(NO_CGI)
  6523. /* This structure helps to create an environment for the spawned CGI program.
  6524. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6525. * last element must be NULL.
  6526. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6527. * strings must reside in a contiguous buffer. The end of the buffer is
  6528. * marked by two '\0' characters.
  6529. * We satisfy both worlds: we create an envp array (which is vars), all
  6530. * entries are actually pointers inside buf. */
  6531. struct cgi_environment {
  6532. struct mg_connection *conn;
  6533. /* Data block */
  6534. char *buf; /* Environment buffer */
  6535. size_t buflen; /* Space available in buf */
  6536. size_t bufused; /* Space taken in buf */
  6537. /* Index block */
  6538. char **var; /* char **envp */
  6539. size_t varlen; /* Number of variables available in var */
  6540. size_t varused; /* Number of variables stored in var */
  6541. };
  6542. static void addenv(struct cgi_environment *env,
  6543. PRINTF_FORMAT_STRING(const char *fmt),
  6544. ...) PRINTF_ARGS(2, 3);
  6545. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6546. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6547. static void
  6548. addenv(struct cgi_environment *env, const char *fmt, ...)
  6549. {
  6550. size_t n, space;
  6551. int truncated;
  6552. char *added;
  6553. va_list ap;
  6554. /* Calculate how much space is left in the buffer */
  6555. space = (env->buflen - env->bufused);
  6556. /* Calculate an estimate for the required space */
  6557. n = strlen(fmt) + 2 + 128;
  6558. do {
  6559. if (space <= n) {
  6560. /* Allocate new buffer */
  6561. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6562. added = (char *)mg_realloc(env->buf, n);
  6563. if (!added) {
  6564. /* Out of memory */
  6565. mg_cry(env->conn,
  6566. "%s: Cannot allocate memory for CGI variable [%s]",
  6567. __func__,
  6568. fmt);
  6569. return;
  6570. }
  6571. env->buf = added;
  6572. env->buflen = n;
  6573. space = (env->buflen - env->bufused);
  6574. }
  6575. /* Make a pointer to the free space int the buffer */
  6576. added = env->buf + env->bufused;
  6577. /* Copy VARIABLE=VALUE\0 string into the free space */
  6578. va_start(ap, fmt);
  6579. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6580. va_end(ap);
  6581. /* Do not add truncated strings to the environment */
  6582. if (truncated) {
  6583. /* Reallocate the buffer */
  6584. space = 0;
  6585. n = 1;
  6586. }
  6587. } while (truncated);
  6588. /* Calculate number of bytes added to the environment */
  6589. n = strlen(added) + 1;
  6590. env->bufused += n;
  6591. /* Now update the variable index */
  6592. space = (env->varlen - env->varused);
  6593. if (space < 2) {
  6594. mg_cry(env->conn,
  6595. "%s: Cannot register CGI variable [%s]",
  6596. __func__,
  6597. fmt);
  6598. return;
  6599. }
  6600. /* Append a pointer to the added string into the envp array */
  6601. env->var[env->varused] = added;
  6602. env->varused++;
  6603. }
  6604. static void
  6605. prepare_cgi_environment(struct mg_connection *conn,
  6606. const char *prog,
  6607. struct cgi_environment *env)
  6608. {
  6609. const char *s;
  6610. struct vec var_vec;
  6611. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6612. int i, truncated;
  6613. if (conn == NULL || prog == NULL || env == NULL) {
  6614. return;
  6615. }
  6616. env->conn = conn;
  6617. env->buflen = CGI_ENVIRONMENT_SIZE;
  6618. env->bufused = 0;
  6619. env->buf = (char *)mg_malloc(env->buflen);
  6620. env->varlen = MAX_CGI_ENVIR_VARS;
  6621. env->varused = 0;
  6622. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6623. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6624. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6625. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6626. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6627. /* Prepare the environment block */
  6628. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6629. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6630. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6631. #if defined(USE_IPV6)
  6632. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6633. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6634. } else
  6635. #endif
  6636. {
  6637. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6638. }
  6639. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6640. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6641. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6642. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6643. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6644. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6645. /* SCRIPT_NAME */
  6646. addenv(env,
  6647. "SCRIPT_NAME=%.*s",
  6648. (int)strlen(conn->request_info.local_uri)
  6649. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6650. conn->request_info.local_uri);
  6651. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6652. if (conn->path_info == NULL) {
  6653. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6654. } else {
  6655. addenv(env,
  6656. "PATH_TRANSLATED=%s%s",
  6657. conn->ctx->config[DOCUMENT_ROOT],
  6658. conn->path_info);
  6659. }
  6660. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  6661. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6662. addenv(env, "CONTENT_TYPE=%s", s);
  6663. }
  6664. if (conn->request_info.query_string != NULL) {
  6665. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6666. }
  6667. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6668. addenv(env, "CONTENT_LENGTH=%s", s);
  6669. }
  6670. if ((s = getenv("PATH")) != NULL) {
  6671. addenv(env, "PATH=%s", s);
  6672. }
  6673. if (conn->path_info != NULL) {
  6674. addenv(env, "PATH_INFO=%s", conn->path_info);
  6675. }
  6676. if (conn->status_code > 0) {
  6677. /* CGI error handler should show the status code */
  6678. addenv(env, "STATUS=%d", conn->status_code);
  6679. }
  6680. #if defined(_WIN32)
  6681. if ((s = getenv("COMSPEC")) != NULL) {
  6682. addenv(env, "COMSPEC=%s", s);
  6683. }
  6684. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6685. addenv(env, "SYSTEMROOT=%s", s);
  6686. }
  6687. if ((s = getenv("SystemDrive")) != NULL) {
  6688. addenv(env, "SystemDrive=%s", s);
  6689. }
  6690. if ((s = getenv("ProgramFiles")) != NULL) {
  6691. addenv(env, "ProgramFiles=%s", s);
  6692. }
  6693. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6694. addenv(env, "ProgramFiles(x86)=%s", s);
  6695. }
  6696. #else
  6697. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6698. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6699. }
  6700. #endif /* _WIN32 */
  6701. if ((s = getenv("PERLLIB")) != NULL) {
  6702. addenv(env, "PERLLIB=%s", s);
  6703. }
  6704. if (conn->request_info.remote_user != NULL) {
  6705. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6706. addenv(env, "%s", "AUTH_TYPE=Digest");
  6707. }
  6708. /* Add all headers as HTTP_* variables */
  6709. for (i = 0; i < conn->request_info.num_headers; i++) {
  6710. (void)mg_snprintf(conn,
  6711. &truncated,
  6712. http_var_name,
  6713. sizeof(http_var_name),
  6714. "HTTP_%s",
  6715. conn->request_info.http_headers[i].name);
  6716. if (truncated) {
  6717. mg_cry(conn,
  6718. "%s: HTTP header variable too long [%s]",
  6719. __func__,
  6720. conn->request_info.http_headers[i].name);
  6721. continue;
  6722. }
  6723. /* Convert variable name into uppercase, and change - to _ */
  6724. for (p = http_var_name; *p != '\0'; p++) {
  6725. if (*p == '-') {
  6726. *p = '_';
  6727. }
  6728. *p = (char)toupper(*(unsigned char *)p);
  6729. }
  6730. addenv(env,
  6731. "%s=%s",
  6732. http_var_name,
  6733. conn->request_info.http_headers[i].value);
  6734. }
  6735. /* Add user-specified variables */
  6736. s = conn->ctx->config[CGI_ENVIRONMENT];
  6737. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6738. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6739. }
  6740. env->var[env->varused] = NULL;
  6741. env->buf[env->bufused] = '\0';
  6742. }
  6743. static void
  6744. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6745. {
  6746. char *buf;
  6747. size_t buflen;
  6748. int headers_len, data_len, i, truncated;
  6749. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6750. const char *status, *status_text, *connection_state;
  6751. char *pbuf, dir[PATH_MAX], *p;
  6752. struct mg_request_info ri;
  6753. struct cgi_environment blk;
  6754. FILE *in = NULL, *out = NULL, *err = NULL;
  6755. struct file fout = STRUCT_FILE_INITIALIZER;
  6756. pid_t pid = (pid_t)-1;
  6757. if (conn == NULL) {
  6758. return;
  6759. }
  6760. buf = NULL;
  6761. buflen = 16384;
  6762. prepare_cgi_environment(conn, prog, &blk);
  6763. /* CGI must be executed in its own directory. 'dir' must point to the
  6764. * directory containing executable program, 'p' must point to the
  6765. * executable program name relative to 'dir'. */
  6766. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6767. if (truncated) {
  6768. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6769. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6770. goto done;
  6771. }
  6772. if ((p = strrchr(dir, '/')) != NULL) {
  6773. *p++ = '\0';
  6774. } else {
  6775. dir[0] = '.', dir[1] = '\0';
  6776. p = (char *)prog;
  6777. }
  6778. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6779. status = strerror(ERRNO);
  6780. mg_cry(conn,
  6781. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6782. prog,
  6783. status);
  6784. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6785. goto done;
  6786. }
  6787. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  6788. if (pid == (pid_t)-1) {
  6789. status = strerror(ERRNO);
  6790. mg_cry(conn,
  6791. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6792. prog,
  6793. status);
  6794. send_http_error(conn,
  6795. 500,
  6796. "Error: Cannot spawn CGI process [%s]: %s",
  6797. prog,
  6798. status);
  6799. goto done;
  6800. }
  6801. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6802. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  6803. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  6804. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  6805. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  6806. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  6807. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  6808. /* Parent closes only one side of the pipes.
  6809. * If we don't mark them as closed, close() attempt before
  6810. * return from this function throws an exception on Windows.
  6811. * Windows does not like when closed descriptor is closed again. */
  6812. (void)close(fdin[0]);
  6813. (void)close(fdout[1]);
  6814. (void)close(fderr[1]);
  6815. fdin[0] = fdout[1] = fderr[1] = -1;
  6816. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6817. status = strerror(ERRNO);
  6818. mg_cry(conn,
  6819. "Error: CGI program \"%s\": Can not open stdin: %s",
  6820. prog,
  6821. status);
  6822. send_http_error(conn,
  6823. 500,
  6824. "Error: CGI can not open fdin\nfopen: %s",
  6825. status);
  6826. goto done;
  6827. }
  6828. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6829. status = strerror(ERRNO);
  6830. mg_cry(conn,
  6831. "Error: CGI program \"%s\": Can not open stdout: %s",
  6832. prog,
  6833. status);
  6834. send_http_error(conn,
  6835. 500,
  6836. "Error: CGI can not open fdout\nfopen: %s",
  6837. status);
  6838. goto done;
  6839. }
  6840. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6841. status = strerror(ERRNO);
  6842. mg_cry(conn,
  6843. "Error: CGI program \"%s\": Can not open stderr: %s",
  6844. prog,
  6845. status);
  6846. send_http_error(conn,
  6847. 500,
  6848. "Error: CGI can not open fdout\nfopen: %s",
  6849. status);
  6850. goto done;
  6851. }
  6852. setbuf(in, NULL);
  6853. setbuf(out, NULL);
  6854. setbuf(err, NULL);
  6855. fout.fp = out;
  6856. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6857. /* This is a POST/PUT request, or another request with body data. */
  6858. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6859. /* Error sending the body data */
  6860. mg_cry(conn,
  6861. "Error: CGI program \"%s\": Forward body data failed",
  6862. prog);
  6863. goto done;
  6864. }
  6865. }
  6866. /* Close so child gets an EOF. */
  6867. fclose(in);
  6868. in = NULL;
  6869. fdin[1] = -1;
  6870. /* Now read CGI reply into a buffer. We need to set correct
  6871. * status code, thus we need to see all HTTP headers first.
  6872. * Do not send anything back to client, until we buffer in all
  6873. * HTTP headers. */
  6874. data_len = 0;
  6875. buf = (char *)mg_malloc(buflen);
  6876. if (buf == NULL) {
  6877. send_http_error(conn,
  6878. 500,
  6879. "Error: Not enough memory for CGI buffer (%u bytes)",
  6880. (unsigned int)buflen);
  6881. mg_cry(conn,
  6882. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6883. "bytes)",
  6884. prog,
  6885. (unsigned int)buflen);
  6886. goto done;
  6887. }
  6888. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6889. if (headers_len <= 0) {
  6890. /* Could not parse the CGI response. Check if some error message on
  6891. * stderr. */
  6892. i = pull_all(err, conn, buf, (int)buflen);
  6893. if (i > 0) {
  6894. mg_cry(conn,
  6895. "Error: CGI program \"%s\" sent error "
  6896. "message: [%.*s]",
  6897. prog,
  6898. i,
  6899. buf);
  6900. send_http_error(conn,
  6901. 500,
  6902. "Error: CGI program \"%s\" sent error "
  6903. "message: [%.*s]",
  6904. prog,
  6905. i,
  6906. buf);
  6907. } else {
  6908. mg_cry(conn,
  6909. "Error: CGI program sent malformed or too big "
  6910. "(>%u bytes) HTTP headers: [%.*s]",
  6911. (unsigned)buflen,
  6912. data_len,
  6913. buf);
  6914. send_http_error(conn,
  6915. 500,
  6916. "Error: CGI program sent malformed or too big "
  6917. "(>%u bytes) HTTP headers: [%.*s]",
  6918. (unsigned)buflen,
  6919. data_len,
  6920. buf);
  6921. }
  6922. goto done;
  6923. }
  6924. pbuf = buf;
  6925. buf[headers_len - 1] = '\0';
  6926. parse_http_headers(&pbuf, &ri);
  6927. /* Make up and send the status line */
  6928. status_text = "OK";
  6929. if ((status = get_header(&ri, "Status")) != NULL) {
  6930. conn->status_code = atoi(status);
  6931. status_text = status;
  6932. while (isdigit(*(const unsigned char *)status_text)
  6933. || *status_text == ' ') {
  6934. status_text++;
  6935. }
  6936. } else if (get_header(&ri, "Location") != NULL) {
  6937. conn->status_code = 302;
  6938. } else {
  6939. conn->status_code = 200;
  6940. }
  6941. connection_state = get_header(&ri, "Connection");
  6942. if (!header_has_option(connection_state, "keep-alive")) {
  6943. conn->must_close = 1;
  6944. }
  6945. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6946. /* Send headers */
  6947. for (i = 0; i < ri.num_headers; i++) {
  6948. mg_printf(conn,
  6949. "%s: %s\r\n",
  6950. ri.http_headers[i].name,
  6951. ri.http_headers[i].value);
  6952. }
  6953. mg_write(conn, "\r\n", 2);
  6954. /* Send chunk of data that may have been read after the headers */
  6955. conn->num_bytes_sent +=
  6956. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6957. /* Read the rest of CGI output and send to the client */
  6958. send_file_data(conn, &fout, 0, INT64_MAX);
  6959. done:
  6960. mg_free(blk.var);
  6961. mg_free(blk.buf);
  6962. if (pid != (pid_t)-1) {
  6963. kill(pid, SIGKILL);
  6964. #if !defined(_WIN32)
  6965. {
  6966. int st;
  6967. while (waitpid(pid, &st, 0) != -1)
  6968. ; /* clean zombies */
  6969. }
  6970. #endif
  6971. }
  6972. if (fdin[0] != -1) {
  6973. close(fdin[0]);
  6974. }
  6975. if (fdout[1] != -1) {
  6976. close(fdout[1]);
  6977. }
  6978. if (in != NULL) {
  6979. fclose(in);
  6980. } else if (fdin[1] != -1) {
  6981. close(fdin[1]);
  6982. }
  6983. if (out != NULL) {
  6984. fclose(out);
  6985. } else if (fdout[0] != -1) {
  6986. close(fdout[0]);
  6987. }
  6988. if (err != NULL) {
  6989. fclose(err);
  6990. } else if (fderr[0] != -1) {
  6991. close(fderr[0]);
  6992. }
  6993. if (buf != NULL) {
  6994. mg_free(buf);
  6995. }
  6996. }
  6997. #endif /* !NO_CGI */
  6998. #if !defined(NO_FILES)
  6999. static void
  7000. mkcol(struct mg_connection *conn, const char *path)
  7001. {
  7002. int rc, body_len;
  7003. struct de de;
  7004. char date[64];
  7005. time_t curtime = time(NULL);
  7006. if (conn == NULL) {
  7007. return;
  7008. }
  7009. /* TODO (mid): Check the send_http_error situations in this function */
  7010. memset(&de.file, 0, sizeof(de.file));
  7011. if (!mg_stat(conn, path, &de.file)) {
  7012. mg_cry(conn,
  7013. "%s: mg_stat(%s) failed: %s",
  7014. __func__,
  7015. path,
  7016. strerror(ERRNO));
  7017. }
  7018. if (de.file.last_modified) {
  7019. /* TODO (high): This check does not seem to make any sense ! */
  7020. send_http_error(
  7021. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7022. return;
  7023. }
  7024. body_len = conn->data_len - conn->request_len;
  7025. if (body_len > 0) {
  7026. send_http_error(
  7027. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7028. return;
  7029. }
  7030. rc = mg_mkdir(conn, path, 0755);
  7031. if (rc == 0) {
  7032. conn->status_code = 201;
  7033. gmt_time_string(date, sizeof(date), &curtime);
  7034. mg_printf(conn,
  7035. "HTTP/1.1 %d Created\r\n"
  7036. "Date: %s\r\n",
  7037. conn->status_code,
  7038. date);
  7039. send_static_cache_header(conn);
  7040. mg_printf(conn,
  7041. "Content-Length: 0\r\n"
  7042. "Connection: %s\r\n\r\n",
  7043. suggest_connection_header(conn));
  7044. } else if (rc == -1) {
  7045. if (errno == EEXIST) {
  7046. send_http_error(
  7047. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7048. } else if (errno == EACCES) {
  7049. send_http_error(
  7050. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7051. } else if (errno == ENOENT) {
  7052. send_http_error(
  7053. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7054. } else {
  7055. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7056. }
  7057. }
  7058. }
  7059. static void
  7060. put_file(struct mg_connection *conn, const char *path)
  7061. {
  7062. struct file file = STRUCT_FILE_INITIALIZER;
  7063. const char *range;
  7064. int64_t r1, r2;
  7065. int rc;
  7066. char date[64];
  7067. time_t curtime = time(NULL);
  7068. if (conn == NULL) {
  7069. return;
  7070. }
  7071. if (mg_stat(conn, path, &file)) {
  7072. /* File already exists */
  7073. conn->status_code = 200;
  7074. if (file.is_directory) {
  7075. /* This is an already existing directory,
  7076. * so there is nothing to do for the server. */
  7077. rc = 0;
  7078. } else {
  7079. /* File exists and is not a directory. */
  7080. /* Can it be replaced? */
  7081. if (file.membuf != NULL) {
  7082. /* This is an "in-memory" file, that can not be replaced */
  7083. send_http_error(
  7084. conn,
  7085. 405,
  7086. "Error: Put not possible\nReplacing %s is not supported",
  7087. path);
  7088. return;
  7089. }
  7090. /* Check if the server may write this file */
  7091. if (access(path, W_OK) == 0) {
  7092. /* Access granted */
  7093. conn->status_code = 200;
  7094. rc = 1;
  7095. } else {
  7096. send_http_error(
  7097. conn,
  7098. 403,
  7099. "Error: Put not possible\nReplacing %s is not allowed",
  7100. path);
  7101. return;
  7102. }
  7103. }
  7104. } else {
  7105. /* File should be created */
  7106. conn->status_code = 201;
  7107. rc = put_dir(conn, path);
  7108. }
  7109. if (rc == 0) {
  7110. /* put_dir returns 0 if path is a directory */
  7111. gmt_time_string(date, sizeof(date), &curtime);
  7112. mg_printf(conn,
  7113. "HTTP/1.1 %d %s\r\n",
  7114. conn->status_code,
  7115. mg_get_response_code_text(NULL, conn->status_code));
  7116. send_no_cache_header(conn);
  7117. mg_printf(conn,
  7118. "Date: %s\r\n"
  7119. "Content-Length: 0\r\n"
  7120. "Connection: %s\r\n\r\n",
  7121. date,
  7122. suggest_connection_header(conn));
  7123. /* Request to create a directory has been fulfilled successfully.
  7124. * No need to put a file. */
  7125. return;
  7126. }
  7127. if (rc == -1) {
  7128. /* put_dir returns -1 if the path is too long */
  7129. send_http_error(conn,
  7130. 414,
  7131. "Error: Path too long\nput_dir(%s): %s",
  7132. path,
  7133. strerror(ERRNO));
  7134. return;
  7135. }
  7136. if (rc == -2) {
  7137. /* put_dir returns -2 if the directory can not be created */
  7138. send_http_error(conn,
  7139. 500,
  7140. "Error: Can not create directory\nput_dir(%s): %s",
  7141. path,
  7142. strerror(ERRNO));
  7143. return;
  7144. }
  7145. /* A file should be created or overwritten. */
  7146. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  7147. mg_fclose(&file);
  7148. send_http_error(conn,
  7149. 500,
  7150. "Error: Can not create file\nfopen(%s): %s",
  7151. path,
  7152. strerror(ERRNO));
  7153. return;
  7154. }
  7155. fclose_on_exec(&file, conn);
  7156. range = mg_get_header(conn, "Content-Range");
  7157. r1 = r2 = 0;
  7158. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7159. conn->status_code = 206; /* Partial content */
  7160. fseeko(file.fp, r1, SEEK_SET);
  7161. }
  7162. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  7163. /* forward_body_data failed.
  7164. * The error code has already been sent to the client,
  7165. * and conn->status_code is already set. */
  7166. mg_fclose(&file);
  7167. return;
  7168. }
  7169. gmt_time_string(date, sizeof(date), &curtime);
  7170. mg_printf(conn,
  7171. "HTTP/1.1 %d %s\r\n",
  7172. conn->status_code,
  7173. mg_get_response_code_text(NULL, conn->status_code));
  7174. send_no_cache_header(conn);
  7175. mg_printf(conn,
  7176. "Date: %s\r\n"
  7177. "Content-Length: 0\r\n"
  7178. "Connection: %s\r\n\r\n",
  7179. date,
  7180. suggest_connection_header(conn));
  7181. mg_fclose(&file);
  7182. }
  7183. static void
  7184. delete_file(struct mg_connection *conn, const char *path)
  7185. {
  7186. struct de de;
  7187. memset(&de.file, 0, sizeof(de.file));
  7188. if (!mg_stat(conn, path, &de.file)) {
  7189. /* mg_stat returns 0 if the file does not exist */
  7190. send_http_error(conn,
  7191. 404,
  7192. "Error: Cannot delete file\nFile %s not found",
  7193. path);
  7194. return;
  7195. }
  7196. if (de.file.membuf != NULL) {
  7197. /* the file is cached in memory */
  7198. send_http_error(
  7199. conn,
  7200. 405,
  7201. "Error: Delete not possible\nDeleting %s is not supported",
  7202. path);
  7203. return;
  7204. }
  7205. if (de.file.is_directory) {
  7206. if (remove_directory(conn, path)) {
  7207. /* Delete is successful: Return 204 without content. */
  7208. send_http_error(conn, 204, "%s", "");
  7209. } else {
  7210. /* Delete is not successful: Return 500 (Server error). */
  7211. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7212. }
  7213. return;
  7214. }
  7215. /* This is an existing file (not a directory).
  7216. * Check if write permission is granted. */
  7217. if (access(path, W_OK) != 0) {
  7218. /* File is read only */
  7219. send_http_error(
  7220. conn,
  7221. 403,
  7222. "Error: Delete not possible\nDeleting %s is not allowed",
  7223. path);
  7224. return;
  7225. }
  7226. /* Try to delete it. */
  7227. if (mg_remove(conn, path) == 0) {
  7228. /* Delete was successful: Return 204 without content. */
  7229. send_http_error(conn, 204, "%s", "");
  7230. } else {
  7231. /* Delete not successful (file locked). */
  7232. send_http_error(conn,
  7233. 423,
  7234. "Error: Cannot delete file\nremove(%s): %s",
  7235. path,
  7236. strerror(ERRNO));
  7237. }
  7238. }
  7239. #endif /* !NO_FILES */
  7240. static void
  7241. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  7242. static void
  7243. do_ssi_include(struct mg_connection *conn,
  7244. const char *ssi,
  7245. char *tag,
  7246. int include_level)
  7247. {
  7248. char file_name[MG_BUF_LEN], path[512], *p;
  7249. struct file file = STRUCT_FILE_INITIALIZER;
  7250. size_t len;
  7251. int truncated = 0;
  7252. if (conn == NULL) {
  7253. return;
  7254. }
  7255. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7256. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7257. * always < MG_BUF_LEN. */
  7258. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7259. /* File name is relative to the webserver root */
  7260. file_name[511] = 0;
  7261. (void)mg_snprintf(conn,
  7262. &truncated,
  7263. path,
  7264. sizeof(path),
  7265. "%s/%s",
  7266. conn->ctx->config[DOCUMENT_ROOT],
  7267. file_name);
  7268. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7269. /* File name is relative to the webserver working directory
  7270. * or it is absolute system path */
  7271. file_name[511] = 0;
  7272. (void)
  7273. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7274. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7275. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7276. /* File name is relative to the currect document */
  7277. file_name[511] = 0;
  7278. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7279. if (!truncated) {
  7280. if ((p = strrchr(path, '/')) != NULL) {
  7281. p[1] = '\0';
  7282. }
  7283. len = strlen(path);
  7284. (void)mg_snprintf(conn,
  7285. &truncated,
  7286. path + len,
  7287. sizeof(path) - len,
  7288. "%s",
  7289. file_name);
  7290. }
  7291. } else {
  7292. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7293. return;
  7294. }
  7295. if (truncated) {
  7296. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7297. return;
  7298. }
  7299. if (!mg_fopen(conn, path, "rb", &file)) {
  7300. mg_cry(conn,
  7301. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7302. tag,
  7303. path,
  7304. strerror(ERRNO));
  7305. } else {
  7306. fclose_on_exec(&file, conn);
  7307. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7308. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7309. path) > 0) {
  7310. send_ssi_file(conn, path, &file, include_level + 1);
  7311. } else {
  7312. send_file_data(conn, &file, 0, INT64_MAX);
  7313. }
  7314. mg_fclose(&file);
  7315. }
  7316. }
  7317. #if !defined(NO_POPEN)
  7318. static void
  7319. do_ssi_exec(struct mg_connection *conn, char *tag)
  7320. {
  7321. char cmd[1024] = "";
  7322. struct file file = STRUCT_FILE_INITIALIZER;
  7323. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7324. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7325. } else {
  7326. cmd[1023] = 0;
  7327. if ((file.fp = popen(cmd, "r")) == NULL) {
  7328. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7329. } else {
  7330. send_file_data(conn, &file, 0, INT64_MAX);
  7331. pclose(file.fp);
  7332. }
  7333. }
  7334. }
  7335. #endif /* !NO_POPEN */
  7336. static int
  7337. mg_fgetc(struct file *filep, int offset)
  7338. {
  7339. if (filep == NULL) {
  7340. return EOF;
  7341. }
  7342. if (filep->membuf != NULL && offset >= 0
  7343. && ((unsigned int)(offset)) < filep->size) {
  7344. return ((const unsigned char *)filep->membuf)[offset];
  7345. } else if (filep->fp != NULL) {
  7346. return fgetc(filep->fp);
  7347. } else {
  7348. return EOF;
  7349. }
  7350. }
  7351. static void
  7352. send_ssi_file(struct mg_connection *conn,
  7353. const char *path,
  7354. struct file *filep,
  7355. int include_level)
  7356. {
  7357. char buf[MG_BUF_LEN];
  7358. int ch, offset, len, in_ssi_tag;
  7359. if (include_level > 10) {
  7360. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7361. return;
  7362. }
  7363. in_ssi_tag = len = offset = 0;
  7364. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7365. if (in_ssi_tag && ch == '>') {
  7366. in_ssi_tag = 0;
  7367. buf[len++] = (char)ch;
  7368. buf[len] = '\0';
  7369. /* assert(len <= (int) sizeof(buf)); */
  7370. if (len > (int)sizeof(buf)) {
  7371. break;
  7372. }
  7373. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7374. /* Not an SSI tag, pass it */
  7375. (void)mg_write(conn, buf, (size_t)len);
  7376. } else {
  7377. if (!memcmp(buf + 5, "include", 7)) {
  7378. do_ssi_include(conn, path, buf + 12, include_level);
  7379. #if !defined(NO_POPEN)
  7380. } else if (!memcmp(buf + 5, "exec", 4)) {
  7381. do_ssi_exec(conn, buf + 9);
  7382. #endif /* !NO_POPEN */
  7383. } else {
  7384. mg_cry(conn,
  7385. "%s: unknown SSI "
  7386. "command: \"%s\"",
  7387. path,
  7388. buf);
  7389. }
  7390. }
  7391. len = 0;
  7392. } else if (in_ssi_tag) {
  7393. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7394. /* Not an SSI tag */
  7395. in_ssi_tag = 0;
  7396. } else if (len == (int)sizeof(buf) - 2) {
  7397. mg_cry(conn, "%s: SSI tag is too large", path);
  7398. len = 0;
  7399. }
  7400. buf[len++] = (char)(ch & 0xff);
  7401. } else if (ch == '<') {
  7402. in_ssi_tag = 1;
  7403. if (len > 0) {
  7404. mg_write(conn, buf, (size_t)len);
  7405. }
  7406. len = 0;
  7407. buf[len++] = (char)(ch & 0xff);
  7408. } else {
  7409. buf[len++] = (char)(ch & 0xff);
  7410. if (len == (int)sizeof(buf)) {
  7411. mg_write(conn, buf, (size_t)len);
  7412. len = 0;
  7413. }
  7414. }
  7415. }
  7416. /* Send the rest of buffered data */
  7417. if (len > 0) {
  7418. mg_write(conn, buf, (size_t)len);
  7419. }
  7420. }
  7421. static void
  7422. handle_ssi_file_request(struct mg_connection *conn,
  7423. const char *path,
  7424. struct file *filep)
  7425. {
  7426. char date[64];
  7427. time_t curtime = time(NULL);
  7428. const char *cors1, *cors2, *cors3;
  7429. if (conn == NULL || path == NULL || filep == NULL) {
  7430. return;
  7431. }
  7432. if (mg_get_header(conn, "Origin")) {
  7433. /* Cross-origin resource sharing (CORS). */
  7434. cors1 = "Access-Control-Allow-Origin: ";
  7435. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7436. cors3 = "\r\n";
  7437. } else {
  7438. cors1 = cors2 = cors3 = "";
  7439. }
  7440. if (!mg_fopen(conn, path, "rb", filep)) {
  7441. /* File exists (precondition for calling this function),
  7442. * but can not be opened by the server. */
  7443. send_http_error(conn,
  7444. 500,
  7445. "Error: Cannot read file\nfopen(%s): %s",
  7446. path,
  7447. strerror(ERRNO));
  7448. } else {
  7449. conn->must_close = 1;
  7450. gmt_time_string(date, sizeof(date), &curtime);
  7451. fclose_on_exec(filep, conn);
  7452. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7453. send_no_cache_header(conn);
  7454. mg_printf(conn,
  7455. "%s%s%s"
  7456. "Date: %s\r\n"
  7457. "Content-Type: text/html\r\n"
  7458. "Connection: %s\r\n\r\n",
  7459. cors1,
  7460. cors2,
  7461. cors3,
  7462. date,
  7463. suggest_connection_header(conn));
  7464. send_ssi_file(conn, path, filep, 0);
  7465. mg_fclose(filep);
  7466. }
  7467. }
  7468. #if !defined(NO_FILES)
  7469. static void
  7470. send_options(struct mg_connection *conn)
  7471. {
  7472. char date[64];
  7473. time_t curtime = time(NULL);
  7474. if (!conn) {
  7475. return;
  7476. }
  7477. conn->status_code = 200;
  7478. conn->must_close = 1;
  7479. gmt_time_string(date, sizeof(date), &curtime);
  7480. mg_printf(conn,
  7481. "HTTP/1.1 200 OK\r\n"
  7482. "Date: %s\r\n"
  7483. /* TODO: "Cache-Control" (?) */
  7484. "Connection: %s\r\n"
  7485. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7486. "PROPFIND, MKCOL\r\n"
  7487. "DAV: 1\r\n\r\n",
  7488. date,
  7489. suggest_connection_header(conn));
  7490. }
  7491. /* Writes PROPFIND properties for a collection element */
  7492. static void
  7493. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7494. {
  7495. char mtime[64];
  7496. if (conn == NULL || uri == NULL || filep == NULL) {
  7497. return;
  7498. }
  7499. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7500. conn->num_bytes_sent +=
  7501. mg_printf(conn,
  7502. "<d:response>"
  7503. "<d:href>%s</d:href>"
  7504. "<d:propstat>"
  7505. "<d:prop>"
  7506. "<d:resourcetype>%s</d:resourcetype>"
  7507. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7508. "<d:getlastmodified>%s</d:getlastmodified>"
  7509. "</d:prop>"
  7510. "<d:status>HTTP/1.1 200 OK</d:status>"
  7511. "</d:propstat>"
  7512. "</d:response>\n",
  7513. uri,
  7514. filep->is_directory ? "<d:collection/>" : "",
  7515. filep->size,
  7516. mtime);
  7517. }
  7518. static void
  7519. print_dav_dir_entry(struct de *de, void *data)
  7520. {
  7521. char href[PATH_MAX];
  7522. char href_encoded[PATH_MAX * 3 /* worst case */];
  7523. int truncated;
  7524. struct mg_connection *conn = (struct mg_connection *)data;
  7525. if (!de || !conn) {
  7526. return;
  7527. }
  7528. mg_snprintf(conn,
  7529. &truncated,
  7530. href,
  7531. sizeof(href),
  7532. "%s%s",
  7533. conn->request_info.local_uri,
  7534. de->file_name);
  7535. if (!truncated) {
  7536. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7537. print_props(conn, href_encoded, &de->file);
  7538. }
  7539. }
  7540. static void
  7541. handle_propfind(struct mg_connection *conn,
  7542. const char *path,
  7543. struct file *filep)
  7544. {
  7545. const char *depth = mg_get_header(conn, "Depth");
  7546. char date[64];
  7547. time_t curtime = time(NULL);
  7548. gmt_time_string(date, sizeof(date), &curtime);
  7549. if (!conn || !path || !filep || !conn->ctx) {
  7550. return;
  7551. }
  7552. conn->must_close = 1;
  7553. conn->status_code = 207;
  7554. mg_printf(conn,
  7555. "HTTP/1.1 207 Multi-Status\r\n"
  7556. "Date: %s\r\n",
  7557. date);
  7558. send_static_cache_header(conn);
  7559. mg_printf(conn,
  7560. "Connection: %s\r\n"
  7561. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7562. suggest_connection_header(conn));
  7563. conn->num_bytes_sent +=
  7564. mg_printf(conn,
  7565. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7566. "<d:multistatus xmlns:d='DAV:'>\n");
  7567. /* Print properties for the requested resource itself */
  7568. print_props(conn, conn->request_info.local_uri, filep);
  7569. /* If it is a directory, print directory entries too if Depth is not 0 */
  7570. if (filep && filep->is_directory
  7571. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7572. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7573. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7574. }
  7575. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7576. }
  7577. #endif
  7578. void
  7579. mg_lock_connection(struct mg_connection *conn)
  7580. {
  7581. if (conn) {
  7582. (void)pthread_mutex_lock(&conn->mutex);
  7583. }
  7584. }
  7585. void
  7586. mg_unlock_connection(struct mg_connection *conn)
  7587. {
  7588. if (conn) {
  7589. (void)pthread_mutex_unlock(&conn->mutex);
  7590. }
  7591. }
  7592. void
  7593. mg_lock_context(struct mg_context *ctx)
  7594. {
  7595. if (ctx) {
  7596. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7597. }
  7598. }
  7599. void
  7600. mg_unlock_context(struct mg_context *ctx)
  7601. {
  7602. if (ctx) {
  7603. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7604. }
  7605. }
  7606. #if defined(USE_TIMERS)
  7607. #include "timer.inl"
  7608. #endif /* USE_TIMERS */
  7609. #ifdef USE_LUA
  7610. #include "mod_lua.inl"
  7611. #endif /* USE_LUA */
  7612. #ifdef USE_DUKTAPE
  7613. #include "mod_duktape.inl"
  7614. #endif /* USE_DUKTAPE */
  7615. #if defined(USE_WEBSOCKET)
  7616. /* START OF SHA-1 code
  7617. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7618. #define SHA1HANDSOFF
  7619. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7620. *
  7621. * #if defined(__sun)
  7622. * #include "solarisfixes.h"
  7623. * #endif
  7624. */
  7625. static int
  7626. is_big_endian(void)
  7627. {
  7628. static const int n = 1;
  7629. return ((char *)&n)[0] == 0;
  7630. }
  7631. union char64long16 {
  7632. unsigned char c[64];
  7633. uint32_t l[16];
  7634. };
  7635. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7636. static uint32_t
  7637. blk0(union char64long16 *block, int i)
  7638. {
  7639. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7640. if (!is_big_endian()) {
  7641. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7642. | (rol(block->l[i], 8) & 0x00FF00FF);
  7643. }
  7644. return block->l[i];
  7645. }
  7646. #define blk(i) \
  7647. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7648. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7649. 1))
  7650. #define R0(v, w, x, y, z, i) \
  7651. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7652. w = rol(w, 30);
  7653. #define R1(v, w, x, y, z, i) \
  7654. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7655. w = rol(w, 30);
  7656. #define R2(v, w, x, y, z, i) \
  7657. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7658. w = rol(w, 30);
  7659. #define R3(v, w, x, y, z, i) \
  7660. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7661. w = rol(w, 30);
  7662. #define R4(v, w, x, y, z, i) \
  7663. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7664. w = rol(w, 30);
  7665. typedef struct {
  7666. uint32_t state[5];
  7667. uint32_t count[2];
  7668. unsigned char buffer[64];
  7669. } SHA1_CTX;
  7670. static void
  7671. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7672. {
  7673. uint32_t a, b, c, d, e;
  7674. union char64long16 block[1];
  7675. memcpy(block, buffer, 64);
  7676. a = state[0];
  7677. b = state[1];
  7678. c = state[2];
  7679. d = state[3];
  7680. e = state[4];
  7681. R0(a, b, c, d, e, 0);
  7682. R0(e, a, b, c, d, 1);
  7683. R0(d, e, a, b, c, 2);
  7684. R0(c, d, e, a, b, 3);
  7685. R0(b, c, d, e, a, 4);
  7686. R0(a, b, c, d, e, 5);
  7687. R0(e, a, b, c, d, 6);
  7688. R0(d, e, a, b, c, 7);
  7689. R0(c, d, e, a, b, 8);
  7690. R0(b, c, d, e, a, 9);
  7691. R0(a, b, c, d, e, 10);
  7692. R0(e, a, b, c, d, 11);
  7693. R0(d, e, a, b, c, 12);
  7694. R0(c, d, e, a, b, 13);
  7695. R0(b, c, d, e, a, 14);
  7696. R0(a, b, c, d, e, 15);
  7697. R1(e, a, b, c, d, 16);
  7698. R1(d, e, a, b, c, 17);
  7699. R1(c, d, e, a, b, 18);
  7700. R1(b, c, d, e, a, 19);
  7701. R2(a, b, c, d, e, 20);
  7702. R2(e, a, b, c, d, 21);
  7703. R2(d, e, a, b, c, 22);
  7704. R2(c, d, e, a, b, 23);
  7705. R2(b, c, d, e, a, 24);
  7706. R2(a, b, c, d, e, 25);
  7707. R2(e, a, b, c, d, 26);
  7708. R2(d, e, a, b, c, 27);
  7709. R2(c, d, e, a, b, 28);
  7710. R2(b, c, d, e, a, 29);
  7711. R2(a, b, c, d, e, 30);
  7712. R2(e, a, b, c, d, 31);
  7713. R2(d, e, a, b, c, 32);
  7714. R2(c, d, e, a, b, 33);
  7715. R2(b, c, d, e, a, 34);
  7716. R2(a, b, c, d, e, 35);
  7717. R2(e, a, b, c, d, 36);
  7718. R2(d, e, a, b, c, 37);
  7719. R2(c, d, e, a, b, 38);
  7720. R2(b, c, d, e, a, 39);
  7721. R3(a, b, c, d, e, 40);
  7722. R3(e, a, b, c, d, 41);
  7723. R3(d, e, a, b, c, 42);
  7724. R3(c, d, e, a, b, 43);
  7725. R3(b, c, d, e, a, 44);
  7726. R3(a, b, c, d, e, 45);
  7727. R3(e, a, b, c, d, 46);
  7728. R3(d, e, a, b, c, 47);
  7729. R3(c, d, e, a, b, 48);
  7730. R3(b, c, d, e, a, 49);
  7731. R3(a, b, c, d, e, 50);
  7732. R3(e, a, b, c, d, 51);
  7733. R3(d, e, a, b, c, 52);
  7734. R3(c, d, e, a, b, 53);
  7735. R3(b, c, d, e, a, 54);
  7736. R3(a, b, c, d, e, 55);
  7737. R3(e, a, b, c, d, 56);
  7738. R3(d, e, a, b, c, 57);
  7739. R3(c, d, e, a, b, 58);
  7740. R3(b, c, d, e, a, 59);
  7741. R4(a, b, c, d, e, 60);
  7742. R4(e, a, b, c, d, 61);
  7743. R4(d, e, a, b, c, 62);
  7744. R4(c, d, e, a, b, 63);
  7745. R4(b, c, d, e, a, 64);
  7746. R4(a, b, c, d, e, 65);
  7747. R4(e, a, b, c, d, 66);
  7748. R4(d, e, a, b, c, 67);
  7749. R4(c, d, e, a, b, 68);
  7750. R4(b, c, d, e, a, 69);
  7751. R4(a, b, c, d, e, 70);
  7752. R4(e, a, b, c, d, 71);
  7753. R4(d, e, a, b, c, 72);
  7754. R4(c, d, e, a, b, 73);
  7755. R4(b, c, d, e, a, 74);
  7756. R4(a, b, c, d, e, 75);
  7757. R4(e, a, b, c, d, 76);
  7758. R4(d, e, a, b, c, 77);
  7759. R4(c, d, e, a, b, 78);
  7760. R4(b, c, d, e, a, 79);
  7761. state[0] += a;
  7762. state[1] += b;
  7763. state[2] += c;
  7764. state[3] += d;
  7765. state[4] += e;
  7766. a = b = c = d = e = 0;
  7767. memset(block, '\0', sizeof(block));
  7768. }
  7769. static void
  7770. SHA1Init(SHA1_CTX *context)
  7771. {
  7772. context->state[0] = 0x67452301;
  7773. context->state[1] = 0xEFCDAB89;
  7774. context->state[2] = 0x98BADCFE;
  7775. context->state[3] = 0x10325476;
  7776. context->state[4] = 0xC3D2E1F0;
  7777. context->count[0] = context->count[1] = 0;
  7778. }
  7779. static void
  7780. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7781. {
  7782. uint32_t i, j;
  7783. j = context->count[0];
  7784. if ((context->count[0] += len << 3) < j) {
  7785. context->count[1]++;
  7786. }
  7787. context->count[1] += (len >> 29);
  7788. j = (j >> 3) & 63;
  7789. if ((j + len) > 63) {
  7790. memcpy(&context->buffer[j], data, (i = 64 - j));
  7791. SHA1Transform(context->state, context->buffer);
  7792. for (; i + 63 < len; i += 64) {
  7793. SHA1Transform(context->state, &data[i]);
  7794. }
  7795. j = 0;
  7796. } else
  7797. i = 0;
  7798. memcpy(&context->buffer[j], &data[i], len - i);
  7799. }
  7800. static void
  7801. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7802. {
  7803. unsigned i;
  7804. unsigned char finalcount[8], c;
  7805. for (i = 0; i < 8; i++) {
  7806. finalcount[i] = (unsigned char)((context->count[(i >= 4) ? 0 : 1]
  7807. >> ((3 - (i & 3)) * 8)) & 255);
  7808. }
  7809. c = 0200;
  7810. SHA1Update(context, &c, 1);
  7811. while ((context->count[0] & 504) != 448) {
  7812. c = 0000;
  7813. SHA1Update(context, &c, 1);
  7814. }
  7815. SHA1Update(context, finalcount, 8);
  7816. for (i = 0; i < 20; i++) {
  7817. digest[i] = (unsigned char)((context->state[i >> 2]
  7818. >> ((3 - (i & 3)) * 8)) & 255);
  7819. }
  7820. memset(context, '\0', sizeof(*context));
  7821. memset(&finalcount, '\0', sizeof(finalcount));
  7822. }
  7823. /* END OF SHA1 CODE */
  7824. static int
  7825. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7826. {
  7827. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7828. const char *protocol = NULL;
  7829. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7830. SHA1_CTX sha_ctx;
  7831. int truncated;
  7832. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7833. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7834. if (truncated) {
  7835. conn->must_close = 1;
  7836. return 0;
  7837. }
  7838. SHA1Init(&sha_ctx);
  7839. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7840. SHA1Final((unsigned char *)sha, &sha_ctx);
  7841. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7842. mg_printf(conn,
  7843. "HTTP/1.1 101 Switching Protocols\r\n"
  7844. "Upgrade: websocket\r\n"
  7845. "Connection: Upgrade\r\n"
  7846. "Sec-WebSocket-Accept: %s\r\n",
  7847. b64_sha);
  7848. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7849. if (protocol) {
  7850. /* The protocol is a comma seperated list of names. */
  7851. /* The server must only return one value from this list. */
  7852. /* First check if it is a list or just a single value. */
  7853. const char *sep = strchr(protocol, ',');
  7854. if (sep == NULL) {
  7855. /* Just a single protocol -> accept it. */
  7856. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7857. } else {
  7858. /* Multiple protocols -> accept the first one. */
  7859. /* This is just a quick fix if the client offers multiple
  7860. * protocols. In order to get the behavior intended by
  7861. * RFC 6455 (https://tools.ietf.org/rfc/rfc6455.txt), it is
  7862. * required to have a list of websocket subprotocols accepted
  7863. * by the server. Then the server must either select a subprotocol
  7864. * supported by client and server, or the server has to abort the
  7865. * handshake by not returning a Sec-Websocket-Protocol header if
  7866. * no subprotocol is acceptable.
  7867. */
  7868. mg_printf(conn,
  7869. "Sec-WebSocket-Protocol: %.*s\r\n\r\n",
  7870. (int)(sep - protocol),
  7871. protocol);
  7872. }
  7873. /* TODO: Real subprotocol negotiation instead of just taking the first
  7874. * websocket subprotocol suggested by the client. */
  7875. } else {
  7876. mg_printf(conn, "%s", "\r\n");
  7877. }
  7878. return 1;
  7879. }
  7880. static void
  7881. read_websocket(struct mg_connection *conn,
  7882. mg_websocket_data_handler ws_data_handler,
  7883. void *callback_data)
  7884. {
  7885. /* Pointer to the beginning of the portion of the incoming websocket
  7886. * message queue.
  7887. * The original websocket upgrade request is never removed, so the queue
  7888. * begins after it. */
  7889. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7890. int n, error, exit_by_callback;
  7891. /* body_len is the length of the entire queue in bytes
  7892. * len is the length of the current message
  7893. * data_len is the length of the current message's data payload
  7894. * header_len is the length of the current message's header */
  7895. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7896. /* "The masking key is a 32-bit value chosen at random by the client."
  7897. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7898. */
  7899. unsigned char mask[4];
  7900. /* data points to the place where the message is stored when passed to
  7901. * the
  7902. * websocket_data callback. This is either mem on the stack, or a
  7903. * dynamically allocated buffer if it is too large. */
  7904. char mem[4096];
  7905. char *data = mem;
  7906. unsigned char mop; /* mask flag and opcode */
  7907. double timeout = -1.0;
  7908. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7909. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7910. }
  7911. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7912. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7913. }
  7914. mg_set_thread_name("wsock");
  7915. /* Loop continuously, reading messages from the socket, invoking the
  7916. * callback, and waiting repeatedly until an error occurs. */
  7917. while (!conn->ctx->stop_flag) {
  7918. header_len = 0;
  7919. assert(conn->data_len >= conn->request_len);
  7920. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7921. len = buf[1] & 127;
  7922. mask_len = (buf[1] & 128) ? 4 : 0;
  7923. if ((len < 126) && (body_len >= mask_len)) {
  7924. data_len = len;
  7925. header_len = 2 + mask_len;
  7926. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  7927. header_len = 4 + mask_len;
  7928. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7929. } else if (body_len >= (10 + mask_len)) {
  7930. header_len = 10 + mask_len;
  7931. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7932. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7933. }
  7934. }
  7935. if (header_len > 0 && body_len >= header_len) {
  7936. /* Allocate space to hold websocket payload */
  7937. data = mem;
  7938. if (data_len > sizeof(mem)) {
  7939. data = (char *)mg_malloc(data_len);
  7940. if (data == NULL) {
  7941. /* Allocation failed, exit the loop and then close the
  7942. * connection */
  7943. mg_cry(conn, "websocket out of memory; closing connection");
  7944. break;
  7945. }
  7946. }
  7947. /* Copy the mask before we shift the queue and destroy it */
  7948. if (mask_len > 0) {
  7949. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7950. } else {
  7951. memset(mask, 0, sizeof(mask));
  7952. }
  7953. /* Read frame payload from the first message in the queue into
  7954. * data and advance the queue by moving the memory in place. */
  7955. assert(body_len >= header_len);
  7956. if (data_len + header_len > body_len) {
  7957. mop = buf[0]; /* current mask and opcode */
  7958. /* Overflow case */
  7959. len = body_len - header_len;
  7960. memcpy(data, buf + header_len, len);
  7961. error = 0;
  7962. while (len < data_len) {
  7963. n = pull(
  7964. NULL, conn, data + len, (int)(data_len - len), timeout);
  7965. if (n <= 0) {
  7966. error = 1;
  7967. break;
  7968. }
  7969. len += (size_t)n;
  7970. }
  7971. if (error) {
  7972. mg_cry(conn, "Websocket pull failed; closing connection");
  7973. break;
  7974. }
  7975. conn->data_len = conn->request_len;
  7976. } else {
  7977. mop = buf[0]; /* current mask and opcode, overwritten by
  7978. * memmove() */
  7979. /* Length of the message being read at the front of the
  7980. * queue */
  7981. len = data_len + header_len;
  7982. /* Copy the data payload into the data pointer for the
  7983. * callback */
  7984. memcpy(data, buf + header_len, data_len);
  7985. /* Move the queue forward len bytes */
  7986. memmove(buf, buf + len, body_len - len);
  7987. /* Mark the queue as advanced */
  7988. conn->data_len -= (int)len;
  7989. }
  7990. /* Apply mask if necessary */
  7991. if (mask_len > 0) {
  7992. for (i = 0; i < data_len; ++i) {
  7993. data[i] ^= mask[i & 3];
  7994. }
  7995. }
  7996. /* Exit the loop if callback signals to exit (server side),
  7997. * or "connection close" opcode received (client side). */
  7998. exit_by_callback = 0;
  7999. if ((ws_data_handler != NULL)
  8000. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  8001. exit_by_callback = 1;
  8002. }
  8003. if (data != mem) {
  8004. mg_free(data);
  8005. }
  8006. if (exit_by_callback
  8007. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8008. /* Opcode == 8, connection close */
  8009. break;
  8010. }
  8011. /* Not breaking the loop, process next websocket frame. */
  8012. } else {
  8013. /* Read from the socket into the next available location in the
  8014. * message queue. */
  8015. if ((n = pull(NULL,
  8016. conn,
  8017. conn->buf + conn->data_len,
  8018. conn->buf_size - conn->data_len,
  8019. timeout)) <= 0) {
  8020. /* Error, no bytes read */
  8021. break;
  8022. }
  8023. conn->data_len += n;
  8024. }
  8025. }
  8026. mg_set_thread_name("worker");
  8027. }
  8028. static int
  8029. mg_websocket_write_exec(struct mg_connection *conn,
  8030. int opcode,
  8031. const char *data,
  8032. size_t dataLen,
  8033. uint32_t masking_key)
  8034. {
  8035. unsigned char header[14];
  8036. size_t headerLen = 1;
  8037. int retval = -1;
  8038. header[0] = 0x80 + (opcode & 0xF);
  8039. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8040. if (dataLen < 126) {
  8041. /* inline 7-bit length field */
  8042. header[1] = (unsigned char)dataLen;
  8043. headerLen = 2;
  8044. } else if (dataLen <= 0xFFFF) {
  8045. /* 16-bit length field */
  8046. uint16_t len = htons((uint16_t)dataLen);
  8047. header[1] = 126;
  8048. memcpy(header + 2, &len, 2);
  8049. headerLen = 4;
  8050. } else {
  8051. /* 64-bit length field */
  8052. uint32_t len1 = htonl((uint64_t)dataLen >> 32);
  8053. uint32_t len2 = htonl(dataLen & 0xFFFFFFFF);
  8054. header[1] = 127;
  8055. memcpy(header + 2, &len1, 4);
  8056. memcpy(header + 6, &len2, 4);
  8057. headerLen = 10;
  8058. }
  8059. if (masking_key) {
  8060. /* add mask */
  8061. header[1] |= 0x80;
  8062. memcpy(header + headerLen, &masking_key, 4);
  8063. headerLen += 4;
  8064. }
  8065. /* Note that POSIX/Winsock's send() is threadsafe
  8066. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8067. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8068. * push(), although that is only a problem if the packet is large or
  8069. * outgoing buffer is full). */
  8070. (void)mg_lock_connection(conn);
  8071. retval = mg_write(conn, header, headerLen);
  8072. if (dataLen > 0) {
  8073. retval = mg_write(conn, data, dataLen);
  8074. }
  8075. mg_unlock_connection(conn);
  8076. return retval;
  8077. }
  8078. int
  8079. mg_websocket_write(struct mg_connection *conn,
  8080. int opcode,
  8081. const char *data,
  8082. size_t dataLen)
  8083. {
  8084. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8085. }
  8086. static void
  8087. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8088. {
  8089. size_t i = 0;
  8090. i = 0;
  8091. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8092. /* Convert in 32 bit words, if data is 4 byte aligned */
  8093. while (i < (in_len - 3)) {
  8094. *(uint32_t *)(void *)(out + i) =
  8095. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8096. i += 4;
  8097. }
  8098. }
  8099. if (i != in_len) {
  8100. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8101. while (i < in_len) {
  8102. *(uint8_t *)(void *)(out + i) =
  8103. *(uint8_t *)(void *)(in + i)
  8104. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8105. i++;
  8106. }
  8107. }
  8108. }
  8109. int
  8110. mg_websocket_client_write(struct mg_connection *conn,
  8111. int opcode,
  8112. const char *data,
  8113. size_t dataLen)
  8114. {
  8115. int retval = -1;
  8116. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8117. uint32_t masking_key = (uint32_t)get_random();
  8118. if (masked_data == NULL) {
  8119. /* Return -1 in an error case */
  8120. mg_cry(conn,
  8121. "Cannot allocate buffer for masked websocket response: "
  8122. "Out of memory");
  8123. return -1;
  8124. }
  8125. mask_data(data, dataLen, masking_key, masked_data);
  8126. retval = mg_websocket_write_exec(
  8127. conn, opcode, masked_data, dataLen, masking_key);
  8128. mg_free(masked_data);
  8129. return retval;
  8130. }
  8131. static void
  8132. handle_websocket_request(struct mg_connection *conn,
  8133. const char *path,
  8134. int is_callback_resource,
  8135. mg_websocket_connect_handler ws_connect_handler,
  8136. mg_websocket_ready_handler ws_ready_handler,
  8137. mg_websocket_data_handler ws_data_handler,
  8138. mg_websocket_close_handler ws_close_handler,
  8139. void *cbData)
  8140. {
  8141. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8142. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8143. int lua_websock = 0;
  8144. #if !defined(USE_LUA)
  8145. (void)path;
  8146. #endif
  8147. /* Step 1: Check websocket protocol version. */
  8148. /* Step 1.1: Check Sec-WebSocket-Key. */
  8149. if (!websock_key) {
  8150. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8151. * requires a Sec-WebSocket-Key header.
  8152. */
  8153. /* It could be the hixie draft version
  8154. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8155. */
  8156. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8157. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8158. char key3[8];
  8159. if ((key1 != NULL) && (key2 != NULL)) {
  8160. /* This version uses 8 byte body data in a GET request */
  8161. conn->content_len = 8;
  8162. if (8 == mg_read(conn, key3, 8)) {
  8163. /* This is the hixie version */
  8164. send_http_error(conn,
  8165. 426,
  8166. "%s",
  8167. "Protocol upgrade to RFC 6455 required");
  8168. return;
  8169. }
  8170. }
  8171. /* This is an unknown version */
  8172. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8173. return;
  8174. }
  8175. /* Step 1.2: Check websocket protocol version. */
  8176. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8177. if (version == NULL || strcmp(version, "13") != 0) {
  8178. /* Reject wrong versions */
  8179. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8180. return;
  8181. }
  8182. /* Step 1.3: Could check for "Host", but we do not really nead this
  8183. * value for anything, so just ignore it. */
  8184. /* Step 2: If a callback is responsible, call it. */
  8185. if (is_callback_resource) {
  8186. if (ws_connect_handler != NULL
  8187. && ws_connect_handler(conn, cbData) != 0) {
  8188. /* C callback has returned non-zero, do not proceed with
  8189. * handshake.
  8190. */
  8191. /* Note that C callbacks are no longer called when Lua is
  8192. * responsible, so C can no longer filter callbacks for Lua. */
  8193. return;
  8194. }
  8195. }
  8196. #if defined(USE_LUA)
  8197. /* Step 3: No callback. Check if Lua is responsible. */
  8198. else {
  8199. /* Step 3.1: Check if Lua is responsible. */
  8200. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8201. lua_websock =
  8202. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8203. strlen(
  8204. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8205. path);
  8206. }
  8207. if (lua_websock) {
  8208. /* Step 3.2: Lua is responsible: call it. */
  8209. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8210. if (!conn->lua_websocket_state) {
  8211. /* Lua rejected the new client */
  8212. return;
  8213. }
  8214. }
  8215. }
  8216. #endif
  8217. /* Step 4: Check if there is a responsible websocket handler. */
  8218. if (!is_callback_resource && !lua_websock) {
  8219. /* There is no callback, an Lua is not responsible either. */
  8220. /* Reply with a 404 Not Found or with nothing at all?
  8221. * TODO (mid): check the websocket standards, how to reply to
  8222. * requests to invalid websocket addresses. */
  8223. send_http_error(conn, 404, "%s", "Not found");
  8224. return;
  8225. }
  8226. /* Step 5: The websocket connection has been accepted */
  8227. if (!send_websocket_handshake(conn, websock_key)) {
  8228. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8229. return;
  8230. }
  8231. /* Step 6: Call the ready handler */
  8232. if (is_callback_resource) {
  8233. if (ws_ready_handler != NULL) {
  8234. ws_ready_handler(conn, cbData);
  8235. }
  8236. #if defined(USE_LUA)
  8237. } else if (lua_websock) {
  8238. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8239. /* the ready handler returned false */
  8240. return;
  8241. }
  8242. #endif
  8243. }
  8244. /* Step 7: Enter the read loop */
  8245. if (is_callback_resource) {
  8246. read_websocket(conn, ws_data_handler, cbData);
  8247. #if defined(USE_LUA)
  8248. } else if (lua_websock) {
  8249. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8250. #endif
  8251. }
  8252. /* Step 8: Call the close handler */
  8253. if (ws_close_handler) {
  8254. ws_close_handler(conn, cbData);
  8255. }
  8256. }
  8257. static int
  8258. is_websocket_protocol(const struct mg_connection *conn)
  8259. {
  8260. const char *upgrade, *connection;
  8261. /* A websocket protocoll has the following HTTP headers:
  8262. *
  8263. * Connection: Upgrade
  8264. * Upgrade: Websocket
  8265. */
  8266. upgrade = mg_get_header(conn, "Upgrade");
  8267. if (upgrade == NULL) {
  8268. return 0; /* fail early, don't waste time checking other header
  8269. * fields
  8270. */
  8271. }
  8272. if (!mg_strcasestr(upgrade, "websocket")) {
  8273. return 0;
  8274. }
  8275. connection = mg_get_header(conn, "Connection");
  8276. if (connection == NULL) {
  8277. return 0;
  8278. }
  8279. if (!mg_strcasestr(connection, "upgrade")) {
  8280. return 0;
  8281. }
  8282. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8283. * "Sec-WebSocket-Version" are also required.
  8284. * Don't check them here, since even an unsupported websocket protocol
  8285. * request still IS a websocket request (in contrast to a standard HTTP
  8286. * request). It will fail later in handle_websocket_request.
  8287. */
  8288. return 1;
  8289. }
  8290. #endif /* !USE_WEBSOCKET */
  8291. static int
  8292. isbyte(int n)
  8293. {
  8294. return n >= 0 && n <= 255;
  8295. }
  8296. static int
  8297. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8298. {
  8299. int n, a, b, c, d, slash = 32, len = 0;
  8300. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8301. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8302. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8303. && slash < 33) {
  8304. len = n;
  8305. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8306. | (uint32_t)d;
  8307. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8308. }
  8309. return len;
  8310. }
  8311. static int
  8312. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8313. {
  8314. int throttle = 0;
  8315. struct vec vec, val;
  8316. uint32_t net, mask;
  8317. char mult;
  8318. double v;
  8319. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8320. mult = ',';
  8321. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  8322. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  8323. && mult != ',')) {
  8324. continue;
  8325. }
  8326. v *= (lowercase(&mult) == 'k')
  8327. ? 1024
  8328. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8329. if (vec.len == 1 && vec.ptr[0] == '*') {
  8330. throttle = (int)v;
  8331. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8332. if ((remote_ip & mask) == net) {
  8333. throttle = (int)v;
  8334. }
  8335. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8336. throttle = (int)v;
  8337. }
  8338. }
  8339. return throttle;
  8340. }
  8341. static uint32_t
  8342. get_remote_ip(const struct mg_connection *conn)
  8343. {
  8344. if (!conn) {
  8345. return 0;
  8346. }
  8347. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8348. }
  8349. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8350. #include "handle_form.inl"
  8351. #if defined(MG_LEGACY_INTERFACE)
  8352. /* Implement the deprecated mg_upload function by calling the new
  8353. * mg_handle_form_request function. While mg_upload could only handle
  8354. * HTML forms sent as POST request in multipart/form-data format
  8355. * containing only file input elements, mg_handle_form_request can
  8356. * handle all form input elements and all standard request methods. */
  8357. struct mg_upload_user_data {
  8358. struct mg_connection *conn;
  8359. const char *destination_dir;
  8360. int num_uploaded_files;
  8361. };
  8362. /* Helper function for deprecated mg_upload. */
  8363. static int
  8364. mg_upload_field_found(const char *key,
  8365. const char *filename,
  8366. char *path,
  8367. size_t pathlen,
  8368. void *user_data)
  8369. {
  8370. int truncated = 0;
  8371. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8372. (void)key;
  8373. if (!filename) {
  8374. mg_cry(fud->conn, "%s: No filename set", __func__);
  8375. return FORM_FIELD_STORAGE_ABORT;
  8376. }
  8377. mg_snprintf(fud->conn,
  8378. &truncated,
  8379. path,
  8380. pathlen - 1,
  8381. "%s/%s",
  8382. fud->destination_dir,
  8383. filename);
  8384. if (!truncated) {
  8385. mg_cry(fud->conn, "%s: File path too long", __func__);
  8386. return FORM_FIELD_STORAGE_ABORT;
  8387. }
  8388. return FORM_FIELD_STORAGE_STORE;
  8389. }
  8390. /* Helper function for deprecated mg_upload. */
  8391. static int
  8392. mg_upload_field_get(const char *key,
  8393. const char *value,
  8394. size_t value_size,
  8395. void *user_data)
  8396. {
  8397. /* Function should never be called */
  8398. (void)key;
  8399. (void)value;
  8400. (void)value_size;
  8401. (void)user_data;
  8402. return 0;
  8403. }
  8404. /* Helper function for deprecated mg_upload. */
  8405. static int
  8406. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8407. {
  8408. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8409. (void)file_size;
  8410. fud->num_uploaded_files++;
  8411. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8412. return 0;
  8413. }
  8414. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8415. int
  8416. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8417. {
  8418. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8419. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8420. mg_upload_field_get,
  8421. mg_upload_field_stored,
  8422. 0};
  8423. int ret;
  8424. fdh.user_data = (void *)&fud;
  8425. ret = mg_handle_form_request(conn, &fdh);
  8426. if (ret < 0) {
  8427. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8428. }
  8429. return fud.num_uploaded_files;
  8430. }
  8431. #endif
  8432. static int
  8433. get_first_ssl_listener_index(const struct mg_context *ctx)
  8434. {
  8435. unsigned int i;
  8436. int idx = -1;
  8437. if (ctx) {
  8438. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8439. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8440. }
  8441. }
  8442. return idx;
  8443. }
  8444. static void
  8445. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8446. {
  8447. char host[1025];
  8448. const char *host_header;
  8449. size_t hostlen;
  8450. host_header = mg_get_header(conn, "Host");
  8451. hostlen = sizeof(host);
  8452. if (host_header != NULL) {
  8453. char *pos;
  8454. mg_strlcpy(host, host_header, hostlen);
  8455. host[hostlen - 1] = '\0';
  8456. pos = strchr(host, ':');
  8457. if (pos != NULL) {
  8458. *pos = '\0';
  8459. }
  8460. } else {
  8461. /* Cannot get host from the Host: header.
  8462. * Fallback to our IP address. */
  8463. if (conn) {
  8464. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8465. }
  8466. }
  8467. /* Send host, port, uri and (if it exists) ?query_string */
  8468. if (conn) {
  8469. mg_printf(conn,
  8470. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8471. host,
  8472. #if defined(USE_IPV6)
  8473. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8474. == AF_INET6)
  8475. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8476. .lsa.sin6.sin6_port)
  8477. :
  8478. #endif
  8479. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8480. .lsa.sin.sin_port),
  8481. conn->request_info.local_uri,
  8482. (conn->request_info.query_string == NULL) ? "" : "?",
  8483. (conn->request_info.query_string == NULL)
  8484. ? ""
  8485. : conn->request_info.query_string);
  8486. }
  8487. }
  8488. static void
  8489. mg_set_handler_type(struct mg_context *ctx,
  8490. const char *uri,
  8491. int handler_type,
  8492. int is_delete_request,
  8493. mg_request_handler handler,
  8494. mg_websocket_connect_handler connect_handler,
  8495. mg_websocket_ready_handler ready_handler,
  8496. mg_websocket_data_handler data_handler,
  8497. mg_websocket_close_handler close_handler,
  8498. mg_authorization_handler auth_handler,
  8499. void *cbdata)
  8500. {
  8501. struct mg_handler_info *tmp_rh, **lastref;
  8502. size_t urilen = strlen(uri);
  8503. if (handler_type == WEBSOCKET_HANDLER) {
  8504. /* assert(handler == NULL); */
  8505. /* assert(is_delete_request || connect_handler!=NULL ||
  8506. * ready_handler!=NULL || data_handler!=NULL ||
  8507. * close_handler!=NULL);
  8508. */
  8509. /* assert(auth_handler == NULL); */
  8510. if (handler != NULL) {
  8511. return;
  8512. }
  8513. if (!is_delete_request && connect_handler == NULL
  8514. && ready_handler == NULL
  8515. && data_handler == NULL
  8516. && close_handler == NULL) {
  8517. return;
  8518. }
  8519. if (auth_handler != NULL) {
  8520. return;
  8521. }
  8522. } else if (handler_type == REQUEST_HANDLER) {
  8523. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8524. * data_handler==NULL && close_handler==NULL); */
  8525. /* assert(is_delete_request || (handler!=NULL));
  8526. */
  8527. /* assert(auth_handler == NULL); */
  8528. if (connect_handler != NULL || ready_handler != NULL
  8529. || data_handler != NULL
  8530. || close_handler != NULL) {
  8531. return;
  8532. }
  8533. if (!is_delete_request && (handler == NULL)) {
  8534. return;
  8535. }
  8536. if (auth_handler != NULL) {
  8537. return;
  8538. }
  8539. } else { /* AUTH_HANDLER */
  8540. /* assert(handler == NULL); */
  8541. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8542. * data_handler==NULL && close_handler==NULL); */
  8543. /* assert(auth_handler != NULL); */
  8544. if (handler != NULL) {
  8545. return;
  8546. }
  8547. if (connect_handler != NULL || ready_handler != NULL
  8548. || data_handler != NULL
  8549. || close_handler != NULL) {
  8550. return;
  8551. }
  8552. if (!is_delete_request && (auth_handler == NULL)) {
  8553. return;
  8554. }
  8555. }
  8556. if (!ctx) {
  8557. return;
  8558. }
  8559. mg_lock_context(ctx);
  8560. /* first try to find an existing handler */
  8561. lastref = &(ctx->handlers);
  8562. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8563. if (tmp_rh->handler_type == handler_type) {
  8564. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8565. if (!is_delete_request) {
  8566. /* update existing handler */
  8567. if (handler_type == REQUEST_HANDLER) {
  8568. tmp_rh->handler = handler;
  8569. } else if (handler_type == WEBSOCKET_HANDLER) {
  8570. tmp_rh->connect_handler = connect_handler;
  8571. tmp_rh->ready_handler = ready_handler;
  8572. tmp_rh->data_handler = data_handler;
  8573. tmp_rh->close_handler = close_handler;
  8574. } else { /* AUTH_HANDLER */
  8575. tmp_rh->auth_handler = auth_handler;
  8576. }
  8577. tmp_rh->cbdata = cbdata;
  8578. } else {
  8579. /* remove existing handler */
  8580. *lastref = tmp_rh->next;
  8581. mg_free(tmp_rh->uri);
  8582. mg_free(tmp_rh);
  8583. }
  8584. mg_unlock_context(ctx);
  8585. return;
  8586. }
  8587. }
  8588. lastref = &(tmp_rh->next);
  8589. }
  8590. if (is_delete_request) {
  8591. /* no handler to set, this was a remove request to a non-existing
  8592. * handler */
  8593. mg_unlock_context(ctx);
  8594. return;
  8595. }
  8596. tmp_rh =
  8597. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8598. if (tmp_rh == NULL) {
  8599. mg_unlock_context(ctx);
  8600. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8601. return;
  8602. }
  8603. tmp_rh->uri = mg_strdup(uri);
  8604. if (!tmp_rh->uri) {
  8605. mg_unlock_context(ctx);
  8606. mg_free(tmp_rh);
  8607. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8608. return;
  8609. }
  8610. tmp_rh->uri_len = urilen;
  8611. if (handler_type == REQUEST_HANDLER) {
  8612. tmp_rh->handler = handler;
  8613. } else if (handler_type == WEBSOCKET_HANDLER) {
  8614. tmp_rh->connect_handler = connect_handler;
  8615. tmp_rh->ready_handler = ready_handler;
  8616. tmp_rh->data_handler = data_handler;
  8617. tmp_rh->close_handler = close_handler;
  8618. } else { /* AUTH_HANDLER */
  8619. tmp_rh->auth_handler = auth_handler;
  8620. }
  8621. tmp_rh->cbdata = cbdata;
  8622. tmp_rh->handler_type = handler_type;
  8623. tmp_rh->next = NULL;
  8624. *lastref = tmp_rh;
  8625. mg_unlock_context(ctx);
  8626. }
  8627. void
  8628. mg_set_request_handler(struct mg_context *ctx,
  8629. const char *uri,
  8630. mg_request_handler handler,
  8631. void *cbdata)
  8632. {
  8633. mg_set_handler_type(ctx,
  8634. uri,
  8635. REQUEST_HANDLER,
  8636. handler == NULL,
  8637. handler,
  8638. NULL,
  8639. NULL,
  8640. NULL,
  8641. NULL,
  8642. NULL,
  8643. cbdata);
  8644. }
  8645. void
  8646. mg_set_websocket_handler(struct mg_context *ctx,
  8647. const char *uri,
  8648. mg_websocket_connect_handler connect_handler,
  8649. mg_websocket_ready_handler ready_handler,
  8650. mg_websocket_data_handler data_handler,
  8651. mg_websocket_close_handler close_handler,
  8652. void *cbdata)
  8653. {
  8654. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8655. && (data_handler == NULL)
  8656. && (close_handler == NULL);
  8657. mg_set_handler_type(ctx,
  8658. uri,
  8659. WEBSOCKET_HANDLER,
  8660. is_delete_request,
  8661. NULL,
  8662. connect_handler,
  8663. ready_handler,
  8664. data_handler,
  8665. close_handler,
  8666. NULL,
  8667. cbdata);
  8668. }
  8669. void
  8670. mg_set_auth_handler(struct mg_context *ctx,
  8671. const char *uri,
  8672. mg_request_handler handler,
  8673. void *cbdata)
  8674. {
  8675. mg_set_handler_type(ctx,
  8676. uri,
  8677. AUTH_HANDLER,
  8678. handler == NULL,
  8679. NULL,
  8680. NULL,
  8681. NULL,
  8682. NULL,
  8683. NULL,
  8684. handler,
  8685. cbdata);
  8686. }
  8687. static int
  8688. get_request_handler(struct mg_connection *conn,
  8689. int handler_type,
  8690. mg_request_handler *handler,
  8691. mg_websocket_connect_handler *connect_handler,
  8692. mg_websocket_ready_handler *ready_handler,
  8693. mg_websocket_data_handler *data_handler,
  8694. mg_websocket_close_handler *close_handler,
  8695. mg_authorization_handler *auth_handler,
  8696. void **cbdata)
  8697. {
  8698. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8699. if (request_info) {
  8700. const char *uri = request_info->local_uri;
  8701. size_t urilen = strlen(uri);
  8702. struct mg_handler_info *tmp_rh;
  8703. if (!conn || !conn->ctx) {
  8704. return 0;
  8705. }
  8706. mg_lock_context(conn->ctx);
  8707. /* first try for an exact match */
  8708. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8709. tmp_rh = tmp_rh->next) {
  8710. if (tmp_rh->handler_type == handler_type) {
  8711. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8712. if (handler_type == WEBSOCKET_HANDLER) {
  8713. *connect_handler = tmp_rh->connect_handler;
  8714. *ready_handler = tmp_rh->ready_handler;
  8715. *data_handler = tmp_rh->data_handler;
  8716. *close_handler = tmp_rh->close_handler;
  8717. } else if (handler_type == REQUEST_HANDLER) {
  8718. *handler = tmp_rh->handler;
  8719. } else { /* AUTH_HANDLER */
  8720. *auth_handler = tmp_rh->auth_handler;
  8721. }
  8722. *cbdata = tmp_rh->cbdata;
  8723. mg_unlock_context(conn->ctx);
  8724. return 1;
  8725. }
  8726. }
  8727. }
  8728. /* next try for a partial match, we will accept uri/something */
  8729. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8730. tmp_rh = tmp_rh->next) {
  8731. if (tmp_rh->handler_type == handler_type) {
  8732. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8733. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8734. if (handler_type == WEBSOCKET_HANDLER) {
  8735. *connect_handler = tmp_rh->connect_handler;
  8736. *ready_handler = tmp_rh->ready_handler;
  8737. *data_handler = tmp_rh->data_handler;
  8738. *close_handler = tmp_rh->close_handler;
  8739. } else if (handler_type == REQUEST_HANDLER) {
  8740. *handler = tmp_rh->handler;
  8741. } else { /* AUTH_HANDLER */
  8742. *auth_handler = tmp_rh->auth_handler;
  8743. }
  8744. *cbdata = tmp_rh->cbdata;
  8745. mg_unlock_context(conn->ctx);
  8746. return 1;
  8747. }
  8748. }
  8749. }
  8750. /* finally try for pattern match */
  8751. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8752. tmp_rh = tmp_rh->next) {
  8753. if (tmp_rh->handler_type == handler_type) {
  8754. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8755. if (handler_type == WEBSOCKET_HANDLER) {
  8756. *connect_handler = tmp_rh->connect_handler;
  8757. *ready_handler = tmp_rh->ready_handler;
  8758. *data_handler = tmp_rh->data_handler;
  8759. *close_handler = tmp_rh->close_handler;
  8760. } else if (handler_type == REQUEST_HANDLER) {
  8761. *handler = tmp_rh->handler;
  8762. } else { /* AUTH_HANDLER */
  8763. *auth_handler = tmp_rh->auth_handler;
  8764. }
  8765. *cbdata = tmp_rh->cbdata;
  8766. mg_unlock_context(conn->ctx);
  8767. return 1;
  8768. }
  8769. }
  8770. }
  8771. mg_unlock_context(conn->ctx);
  8772. }
  8773. return 0; /* none found */
  8774. }
  8775. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8776. static int
  8777. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8778. void *cbdata)
  8779. {
  8780. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8781. if (pcallbacks->websocket_connect) {
  8782. return pcallbacks->websocket_connect(conn);
  8783. }
  8784. /* No handler set - assume "OK" */
  8785. return 0;
  8786. }
  8787. static void
  8788. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8789. {
  8790. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8791. if (pcallbacks->websocket_ready) {
  8792. pcallbacks->websocket_ready(conn);
  8793. }
  8794. }
  8795. static int
  8796. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8797. int bits,
  8798. char *data,
  8799. size_t len,
  8800. void *cbdata)
  8801. {
  8802. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8803. if (pcallbacks->websocket_data) {
  8804. return pcallbacks->websocket_data(conn, bits, data, len);
  8805. }
  8806. /* No handler set - assume "OK" */
  8807. return 1;
  8808. }
  8809. #endif
  8810. /* This is the heart of the Civetweb's logic.
  8811. * This function is called when the request is read, parsed and validated,
  8812. * and Civetweb must decide what action to take: serve a file, or
  8813. * a directory, or call embedded function, etcetera. */
  8814. static void
  8815. handle_request(struct mg_connection *conn)
  8816. {
  8817. if (conn) {
  8818. struct mg_request_info *ri = &conn->request_info;
  8819. char path[PATH_MAX];
  8820. int uri_len, ssl_index;
  8821. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8822. is_put_or_delete_request = 0, is_callback_resource = 0;
  8823. int i;
  8824. struct file file = STRUCT_FILE_INITIALIZER;
  8825. mg_request_handler callback_handler = NULL;
  8826. mg_websocket_connect_handler ws_connect_handler = NULL;
  8827. mg_websocket_ready_handler ws_ready_handler = NULL;
  8828. mg_websocket_data_handler ws_data_handler = NULL;
  8829. mg_websocket_close_handler ws_close_handler = NULL;
  8830. void *callback_data = NULL;
  8831. mg_authorization_handler auth_handler = NULL;
  8832. void *auth_callback_data = NULL;
  8833. #if !defined(NO_FILES)
  8834. time_t curtime = time(NULL);
  8835. char date[64];
  8836. #endif
  8837. path[0] = 0;
  8838. if (!ri) {
  8839. return;
  8840. }
  8841. /* 1. get the request url */
  8842. /* 1.1. split into url and query string */
  8843. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8844. != NULL) {
  8845. *((char *)conn->request_info.query_string++) = '\0';
  8846. }
  8847. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  8848. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8849. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8850. if (ssl_index >= 0) {
  8851. redirect_to_https_port(conn, ssl_index);
  8852. } else {
  8853. /* A http to https forward port has been specified,
  8854. * but no https port to forward to. */
  8855. send_http_error(conn,
  8856. 503,
  8857. "%s",
  8858. "Error: SSL forward not configured properly");
  8859. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8860. }
  8861. return;
  8862. }
  8863. uri_len = (int)strlen(ri->local_uri);
  8864. /* 1.3. decode url (if config says so) */
  8865. if (should_decode_url(conn)) {
  8866. mg_url_decode(
  8867. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8868. }
  8869. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  8870. * not possible */
  8871. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8872. /* step 1. completed, the url is known now */
  8873. uri_len = (int)strlen(ri->local_uri);
  8874. DEBUG_TRACE("URL: %s", ri->local_uri);
  8875. /* 3. if this ip has limited speed, set it for this connection */
  8876. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8877. get_remote_ip(conn),
  8878. ri->local_uri);
  8879. /* 4. call a "handle everything" callback, if registered */
  8880. if (conn->ctx->callbacks.begin_request != NULL) {
  8881. /* Note that since V1.7 the "begin_request" function is called
  8882. * before an authorization check. If an authorization check is
  8883. * required, use a request_handler instead. */
  8884. i = conn->ctx->callbacks.begin_request(conn);
  8885. if (i > 0) {
  8886. /* callback already processed the request. Store the
  8887. return value as a status code for the access log. */
  8888. conn->status_code = i;
  8889. return;
  8890. } else if (i == 0) {
  8891. /* civetweb should process the request */
  8892. } else {
  8893. /* unspecified - may change with the next version */
  8894. return;
  8895. }
  8896. }
  8897. /* request not yet handled by a handler or redirect, so the request
  8898. * is processed here */
  8899. /* 5. interpret the url to find out how the request must be handled
  8900. */
  8901. /* 5.1. first test, if the request targets the regular http(s)://
  8902. * protocol namespace or the websocket ws(s):// protocol namespace.
  8903. */
  8904. is_websocket_request = is_websocket_protocol(conn);
  8905. /* 5.2. check if the request will be handled by a callback */
  8906. if (get_request_handler(conn,
  8907. is_websocket_request ? WEBSOCKET_HANDLER
  8908. : REQUEST_HANDLER,
  8909. &callback_handler,
  8910. &ws_connect_handler,
  8911. &ws_ready_handler,
  8912. &ws_data_handler,
  8913. &ws_close_handler,
  8914. NULL,
  8915. &callback_data)) {
  8916. /* 5.2.1. A callback will handle this request. All requests
  8917. * handled
  8918. * by a callback have to be considered as requests to a script
  8919. * resource. */
  8920. is_callback_resource = 1;
  8921. is_script_resource = 1;
  8922. is_put_or_delete_request = is_put_or_delete_method(conn);
  8923. } else {
  8924. no_callback_resource:
  8925. /* 5.2.2. No callback is responsible for this request. The URI
  8926. * addresses a file based resource (static content or Lua/cgi
  8927. * scripts in the file system). */
  8928. is_callback_resource = 0;
  8929. interpret_uri(conn,
  8930. path,
  8931. sizeof(path),
  8932. &file,
  8933. &is_found,
  8934. &is_script_resource,
  8935. &is_websocket_request,
  8936. &is_put_or_delete_request);
  8937. }
  8938. /* 6. authorization check */
  8939. /* 6.1. a custom authorization handler is installed */
  8940. if (get_request_handler(conn,
  8941. AUTH_HANDLER,
  8942. NULL,
  8943. NULL,
  8944. NULL,
  8945. NULL,
  8946. NULL,
  8947. &auth_handler,
  8948. &auth_callback_data)) {
  8949. if (!auth_handler(conn, auth_callback_data)) {
  8950. return;
  8951. }
  8952. } else if (is_put_or_delete_request && !is_script_resource
  8953. && !is_callback_resource) {
  8954. /* 6.2. this request is a PUT/DELETE to a real file */
  8955. /* 6.2.1. thus, the server must have real files */
  8956. #if defined(NO_FILES)
  8957. if (1) {
  8958. #else
  8959. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8960. #endif
  8961. /* This server does not have any real files, thus the
  8962. * PUT/DELETE methods are not valid. */
  8963. send_http_error(conn,
  8964. 405,
  8965. "%s method not allowed",
  8966. conn->request_info.request_method);
  8967. return;
  8968. }
  8969. #if !defined(NO_FILES)
  8970. /* 6.2.2. Check if put authorization for static files is
  8971. * available.
  8972. */
  8973. if (!is_authorized_for_put(conn)) {
  8974. send_authorization_request(conn);
  8975. return;
  8976. }
  8977. #endif
  8978. } else {
  8979. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8980. * or it is a PUT or DELETE request to a resource that does not
  8981. * correspond to a file. Check authorization. */
  8982. if (!check_authorization(conn, path)) {
  8983. send_authorization_request(conn);
  8984. return;
  8985. }
  8986. }
  8987. /* request is authorized or does not need authorization */
  8988. /* 7. check if there are request handlers for this uri */
  8989. if (is_callback_resource) {
  8990. if (!is_websocket_request) {
  8991. i = callback_handler(conn, callback_data);
  8992. if (i > 0) {
  8993. /* Do nothing, callback has served the request. Store
  8994. * the
  8995. * return value as status code for the log and discard
  8996. * all
  8997. * data from the client not used by the callback. */
  8998. conn->status_code = i;
  8999. discard_unread_request_data(conn);
  9000. } else {
  9001. /* TODO (high): what if the handler did NOT handle the
  9002. * request */
  9003. /* The last version did handle this as a file request,
  9004. * but
  9005. * since a file request is not always a script resource,
  9006. * the authorization check might be different */
  9007. interpret_uri(conn,
  9008. path,
  9009. sizeof(path),
  9010. &file,
  9011. &is_found,
  9012. &is_script_resource,
  9013. &is_websocket_request,
  9014. &is_put_or_delete_request);
  9015. callback_handler = NULL;
  9016. /* TODO (very low): goto is deprecated but for the
  9017. * moment,
  9018. * a goto is simpler than some curious loop. */
  9019. /* The situation "callback does not handle the request"
  9020. * needs to be reconsidered anyway. */
  9021. goto no_callback_resource;
  9022. }
  9023. } else {
  9024. #if defined(USE_WEBSOCKET)
  9025. handle_websocket_request(conn,
  9026. path,
  9027. is_callback_resource,
  9028. ws_connect_handler,
  9029. ws_ready_handler,
  9030. ws_data_handler,
  9031. ws_close_handler,
  9032. callback_data);
  9033. #endif
  9034. }
  9035. return;
  9036. }
  9037. /* 8. handle websocket requests */
  9038. #if defined(USE_WEBSOCKET)
  9039. if (is_websocket_request) {
  9040. if (is_script_resource) {
  9041. /* Websocket Lua script */
  9042. handle_websocket_request(conn,
  9043. path,
  9044. 0 /* Lua Script */,
  9045. NULL,
  9046. NULL,
  9047. NULL,
  9048. NULL,
  9049. &conn->ctx->callbacks);
  9050. } else {
  9051. #if defined(MG_LEGACY_INTERFACE)
  9052. handle_websocket_request(
  9053. conn,
  9054. path,
  9055. !is_script_resource /* could be deprecated global callback */,
  9056. deprecated_websocket_connect_wrapper,
  9057. deprecated_websocket_ready_wrapper,
  9058. deprecated_websocket_data_wrapper,
  9059. NULL,
  9060. &conn->ctx->callbacks);
  9061. #else
  9062. send_http_error(conn, 404, "%s", "Not found");
  9063. #endif
  9064. }
  9065. return;
  9066. } else
  9067. #endif
  9068. #if defined(NO_FILES)
  9069. /* 9a. In case the server uses only callbacks, this uri is
  9070. * unknown.
  9071. * Then, all request handling ends here. */
  9072. send_http_error(conn, 404, "%s", "Not Found");
  9073. #else
  9074. /* 9b. This request is either for a static file or resource handled
  9075. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9076. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9077. send_http_error(conn, 404, "%s", "Not Found");
  9078. return;
  9079. }
  9080. /* 10. File is handled by a script. */
  9081. if (is_script_resource) {
  9082. handle_file_based_request(conn, path, &file);
  9083. return;
  9084. }
  9085. /* 11. Handle put/delete/mkcol requests */
  9086. if (is_put_or_delete_request) {
  9087. /* 11.1. PUT method */
  9088. if (!strcmp(ri->request_method, "PUT")) {
  9089. put_file(conn, path);
  9090. return;
  9091. }
  9092. /* 11.2. DELETE method */
  9093. if (!strcmp(ri->request_method, "DELETE")) {
  9094. delete_file(conn, path);
  9095. return;
  9096. }
  9097. /* 11.3. MKCOL method */
  9098. if (!strcmp(ri->request_method, "MKCOL")) {
  9099. mkcol(conn, path);
  9100. return;
  9101. }
  9102. /* 11.4. PATCH method
  9103. * This method is not supported for static resources,
  9104. * only for scripts (Lua, CGI) and callbacks. */
  9105. send_http_error(conn,
  9106. 405,
  9107. "%s method not allowed",
  9108. conn->request_info.request_method);
  9109. return;
  9110. }
  9111. /* 11. File does not exist, or it was configured that it should be
  9112. * hidden */
  9113. if (!is_found || (must_hide_file(conn, path))) {
  9114. send_http_error(conn, 404, "%s", "Not found");
  9115. return;
  9116. }
  9117. /* 12. Directory uris should end with a slash */
  9118. if (file.is_directory && (uri_len > 0)
  9119. && (ri->local_uri[uri_len - 1] != '/')) {
  9120. gmt_time_string(date, sizeof(date), &curtime);
  9121. mg_printf(conn,
  9122. "HTTP/1.1 301 Moved Permanently\r\n"
  9123. "Location: %s/\r\n"
  9124. "Date: %s\r\n"
  9125. /* "Cache-Control: private\r\n" (= default) */
  9126. "Content-Length: 0\r\n"
  9127. "Connection: %s\r\n\r\n",
  9128. ri->request_uri,
  9129. date,
  9130. suggest_connection_header(conn));
  9131. return;
  9132. }
  9133. /* 13. Handle other methods than GET/HEAD */
  9134. /* 13.1. Handle PROPFIND */
  9135. if (!strcmp(ri->request_method, "PROPFIND")) {
  9136. handle_propfind(conn, path, &file);
  9137. return;
  9138. }
  9139. /* 13.2. Handle OPTIONS for files */
  9140. if (!strcmp(ri->request_method, "OPTIONS")) {
  9141. /* This standard handler is only used for real files.
  9142. * Scripts should support the OPTIONS method themselves, to allow a
  9143. * maximum flexibility.
  9144. * Lua and CGI scripts may fully support CORS this way (including
  9145. * preflights). */
  9146. send_options(conn);
  9147. return;
  9148. }
  9149. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9150. if (0 != strcmp(ri->request_method, "GET")
  9151. && 0 != strcmp(ri->request_method, "HEAD")) {
  9152. send_http_error(conn,
  9153. 405,
  9154. "%s method not allowed",
  9155. conn->request_info.request_method);
  9156. return;
  9157. }
  9158. /* 14. directories */
  9159. if (file.is_directory) {
  9160. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9161. /* 14.1. use a substitute file */
  9162. /* TODO (high): substitute index may be a script resource.
  9163. * define what should be possible in this case. */
  9164. } else {
  9165. /* 14.2. no substitute file */
  9166. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9167. "yes")) {
  9168. handle_directory_request(conn, path);
  9169. } else {
  9170. send_http_error(conn,
  9171. 403,
  9172. "%s",
  9173. "Error: Directory listing denied");
  9174. }
  9175. return;
  9176. }
  9177. }
  9178. handle_file_based_request(conn, path, &file);
  9179. #endif /* !defined(NO_FILES) */
  9180. #if 0
  9181. /* Perform redirect and auth checks before calling begin_request()
  9182. * handler.
  9183. * Otherwise, begin_request() would need to perform auth checks and
  9184. * redirects. */
  9185. #endif
  9186. }
  9187. return;
  9188. }
  9189. static void
  9190. handle_file_based_request(struct mg_connection *conn,
  9191. const char *path,
  9192. struct file *file)
  9193. {
  9194. if (!conn || !conn->ctx) {
  9195. return;
  9196. }
  9197. if (0) {
  9198. #ifdef USE_LUA
  9199. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9200. strlen(
  9201. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9202. path) > 0) {
  9203. /* Lua server page: an SSI like page containing mostly plain html
  9204. * code
  9205. * plus some tags with server generated contents. */
  9206. handle_lsp_request(conn, path, file, NULL);
  9207. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9208. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9209. path) > 0) {
  9210. /* Lua in-server module script: a CGI like script used to generate
  9211. * the
  9212. * entire reply. */
  9213. mg_exec_lua_script(conn, path, NULL);
  9214. #endif
  9215. #if defined(USE_DUKTAPE)
  9216. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9217. strlen(
  9218. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9219. path) > 0) {
  9220. /* Call duktape to generate the page */
  9221. mg_exec_duktape_script(conn, path);
  9222. #endif
  9223. #if !defined(NO_CGI)
  9224. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9225. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9226. path) > 0) {
  9227. /* CGI scripts may support all HTTP methods */
  9228. handle_cgi_request(conn, path);
  9229. #endif /* !NO_CGI */
  9230. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9231. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9232. path) > 0) {
  9233. handle_ssi_file_request(conn, path, file);
  9234. #if !defined(NO_CACHING)
  9235. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  9236. /* Send 304 "Not Modified" - this must not send any body data */
  9237. handle_not_modified_static_file_request(conn, file);
  9238. #endif /* !NO_CACHING */
  9239. } else {
  9240. handle_static_file_request(conn, path, file, NULL, NULL);
  9241. }
  9242. }
  9243. static void
  9244. close_all_listening_sockets(struct mg_context *ctx)
  9245. {
  9246. unsigned int i;
  9247. if (!ctx) {
  9248. return;
  9249. }
  9250. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9251. closesocket(ctx->listening_sockets[i].sock);
  9252. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9253. }
  9254. mg_free(ctx->listening_sockets);
  9255. ctx->listening_sockets = NULL;
  9256. mg_free(ctx->listening_socket_fds);
  9257. ctx->listening_socket_fds = NULL;
  9258. }
  9259. /* Valid listening port specification is: [ip_address:]port[s]
  9260. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  9261. * Examples for IPv6: [::]:80, [::1]:80,
  9262. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  9263. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  9264. static int
  9265. parse_port_string(const struct vec *vec, struct socket *so)
  9266. {
  9267. unsigned int a, b, c, d, port;
  9268. int ch, len;
  9269. #if defined(USE_IPV6)
  9270. char buf[100] = {0};
  9271. #endif
  9272. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9273. * Also, all-zeroes in the socket address means binding to all addresses
  9274. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9275. memset(so, 0, sizeof(*so));
  9276. so->lsa.sin.sin_family = AF_INET;
  9277. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9278. == 5) {
  9279. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9280. so->lsa.sin.sin_addr.s_addr =
  9281. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9282. so->lsa.sin.sin_port = htons((uint16_t)port);
  9283. #if defined(USE_IPV6)
  9284. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9285. && mg_inet_pton(
  9286. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9287. /* IPv6 address, examples: see above */
  9288. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9289. */
  9290. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9291. #endif
  9292. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9293. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9294. so->lsa.sin.sin_port = htons((uint16_t)port);
  9295. } else {
  9296. /* Parsing failure. Make port invalid. */
  9297. port = 0;
  9298. len = 0;
  9299. }
  9300. /* sscanf and the option splitting code ensure the following condition
  9301. */
  9302. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9303. return 0;
  9304. }
  9305. ch = vec->ptr[len]; /* Next character after the port number */
  9306. so->is_ssl = (ch == 's');
  9307. so->ssl_redir = (ch == 'r');
  9308. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9309. return is_valid_port(port)
  9310. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  9311. }
  9312. static int
  9313. set_ports_option(struct mg_context *ctx)
  9314. {
  9315. const char *list;
  9316. int on = 1;
  9317. #if defined(USE_IPV6)
  9318. int off = 0;
  9319. #endif
  9320. struct vec vec;
  9321. struct socket so, *ptr;
  9322. struct pollfd *pfd;
  9323. union usa usa;
  9324. socklen_t len;
  9325. int portsTotal = 0;
  9326. int portsOk = 0;
  9327. if (!ctx) {
  9328. return 0;
  9329. }
  9330. memset(&so, 0, sizeof(so));
  9331. memset(&usa, 0, sizeof(usa));
  9332. len = sizeof(usa);
  9333. list = ctx->config[LISTENING_PORTS];
  9334. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9335. portsTotal++;
  9336. if (!parse_port_string(&vec, &so)) {
  9337. mg_cry(fc(ctx),
  9338. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9339. (int)vec.len,
  9340. vec.ptr,
  9341. portsTotal,
  9342. "[IP_ADDRESS:]PORT[s|r]");
  9343. continue;
  9344. }
  9345. #if !defined(NO_SSL)
  9346. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9347. mg_cry(fc(ctx),
  9348. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9349. "option set?",
  9350. portsTotal);
  9351. continue;
  9352. }
  9353. #endif
  9354. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9355. == INVALID_SOCKET) {
  9356. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9357. continue;
  9358. }
  9359. #ifdef _WIN32
  9360. /* Windows SO_REUSEADDR lets many procs binds to a
  9361. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9362. * if someone already has the socket -- DTL */
  9363. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9364. * Windows might need a few seconds before
  9365. * the same port can be used again in the
  9366. * same process, so a short Sleep may be
  9367. * required between mg_stop and mg_start.
  9368. */
  9369. if (setsockopt(so.sock,
  9370. SOL_SOCKET,
  9371. SO_EXCLUSIVEADDRUSE,
  9372. (SOCK_OPT_TYPE)&on,
  9373. sizeof(on)) != 0) {
  9374. mg_cry(fc(ctx),
  9375. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9376. portsTotal);
  9377. }
  9378. #else
  9379. if (setsockopt(so.sock,
  9380. SOL_SOCKET,
  9381. SO_REUSEADDR,
  9382. (SOCK_OPT_TYPE)&on,
  9383. sizeof(on)) != 0) {
  9384. mg_cry(fc(ctx),
  9385. "cannot set socket option SO_REUSEADDR (entry %i)",
  9386. portsTotal);
  9387. }
  9388. #endif
  9389. #if defined(USE_IPV6)
  9390. if (so.lsa.sa.sa_family == AF_INET6
  9391. && setsockopt(so.sock,
  9392. IPPROTO_IPV6,
  9393. IPV6_V6ONLY,
  9394. (void *)&off,
  9395. sizeof(off)) != 0) {
  9396. mg_cry(fc(ctx),
  9397. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9398. portsTotal);
  9399. }
  9400. #endif
  9401. if (so.lsa.sa.sa_family == AF_INET) {
  9402. len = sizeof(so.lsa.sin);
  9403. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9404. mg_cry(fc(ctx),
  9405. "cannot bind to %.*s: %d (%s)",
  9406. (int)vec.len,
  9407. vec.ptr,
  9408. (int)ERRNO,
  9409. strerror(errno));
  9410. closesocket(so.sock);
  9411. so.sock = INVALID_SOCKET;
  9412. continue;
  9413. }
  9414. }
  9415. #if defined(USE_IPV6)
  9416. else if (so.lsa.sa.sa_family == AF_INET6) {
  9417. len = sizeof(so.lsa.sin6);
  9418. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9419. mg_cry(fc(ctx),
  9420. "cannot bind to IPv6 %.*s: %d (%s)",
  9421. (int)vec.len,
  9422. vec.ptr,
  9423. (int)ERRNO,
  9424. strerror(errno));
  9425. closesocket(so.sock);
  9426. so.sock = INVALID_SOCKET;
  9427. continue;
  9428. }
  9429. }
  9430. #endif
  9431. else {
  9432. mg_cry(fc(ctx),
  9433. "cannot bind: address family not supported (entry %i)",
  9434. portsTotal);
  9435. continue;
  9436. }
  9437. if (listen(so.sock, SOMAXCONN) != 0) {
  9438. mg_cry(fc(ctx),
  9439. "cannot listen to %.*s: %d (%s)",
  9440. (int)vec.len,
  9441. vec.ptr,
  9442. (int)ERRNO,
  9443. strerror(errno));
  9444. closesocket(so.sock);
  9445. so.sock = INVALID_SOCKET;
  9446. continue;
  9447. }
  9448. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9449. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9450. int err = (int)ERRNO;
  9451. mg_cry(fc(ctx),
  9452. "call to getsockname failed %.*s: %d (%s)",
  9453. (int)vec.len,
  9454. vec.ptr,
  9455. err,
  9456. strerror(errno));
  9457. closesocket(so.sock);
  9458. so.sock = INVALID_SOCKET;
  9459. continue;
  9460. }
  9461. /* Update lsa port in case of random free ports */
  9462. #if defined(USE_IPV6)
  9463. if (so.lsa.sa.sa_family == AF_INET6) {
  9464. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9465. } else
  9466. #endif
  9467. {
  9468. so.lsa.sin.sin_port = usa.sin.sin_port;
  9469. }
  9470. if ((ptr = (struct socket *)
  9471. mg_realloc(ctx->listening_sockets,
  9472. (ctx->num_listening_sockets + 1)
  9473. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9474. mg_cry(fc(ctx), "%s", "Out of memory");
  9475. closesocket(so.sock);
  9476. so.sock = INVALID_SOCKET;
  9477. continue;
  9478. }
  9479. if ((pfd = (struct pollfd *)mg_realloc(
  9480. ctx->listening_socket_fds,
  9481. (ctx->num_listening_sockets + 1)
  9482. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9483. mg_cry(fc(ctx), "%s", "Out of memory");
  9484. closesocket(so.sock);
  9485. so.sock = INVALID_SOCKET;
  9486. mg_free(ptr);
  9487. continue;
  9488. }
  9489. set_close_on_exec(so.sock, fc(ctx));
  9490. ctx->listening_sockets = ptr;
  9491. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9492. ctx->listening_socket_fds = pfd;
  9493. ctx->num_listening_sockets++;
  9494. portsOk++;
  9495. }
  9496. if (portsOk != portsTotal) {
  9497. close_all_listening_sockets(ctx);
  9498. portsOk = 0;
  9499. }
  9500. return portsOk;
  9501. }
  9502. static const char *
  9503. header_val(const struct mg_connection *conn, const char *header)
  9504. {
  9505. const char *header_value;
  9506. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9507. return "-";
  9508. } else {
  9509. return header_value;
  9510. }
  9511. }
  9512. static void
  9513. log_access(const struct mg_connection *conn)
  9514. {
  9515. const struct mg_request_info *ri;
  9516. struct file fi;
  9517. char date[64], src_addr[IP_ADDR_STR_LEN];
  9518. struct tm *tm;
  9519. const char *referer;
  9520. const char *user_agent;
  9521. char buf[4096];
  9522. if (!conn || !conn->ctx) {
  9523. return;
  9524. }
  9525. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9526. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  9527. == 0) {
  9528. fi.fp = NULL;
  9529. }
  9530. } else {
  9531. fi.fp = NULL;
  9532. }
  9533. /* Log is written to a file and/or a callback. If both are not set,
  9534. * executing the rest of the function is pointless. */
  9535. if ((fi.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9536. return;
  9537. }
  9538. tm = localtime(&conn->conn_birth_time);
  9539. if (tm != NULL) {
  9540. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9541. } else {
  9542. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9543. date[sizeof(date) - 1] = '\0';
  9544. }
  9545. ri = &conn->request_info;
  9546. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9547. referer = header_val(conn, "Referer");
  9548. user_agent = header_val(conn, "User-Agent");
  9549. mg_snprintf(conn,
  9550. NULL, /* Ignore truncation in access log */
  9551. buf,
  9552. sizeof(buf),
  9553. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9554. src_addr,
  9555. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9556. date,
  9557. ri->request_method ? ri->request_method : "-",
  9558. ri->request_uri ? ri->request_uri : "-",
  9559. ri->query_string ? "?" : "",
  9560. ri->query_string ? ri->query_string : "",
  9561. ri->http_version,
  9562. conn->status_code,
  9563. conn->num_bytes_sent,
  9564. referer,
  9565. user_agent);
  9566. if (conn->ctx->callbacks.log_access) {
  9567. conn->ctx->callbacks.log_access(conn, buf);
  9568. }
  9569. if (fi.fp) {
  9570. flockfile(fi.fp);
  9571. fprintf(fi.fp, "%s\n", buf);
  9572. fflush(fi.fp);
  9573. funlockfile(fi.fp);
  9574. mg_fclose(&fi);
  9575. }
  9576. }
  9577. /* Verify given socket address against the ACL.
  9578. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9579. */
  9580. static int
  9581. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9582. {
  9583. int allowed, flag;
  9584. uint32_t net, mask;
  9585. struct vec vec;
  9586. if (ctx) {
  9587. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9588. /* If any ACL is set, deny by default */
  9589. allowed = (list == NULL) ? '+' : '-';
  9590. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9591. flag = vec.ptr[0];
  9592. if ((flag != '+' && flag != '-')
  9593. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9594. mg_cry(fc(ctx),
  9595. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9596. __func__);
  9597. return -1;
  9598. }
  9599. if (net == (remote_ip & mask)) {
  9600. allowed = flag;
  9601. }
  9602. }
  9603. return allowed == '+';
  9604. }
  9605. return -1;
  9606. }
  9607. #if !defined(_WIN32)
  9608. static int
  9609. set_uid_option(struct mg_context *ctx)
  9610. {
  9611. struct passwd *pw;
  9612. if (ctx) {
  9613. const char *uid = ctx->config[RUN_AS_USER];
  9614. int success = 0;
  9615. if (uid == NULL) {
  9616. success = 1;
  9617. } else {
  9618. if ((pw = getpwnam(uid)) == NULL) {
  9619. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9620. } else if (setgid(pw->pw_gid) == -1) {
  9621. mg_cry(fc(ctx),
  9622. "%s: setgid(%s): %s",
  9623. __func__,
  9624. uid,
  9625. strerror(errno));
  9626. } else if (setgroups(0, NULL)) {
  9627. mg_cry(fc(ctx),
  9628. "%s: setgroups(): %s",
  9629. __func__,
  9630. strerror(errno));
  9631. } else if (setuid(pw->pw_uid) == -1) {
  9632. mg_cry(fc(ctx),
  9633. "%s: setuid(%s): %s",
  9634. __func__,
  9635. uid,
  9636. strerror(errno));
  9637. } else {
  9638. success = 1;
  9639. }
  9640. }
  9641. return success;
  9642. }
  9643. return 0;
  9644. }
  9645. #endif /* !_WIN32 */
  9646. static void
  9647. tls_dtor(void *key)
  9648. {
  9649. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9650. /* key == pthread_getspecific(sTlsKey); */
  9651. if (tls) {
  9652. if (tls->is_master == 2) {
  9653. tls->is_master = -3; /* Mark memory as dead */
  9654. mg_free(tls);
  9655. }
  9656. }
  9657. pthread_setspecific(sTlsKey, NULL);
  9658. }
  9659. #if !defined(NO_SSL)
  9660. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9661. static unsigned long
  9662. ssl_id_callback(void)
  9663. {
  9664. #ifdef _WIN32
  9665. return GetCurrentThreadId();
  9666. #else
  9667. #ifdef __clang__
  9668. #pragma clang diagnostic push
  9669. #pragma clang diagnostic ignored "-Wunreachable-code"
  9670. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9671. * or not, so one of the two conditions will be unreachable by construction.
  9672. * Unfortunately the C standard does not define a way to check this at
  9673. * compile time, since the #if preprocessor conditions can not use the sizeof
  9674. * operator as an argument. */
  9675. #endif
  9676. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9677. /* This is the problematic case for CRYPTO_set_id_callback:
  9678. * The OS pthread_t can not be cast to unsigned long. */
  9679. struct mg_workerTLS *tls =
  9680. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9681. if (tls == NULL) {
  9682. /* SSL called from an unknown thread: Create some thread index.
  9683. */
  9684. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9685. tls->is_master = -2; /* -2 means "3rd party thread" */
  9686. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9687. pthread_setspecific(sTlsKey, tls);
  9688. }
  9689. return tls->thread_idx;
  9690. } else {
  9691. /* pthread_t may be any data type, so a simple cast to unsigned long
  9692. * can rise a warning/error, depending on the platform.
  9693. * Here memcpy is used as an anything-to-anything cast. */
  9694. unsigned long ret = 0;
  9695. pthread_t t = pthread_self();
  9696. memcpy(&ret, &t, sizeof(pthread_t));
  9697. return ret;
  9698. }
  9699. #ifdef __clang__
  9700. #pragma clang diagnostic pop
  9701. #endif
  9702. #endif
  9703. }
  9704. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9705. static const char *ssl_error(void);
  9706. static int
  9707. refresh_trust(struct mg_connection *conn)
  9708. {
  9709. static int reload_lock = 0;
  9710. static long int data_check = 0;
  9711. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  9712. struct stat cert_buf;
  9713. long int t;
  9714. char *pem;
  9715. int should_verify_peer;
  9716. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9717. && conn->ctx->callbacks.init_ssl == NULL) {
  9718. return 0;
  9719. }
  9720. t = data_check;
  9721. if (stat(pem, &cert_buf) != -1) {
  9722. t = (long int)cert_buf.st_mtime;
  9723. }
  9724. if (data_check != t) {
  9725. data_check = t;
  9726. should_verify_peer =
  9727. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9728. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9729. == 0);
  9730. if (should_verify_peer) {
  9731. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9732. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9733. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9734. ca_file,
  9735. ca_path) != 1) {
  9736. mg_cry(fc(conn->ctx),
  9737. "SSL_CTX_load_verify_locations error: %s "
  9738. "ssl_verify_peer requires setting "
  9739. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9740. "present in "
  9741. "the .conf file?",
  9742. ssl_error());
  9743. return 0;
  9744. }
  9745. }
  9746. if (1 == mg_atomic_inc(p_reload_lock)) {
  9747. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9748. return 0;
  9749. }
  9750. *p_reload_lock = 0;
  9751. }
  9752. }
  9753. /* lock while cert is reloading */
  9754. while (*p_reload_lock) {
  9755. sleep(1);
  9756. }
  9757. return 1;
  9758. }
  9759. static pthread_mutex_t *ssl_mutexes;
  9760. static int
  9761. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9762. {
  9763. int ret, err;
  9764. int short_trust;
  9765. unsigned i;
  9766. if (!conn) {
  9767. return 0;
  9768. }
  9769. short_trust =
  9770. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9771. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9772. if (short_trust) {
  9773. int trust_ret = refresh_trust(conn);
  9774. if (!trust_ret) {
  9775. return trust_ret;
  9776. }
  9777. }
  9778. conn->ssl = SSL_new(s);
  9779. if (conn->ssl == NULL) {
  9780. return 0;
  9781. }
  9782. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9783. if (ret != 1) {
  9784. err = SSL_get_error(conn->ssl, ret);
  9785. (void)err; /* TODO: set some error message */
  9786. SSL_free(conn->ssl);
  9787. conn->ssl = NULL;
  9788. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9789. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9790. ERR_remove_state(0);
  9791. return 0;
  9792. }
  9793. /* SSL functions may fail and require to be called again:
  9794. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  9795. * Here "func" could be SSL_connect or SSL_accept. */
  9796. for (i = 0; i <= 16; i *= 2) {
  9797. ret = func(conn->ssl);
  9798. if (ret != 1) {
  9799. err = SSL_get_error(conn->ssl, ret);
  9800. if ((err == SSL_ERROR_WANT_CONNECT)
  9801. || (err == SSL_ERROR_WANT_ACCEPT)) {
  9802. /* Retry */
  9803. mg_sleep(i);
  9804. } else {
  9805. /* This is an error */
  9806. /* TODO: set some error message */
  9807. break;
  9808. }
  9809. } else {
  9810. /* success */
  9811. break;
  9812. }
  9813. }
  9814. if (ret != 1) {
  9815. SSL_free(conn->ssl);
  9816. conn->ssl = NULL;
  9817. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  9818. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9819. ERR_remove_state(0);
  9820. return 0;
  9821. }
  9822. return 1;
  9823. }
  9824. /* Return OpenSSL error message (from CRYPTO lib) */
  9825. static const char *
  9826. ssl_error(void)
  9827. {
  9828. unsigned long err;
  9829. err = ERR_get_error();
  9830. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  9831. }
  9832. static int
  9833. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  9834. {
  9835. int i;
  9836. const char hexdigit[] = "0123456789abcdef";
  9837. if (memlen <= 0 || buflen <= 0) {
  9838. return 0;
  9839. }
  9840. if (buflen < (3 * memlen)) {
  9841. return 0;
  9842. }
  9843. for (i = 0; i < memlen; i++) {
  9844. if (i > 0) {
  9845. buf[3 * i - 1] = ' ';
  9846. }
  9847. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  9848. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  9849. }
  9850. buf[3 * memlen - 1] = 0;
  9851. return 1;
  9852. }
  9853. static void
  9854. ssl_get_client_cert_info(struct mg_connection *conn)
  9855. {
  9856. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  9857. if (cert) {
  9858. char str_subject[1024];
  9859. char str_issuer[1024];
  9860. char str_serial[1024];
  9861. char str_finger[1024];
  9862. unsigned char buf[256];
  9863. int len;
  9864. unsigned int ulen;
  9865. /* Handle to algorithm used for fingerprint */
  9866. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  9867. /* Get Subject and issuer */
  9868. X509_NAME *subj = X509_get_subject_name(cert);
  9869. X509_NAME *iss = X509_get_issuer_name(cert);
  9870. /* Get serial number */
  9871. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  9872. /* Translate subject and issuer to a string */
  9873. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  9874. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  9875. /* Translate serial number to a hex string */
  9876. len = i2c_ASN1_INTEGER(serial, NULL);
  9877. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  9878. unsigned char *pbuf = buf;
  9879. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  9880. if (!hexdump2string(
  9881. buf, len2, str_serial, (int)sizeof(str_serial))) {
  9882. *str_serial = 0;
  9883. }
  9884. } else {
  9885. *str_serial = 0;
  9886. }
  9887. /* Calculate SHA1 fingerprint and store as a hex string */
  9888. ulen = 0;
  9889. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  9890. if (!hexdump2string(
  9891. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  9892. *str_finger = 0;
  9893. }
  9894. conn->request_info.client_cert =
  9895. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  9896. if (conn->request_info.client_cert) {
  9897. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  9898. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  9899. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  9900. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  9901. } else {
  9902. /* TODO: write some OOM message */
  9903. }
  9904. X509_free(cert);
  9905. }
  9906. }
  9907. static void
  9908. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9909. {
  9910. (void)line;
  9911. (void)file;
  9912. if (mode & 1) {
  9913. /* 1 is CRYPTO_LOCK */
  9914. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9915. } else {
  9916. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9917. }
  9918. }
  9919. #if !defined(NO_SSL_DL)
  9920. static void *
  9921. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9922. {
  9923. union {
  9924. void *p;
  9925. void (*fp)(void);
  9926. } u;
  9927. void *dll_handle;
  9928. struct ssl_func *fp;
  9929. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9930. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9931. return NULL;
  9932. }
  9933. for (fp = sw; fp->name != NULL; fp++) {
  9934. #ifdef _WIN32
  9935. /* GetProcAddress() returns pointer to function */
  9936. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9937. #else
  9938. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9939. * pointers to function pointers. We need to use a union to make a
  9940. * cast. */
  9941. u.p = dlsym(dll_handle, fp->name);
  9942. #endif /* _WIN32 */
  9943. if (u.fp == NULL) {
  9944. mg_cry(fc(ctx),
  9945. "%s: %s: cannot find %s",
  9946. __func__,
  9947. dll_name,
  9948. fp->name);
  9949. dlclose(dll_handle);
  9950. return NULL;
  9951. } else {
  9952. fp->ptr = u.fp;
  9953. }
  9954. }
  9955. return dll_handle;
  9956. }
  9957. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9958. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9959. #endif /* NO_SSL_DL */
  9960. #if defined(SSL_ALREADY_INITIALIZED)
  9961. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9962. #else
  9963. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9964. #endif
  9965. static int
  9966. initialize_ssl(struct mg_context *ctx)
  9967. {
  9968. int i;
  9969. size_t size;
  9970. #if !defined(NO_SSL_DL)
  9971. if (!cryptolib_dll_handle) {
  9972. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9973. if (!cryptolib_dll_handle) {
  9974. return 0;
  9975. }
  9976. }
  9977. #endif /* NO_SSL_DL */
  9978. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9979. return 1;
  9980. }
  9981. /* Initialize locking callbacks, needed for thread safety.
  9982. * http://www.openssl.org/support/faq.html#PROG1
  9983. */
  9984. i = CRYPTO_num_locks();
  9985. if (i < 0) {
  9986. i = 0;
  9987. }
  9988. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9989. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9990. mg_cry(fc(ctx),
  9991. "%s: cannot allocate mutexes: %s",
  9992. __func__,
  9993. ssl_error());
  9994. return 0;
  9995. }
  9996. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9997. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9998. }
  9999. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10000. CRYPTO_set_id_callback(&ssl_id_callback);
  10001. return 1;
  10002. }
  10003. static int
  10004. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10005. {
  10006. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10007. mg_cry(fc(ctx),
  10008. "%s: cannot open certificate file %s: %s",
  10009. __func__,
  10010. pem,
  10011. ssl_error());
  10012. return 0;
  10013. }
  10014. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10015. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10016. mg_cry(fc(ctx),
  10017. "%s: cannot open private key file %s: %s",
  10018. __func__,
  10019. pem,
  10020. ssl_error());
  10021. return 0;
  10022. }
  10023. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10024. mg_cry(fc(ctx),
  10025. "%s: certificate and private key do not match: %s",
  10026. __func__,
  10027. pem);
  10028. return 0;
  10029. }
  10030. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10031. mg_cry(fc(ctx),
  10032. "%s: cannot use certificate chain file %s: %s",
  10033. __func__,
  10034. pem,
  10035. ssl_error());
  10036. return 0;
  10037. }
  10038. return 1;
  10039. }
  10040. static long
  10041. ssl_get_protocol(int version_id)
  10042. {
  10043. long ret = SSL_OP_ALL;
  10044. if (version_id > 0)
  10045. ret |= SSL_OP_NO_SSLv2;
  10046. if (version_id > 1)
  10047. ret |= SSL_OP_NO_SSLv3;
  10048. if (version_id > 2)
  10049. ret |= SSL_OP_NO_TLSv1;
  10050. if (version_id > 3)
  10051. ret |= SSL_OP_NO_TLSv1_1;
  10052. return ret;
  10053. }
  10054. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10055. static int
  10056. set_ssl_option(struct mg_context *ctx)
  10057. {
  10058. const char *pem;
  10059. int callback_ret;
  10060. int should_verify_peer;
  10061. const char *ca_path;
  10062. const char *ca_file;
  10063. int use_default_verify_paths;
  10064. int verify_depth;
  10065. time_t now_rt = time(NULL);
  10066. struct timespec now_mt;
  10067. md5_byte_t ssl_context_id[16];
  10068. md5_state_t md5state;
  10069. int protocol_ver;
  10070. /* If PEM file is not specified and the init_ssl callback
  10071. * is not specified, skip SSL initialization. */
  10072. if (!ctx) {
  10073. return 0;
  10074. }
  10075. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10076. && ctx->callbacks.init_ssl == NULL) {
  10077. return 1;
  10078. }
  10079. if (!initialize_ssl(ctx)) {
  10080. return 0;
  10081. }
  10082. #if !defined(NO_SSL_DL)
  10083. if (!ssllib_dll_handle) {
  10084. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10085. if (!ssllib_dll_handle) {
  10086. return 0;
  10087. }
  10088. }
  10089. #endif /* NO_SSL_DL */
  10090. /* Initialize SSL library */
  10091. SSL_library_init();
  10092. SSL_load_error_strings();
  10093. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10094. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10095. return 0;
  10096. }
  10097. SSL_CTX_clear_options(ctx->ssl_ctx,
  10098. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10099. | SSL_OP_NO_TLSv1_1);
  10100. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10101. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10102. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10103. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10104. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10105. /* If a callback has been specified, call it. */
  10106. callback_ret =
  10107. (ctx->callbacks.init_ssl == NULL)
  10108. ? 0
  10109. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10110. /* If callback returns 0, civetweb sets up the SSL certificate.
  10111. * If it returns 1, civetweb assumes the calback already did this.
  10112. * If it returns -1, initializing ssl fails. */
  10113. if (callback_ret < 0) {
  10114. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10115. return 0;
  10116. }
  10117. if (callback_ret > 0) {
  10118. if (pem != NULL) {
  10119. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10120. }
  10121. return 1;
  10122. }
  10123. /* Use some UID as session context ID. */
  10124. md5_init(&md5state);
  10125. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10126. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10127. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10128. md5_append(&md5state,
  10129. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10130. strlen(ctx->config[LISTENING_PORTS]));
  10131. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10132. md5_finish(&md5state, ssl_context_id);
  10133. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10134. (const unsigned char *)&ssl_context_id,
  10135. sizeof(ssl_context_id));
  10136. if (pem != NULL) {
  10137. if (!ssl_use_pem_file(ctx, pem)) {
  10138. return 0;
  10139. }
  10140. }
  10141. should_verify_peer =
  10142. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10143. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10144. use_default_verify_paths =
  10145. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10146. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10147. if (should_verify_peer) {
  10148. ca_path = ctx->config[SSL_CA_PATH];
  10149. ca_file = ctx->config[SSL_CA_FILE];
  10150. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10151. != 1) {
  10152. mg_cry(fc(ctx),
  10153. "SSL_CTX_load_verify_locations error: %s "
  10154. "ssl_verify_peer requires setting "
  10155. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10156. "present in "
  10157. "the .conf file?",
  10158. ssl_error());
  10159. return 0;
  10160. }
  10161. SSL_CTX_set_verify(ctx->ssl_ctx,
  10162. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10163. NULL);
  10164. if (use_default_verify_paths
  10165. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10166. mg_cry(fc(ctx),
  10167. "SSL_CTX_set_default_verify_paths error: %s",
  10168. ssl_error());
  10169. return 0;
  10170. }
  10171. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10172. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10173. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10174. }
  10175. }
  10176. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10177. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10178. != 1) {
  10179. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10180. }
  10181. }
  10182. return 1;
  10183. }
  10184. static void
  10185. uninitialize_ssl(struct mg_context *ctx)
  10186. {
  10187. int i;
  10188. (void)ctx;
  10189. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10190. /* Shutdown according to
  10191. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10192. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10193. */
  10194. CRYPTO_set_locking_callback(NULL);
  10195. CRYPTO_set_id_callback(NULL);
  10196. ENGINE_cleanup();
  10197. CONF_modules_unload(1);
  10198. ERR_free_strings();
  10199. EVP_cleanup();
  10200. CRYPTO_cleanup_all_ex_data();
  10201. ERR_remove_state(0);
  10202. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10203. pthread_mutex_destroy(&ssl_mutexes[i]);
  10204. }
  10205. mg_free(ssl_mutexes);
  10206. ssl_mutexes = NULL;
  10207. }
  10208. }
  10209. #endif /* !NO_SSL */
  10210. static int
  10211. set_gpass_option(struct mg_context *ctx)
  10212. {
  10213. if (ctx) {
  10214. struct file file = STRUCT_FILE_INITIALIZER;
  10215. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10216. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  10217. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10218. return 0;
  10219. }
  10220. return 1;
  10221. }
  10222. return 0;
  10223. }
  10224. static int
  10225. set_acl_option(struct mg_context *ctx)
  10226. {
  10227. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10228. }
  10229. static void
  10230. reset_per_request_attributes(struct mg_connection *conn)
  10231. {
  10232. if (!conn) {
  10233. return;
  10234. }
  10235. conn->path_info = NULL;
  10236. conn->num_bytes_sent = conn->consumed_content = 0;
  10237. conn->status_code = -1;
  10238. conn->is_chunked = 0;
  10239. conn->must_close = conn->request_len = conn->throttle = 0;
  10240. conn->request_info.content_length = -1;
  10241. conn->request_info.remote_user = NULL;
  10242. conn->request_info.request_method = NULL;
  10243. conn->request_info.request_uri = NULL;
  10244. conn->request_info.local_uri = NULL;
  10245. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10246. * local_uri and request_uri */
  10247. conn->request_info.http_version = NULL;
  10248. conn->request_info.num_headers = 0;
  10249. conn->data_len = 0;
  10250. conn->chunk_remainder = 0;
  10251. conn->internal_error = 0;
  10252. }
  10253. static int
  10254. set_sock_timeout(SOCKET sock, int milliseconds)
  10255. {
  10256. int r0 = 0, r1, r2;
  10257. #ifdef _WIN32
  10258. /* Windows specific */
  10259. DWORD tv = (DWORD)milliseconds;
  10260. #else
  10261. /* Linux, ... (not Windows) */
  10262. struct timeval tv;
  10263. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10264. * max. time waiting for the acknowledged of TCP data before the connection
  10265. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10266. * If this option is not set, the default timeout of 20-30 minutes is used.
  10267. */
  10268. /* #define TCP_USER_TIMEOUT (18) */
  10269. #if defined(TCP_USER_TIMEOUT)
  10270. unsigned int uto = (unsigned int)milliseconds;
  10271. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10272. #endif
  10273. memset(&tv, 0, sizeof(tv));
  10274. tv.tv_sec = milliseconds / 1000;
  10275. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10276. #endif /* _WIN32 */
  10277. r1 = setsockopt(
  10278. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10279. r2 = setsockopt(
  10280. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10281. return r0 || r1 || r2;
  10282. }
  10283. static int
  10284. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10285. {
  10286. if (setsockopt(sock,
  10287. IPPROTO_TCP,
  10288. TCP_NODELAY,
  10289. (SOCK_OPT_TYPE)&nodelay_on,
  10290. sizeof(nodelay_on)) != 0) {
  10291. /* Error */
  10292. return 1;
  10293. }
  10294. /* OK */
  10295. return 0;
  10296. }
  10297. static void
  10298. close_socket_gracefully(struct mg_connection *conn)
  10299. {
  10300. #if defined(_WIN32)
  10301. char buf[MG_BUF_LEN];
  10302. int n;
  10303. #endif
  10304. struct linger linger;
  10305. if (!conn) {
  10306. return;
  10307. }
  10308. /* Set linger option to avoid socket hanging out after close. This
  10309. * prevent
  10310. * ephemeral port exhaust problem under high QPS. */
  10311. linger.l_onoff = 1;
  10312. linger.l_linger = 1;
  10313. socklen_t error_code = 0;
  10314. getsockopt(conn->client.sock,
  10315. SOL_SOCKET,
  10316. SO_ERROR,
  10317. &error_code,
  10318. (socklen_t *)sizeof(error_code));
  10319. if (error_code == ECONNRESET) {
  10320. /* Socket already closed by client/peer, close socket without linger */
  10321. } else {
  10322. if (setsockopt(conn->client.sock,
  10323. SOL_SOCKET,
  10324. SO_LINGER,
  10325. (char *)&linger,
  10326. sizeof(linger)) != 0) {
  10327. mg_cry(conn,
  10328. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10329. __func__,
  10330. strerror(ERRNO));
  10331. }
  10332. }
  10333. /* Send FIN to the client */
  10334. shutdown(conn->client.sock, SHUTDOWN_WR);
  10335. set_non_blocking_mode(conn->client.sock);
  10336. #if defined(_WIN32)
  10337. /* Read and discard pending incoming data. If we do not do that and
  10338. * close
  10339. * the socket, the data in the send buffer may be discarded. This
  10340. * behaviour is seen on Windows, when client keeps sending data
  10341. * when server decides to close the connection; then when client
  10342. * does recv() it gets no data back. */
  10343. do {
  10344. n = pull(
  10345. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  10346. } while (n > 0);
  10347. #endif
  10348. /* Now we know that our FIN is ACK-ed, safe to close */
  10349. closesocket(conn->client.sock);
  10350. conn->client.sock = INVALID_SOCKET;
  10351. }
  10352. static void
  10353. close_connection(struct mg_connection *conn)
  10354. {
  10355. if (!conn || !conn->ctx) {
  10356. return;
  10357. }
  10358. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10359. if (conn->lua_websocket_state) {
  10360. lua_websocket_close(conn, conn->lua_websocket_state);
  10361. conn->lua_websocket_state = NULL;
  10362. }
  10363. #endif
  10364. /* call the connection_close callback if assigned */
  10365. if ((conn->ctx->callbacks.connection_close != NULL)
  10366. && (conn->ctx->context_type == 1)) {
  10367. conn->ctx->callbacks.connection_close(conn);
  10368. }
  10369. mg_lock_connection(conn);
  10370. conn->must_close = 1;
  10371. #ifndef NO_SSL
  10372. if (conn->ssl != NULL) {
  10373. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10374. */
  10375. SSL_shutdown(conn->ssl);
  10376. SSL_free(conn->ssl);
  10377. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10378. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10379. ERR_remove_state(0);
  10380. conn->ssl = NULL;
  10381. }
  10382. #endif
  10383. if (conn->client.sock != INVALID_SOCKET) {
  10384. close_socket_gracefully(conn);
  10385. conn->client.sock = INVALID_SOCKET;
  10386. }
  10387. mg_unlock_connection(conn);
  10388. }
  10389. void
  10390. mg_close_connection(struct mg_connection *conn)
  10391. {
  10392. struct mg_context *client_ctx = NULL;
  10393. unsigned int i;
  10394. if (conn == NULL) {
  10395. return;
  10396. }
  10397. if (conn->ctx->context_type == 2) {
  10398. client_ctx = conn->ctx;
  10399. /* client context: loops must end */
  10400. conn->ctx->stop_flag = 1;
  10401. }
  10402. #ifndef NO_SSL
  10403. if (conn->client_ssl_ctx != NULL) {
  10404. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10405. }
  10406. #endif
  10407. close_connection(conn);
  10408. if (client_ctx != NULL) {
  10409. /* join worker thread and free context */
  10410. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10411. if (client_ctx->workerthreadids[i] != 0) {
  10412. mg_join_thread(client_ctx->workerthreadids[i]);
  10413. }
  10414. }
  10415. mg_free(client_ctx->workerthreadids);
  10416. mg_free(client_ctx);
  10417. (void)pthread_mutex_destroy(&conn->mutex);
  10418. mg_free(conn);
  10419. }
  10420. }
  10421. static struct mg_connection *
  10422. mg_connect_client_impl(const struct mg_client_options *client_options,
  10423. int use_ssl,
  10424. char *ebuf,
  10425. size_t ebuf_len)
  10426. {
  10427. static struct mg_context fake_ctx;
  10428. struct mg_connection *conn = NULL;
  10429. SOCKET sock;
  10430. union usa sa;
  10431. if (!connect_socket(&fake_ctx,
  10432. client_options->host,
  10433. client_options->port,
  10434. use_ssl,
  10435. ebuf,
  10436. ebuf_len,
  10437. &sock,
  10438. &sa)) {
  10439. ;
  10440. } else if ((conn = (struct mg_connection *)
  10441. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10442. mg_snprintf(NULL,
  10443. NULL, /* No truncation check for ebuf */
  10444. ebuf,
  10445. ebuf_len,
  10446. "calloc(): %s",
  10447. strerror(ERRNO));
  10448. closesocket(sock);
  10449. #ifndef NO_SSL
  10450. } else if (use_ssl
  10451. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10452. == NULL) {
  10453. mg_snprintf(NULL,
  10454. NULL, /* No truncation check for ebuf */
  10455. ebuf,
  10456. ebuf_len,
  10457. "SSL_CTX_new error");
  10458. closesocket(sock);
  10459. mg_free(conn);
  10460. conn = NULL;
  10461. #endif /* NO_SSL */
  10462. } else {
  10463. #ifdef USE_IPV6
  10464. socklen_t len = (sa.sa.sa_family == AF_INET)
  10465. ? sizeof(conn->client.rsa.sin)
  10466. : sizeof(conn->client.rsa.sin6);
  10467. struct sockaddr *psa =
  10468. (sa.sa.sa_family == AF_INET)
  10469. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10470. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10471. #else
  10472. socklen_t len = sizeof(conn->client.rsa.sin);
  10473. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10474. #endif
  10475. conn->buf_size = MAX_REQUEST_SIZE;
  10476. conn->buf = (char *)(conn + 1);
  10477. conn->ctx = &fake_ctx;
  10478. conn->client.sock = sock;
  10479. conn->client.lsa = sa;
  10480. if (getsockname(sock, psa, &len) != 0) {
  10481. mg_cry(conn,
  10482. "%s: getsockname() failed: %s",
  10483. __func__,
  10484. strerror(ERRNO));
  10485. }
  10486. conn->client.is_ssl = use_ssl ? 1 : 0;
  10487. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10488. #ifndef NO_SSL
  10489. if (use_ssl) {
  10490. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10491. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10492. * SSL_CTX_set_verify call is needed to switch off server
  10493. * certificate checking, which is off by default in OpenSSL and
  10494. * on in yaSSL. */
  10495. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10496. * SSL_VERIFY_PEER, verify_ssl_server); */
  10497. if (client_options->client_cert) {
  10498. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10499. mg_snprintf(NULL,
  10500. NULL, /* No truncation check for ebuf */
  10501. ebuf,
  10502. ebuf_len,
  10503. "Can not use SSL client certificate");
  10504. SSL_CTX_free(conn->client_ssl_ctx);
  10505. closesocket(sock);
  10506. mg_free(conn);
  10507. conn = NULL;
  10508. }
  10509. }
  10510. if (client_options->server_cert) {
  10511. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10512. client_options->server_cert,
  10513. NULL);
  10514. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10515. } else {
  10516. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10517. }
  10518. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  10519. mg_snprintf(NULL,
  10520. NULL, /* No truncation check for ebuf */
  10521. ebuf,
  10522. ebuf_len,
  10523. "SSL connection error");
  10524. SSL_CTX_free(conn->client_ssl_ctx);
  10525. closesocket(sock);
  10526. mg_free(conn);
  10527. conn = NULL;
  10528. }
  10529. }
  10530. #endif
  10531. }
  10532. return conn;
  10533. }
  10534. CIVETWEB_API struct mg_connection *
  10535. mg_connect_client_secure(const struct mg_client_options *client_options,
  10536. char *error_buffer,
  10537. size_t error_buffer_size)
  10538. {
  10539. return mg_connect_client_impl(client_options,
  10540. 1,
  10541. error_buffer,
  10542. error_buffer_size);
  10543. }
  10544. struct mg_connection *
  10545. mg_connect_client(const char *host,
  10546. int port,
  10547. int use_ssl,
  10548. char *error_buffer,
  10549. size_t error_buffer_size)
  10550. {
  10551. struct mg_client_options opts;
  10552. memset(&opts, 0, sizeof(opts));
  10553. opts.host = host;
  10554. opts.port = port;
  10555. return mg_connect_client_impl(&opts,
  10556. use_ssl,
  10557. error_buffer,
  10558. error_buffer_size);
  10559. }
  10560. static const struct {
  10561. const char *proto;
  10562. size_t proto_len;
  10563. unsigned default_port;
  10564. } abs_uri_protocols[] = {{"http://", 7, 80},
  10565. {"https://", 8, 443},
  10566. {"ws://", 5, 80},
  10567. {"wss://", 6, 443},
  10568. {NULL, 0, 0}};
  10569. /* Check if the uri is valid.
  10570. * return 0 for invalid uri,
  10571. * return 1 for *,
  10572. * return 2 for relative uri,
  10573. * return 3 for absolute uri without port,
  10574. * return 4 for absolute uri with port */
  10575. static int
  10576. get_uri_type(const char *uri)
  10577. {
  10578. int i;
  10579. char *hostend, *portbegin, *portend;
  10580. unsigned long port;
  10581. /* According to the HTTP standard
  10582. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10583. * URI can be an asterisk (*) or should start with slash (relative uri),
  10584. * or it should start with the protocol (absolute uri). */
  10585. if (uri[0] == '*' && uri[1] == '\0') {
  10586. /* asterisk */
  10587. return 1;
  10588. }
  10589. /* Valid URIs according to RFC 3986
  10590. * (https://www.ietf.org/rfc/rfc3986.txt)
  10591. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10592. * and unreserved characters A-Z a-z 0-9 and -._~
  10593. * and % encoded symbols.
  10594. */
  10595. for (i = 0; uri[i] != 0; i++) {
  10596. if (uri[i] < 33) {
  10597. /* control characters and spaces are invalid */
  10598. return 0;
  10599. }
  10600. if (uri[i] > 126) {
  10601. /* non-ascii characters must be % encoded */
  10602. return 0;
  10603. } else {
  10604. switch (uri[i]) {
  10605. case '"': /* 34 */
  10606. case '<': /* 60 */
  10607. case '>': /* 62 */
  10608. case '\\': /* 92 */
  10609. case '^': /* 94 */
  10610. case '`': /* 96 */
  10611. case '{': /* 123 */
  10612. case '|': /* 124 */
  10613. case '}': /* 125 */
  10614. return 0;
  10615. default:
  10616. /* character is ok */
  10617. break;
  10618. }
  10619. }
  10620. }
  10621. /* A relative uri starts with a / character */
  10622. if (uri[0] == '/') {
  10623. /* relative uri */
  10624. return 2;
  10625. }
  10626. /* It could be an absolute uri: */
  10627. /* This function only checks if the uri is valid, not if it is
  10628. * addressing the current server. So civetweb can also be used
  10629. * as a proxy server. */
  10630. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10631. if (mg_strncasecmp(uri,
  10632. abs_uri_protocols[i].proto,
  10633. abs_uri_protocols[i].proto_len) == 0) {
  10634. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10635. if (!hostend) {
  10636. return 0;
  10637. }
  10638. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10639. if (!portbegin) {
  10640. return 3;
  10641. }
  10642. port = strtoul(portbegin + 1, &portend, 10);
  10643. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10644. return 0;
  10645. }
  10646. return 4;
  10647. }
  10648. }
  10649. return 0;
  10650. }
  10651. /* Return NULL or the relative uri at the current server */
  10652. static const char *
  10653. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10654. {
  10655. const char *server_domain;
  10656. size_t server_domain_len;
  10657. size_t request_domain_len = 0;
  10658. unsigned long port = 0;
  10659. int i;
  10660. const char *hostbegin = NULL;
  10661. const char *hostend = NULL;
  10662. const char *portbegin;
  10663. char *portend;
  10664. /* DNS is case insensitive, so use case insensitive string compare here
  10665. */
  10666. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  10667. if (!server_domain) {
  10668. return 0;
  10669. }
  10670. server_domain_len = strlen(server_domain);
  10671. if (!server_domain_len) {
  10672. return 0;
  10673. }
  10674. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10675. if (mg_strncasecmp(uri,
  10676. abs_uri_protocols[i].proto,
  10677. abs_uri_protocols[i].proto_len) == 0) {
  10678. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10679. hostend = strchr(hostbegin, '/');
  10680. if (!hostend) {
  10681. return 0;
  10682. }
  10683. portbegin = strchr(hostbegin, ':');
  10684. if ((!portbegin) || (portbegin > hostend)) {
  10685. port = abs_uri_protocols[i].default_port;
  10686. request_domain_len = (size_t)(hostend - hostbegin);
  10687. } else {
  10688. port = strtoul(portbegin + 1, &portend, 10);
  10689. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10690. return 0;
  10691. }
  10692. request_domain_len = (size_t)(portbegin - hostbegin);
  10693. }
  10694. /* protocol found, port set */
  10695. break;
  10696. }
  10697. }
  10698. if (!port) {
  10699. /* port remains 0 if the protocol is not found */
  10700. return 0;
  10701. }
  10702. #if defined(USE_IPV6)
  10703. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10704. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10705. /* Request is directed to a different port */
  10706. return 0;
  10707. }
  10708. } else
  10709. #endif
  10710. {
  10711. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10712. /* Request is directed to a different port */
  10713. return 0;
  10714. }
  10715. }
  10716. if ((request_domain_len != server_domain_len)
  10717. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10718. /* Request is directed to another server */
  10719. return 0;
  10720. }
  10721. return hostend;
  10722. }
  10723. static int
  10724. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10725. {
  10726. const char *cl;
  10727. if (ebuf_len > 0) {
  10728. ebuf[0] = '\0';
  10729. }
  10730. *err = 0;
  10731. reset_per_request_attributes(conn);
  10732. if (!conn) {
  10733. mg_snprintf(conn,
  10734. NULL, /* No truncation check for ebuf */
  10735. ebuf,
  10736. ebuf_len,
  10737. "%s",
  10738. "Internal error");
  10739. *err = 500;
  10740. return 0;
  10741. }
  10742. /* Set the time the request was received. This value should be used for
  10743. * timeouts. */
  10744. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10745. conn->request_len =
  10746. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10747. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10748. */
  10749. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10750. mg_snprintf(conn,
  10751. NULL, /* No truncation check for ebuf */
  10752. ebuf,
  10753. ebuf_len,
  10754. "%s",
  10755. "Invalid request size");
  10756. *err = 500;
  10757. return 0;
  10758. }
  10759. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10760. mg_snprintf(conn,
  10761. NULL, /* No truncation check for ebuf */
  10762. ebuf,
  10763. ebuf_len,
  10764. "%s",
  10765. "Request Too Large");
  10766. *err = 413;
  10767. return 0;
  10768. } else if (conn->request_len <= 0) {
  10769. if (conn->data_len > 0) {
  10770. mg_snprintf(conn,
  10771. NULL, /* No truncation check for ebuf */
  10772. ebuf,
  10773. ebuf_len,
  10774. "%s",
  10775. "Client sent malformed request");
  10776. *err = 400;
  10777. } else {
  10778. /* Server did not send anything -> just close the connection */
  10779. conn->must_close = 1;
  10780. mg_snprintf(conn,
  10781. NULL, /* No truncation check for ebuf */
  10782. ebuf,
  10783. ebuf_len,
  10784. "%s",
  10785. "Client did not send a request");
  10786. *err = 0;
  10787. }
  10788. return 0;
  10789. } else if (parse_http_message(conn->buf,
  10790. conn->buf_size,
  10791. &conn->request_info) <= 0) {
  10792. mg_snprintf(conn,
  10793. NULL, /* No truncation check for ebuf */
  10794. ebuf,
  10795. ebuf_len,
  10796. "%s",
  10797. "Bad Request");
  10798. *err = 400;
  10799. return 0;
  10800. } else {
  10801. /* Message is a valid request or response */
  10802. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10803. /* Request/response has content length set */
  10804. char *endptr = NULL;
  10805. conn->content_len = strtoll(cl, &endptr, 10);
  10806. if (endptr == cl) {
  10807. mg_snprintf(conn,
  10808. NULL, /* No truncation check for ebuf */
  10809. ebuf,
  10810. ebuf_len,
  10811. "%s",
  10812. "Bad Request");
  10813. *err = 411;
  10814. return 0;
  10815. }
  10816. /* Publish the content length back to the request info. */
  10817. conn->request_info.content_length = conn->content_len;
  10818. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10819. != NULL
  10820. && !mg_strcasecmp(cl, "chunked")) {
  10821. conn->is_chunked = 1;
  10822. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10823. || !mg_strcasecmp(conn->request_info.request_method,
  10824. "PUT")) {
  10825. /* POST or PUT request without content length set */
  10826. conn->content_len = -1;
  10827. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10828. "HTTP/",
  10829. 5)) {
  10830. /* Response without content length set */
  10831. conn->content_len = -1;
  10832. } else {
  10833. /* Other request */
  10834. conn->content_len = 0;
  10835. }
  10836. }
  10837. return 1;
  10838. }
  10839. int
  10840. mg_get_response(struct mg_connection *conn,
  10841. char *ebuf,
  10842. size_t ebuf_len,
  10843. int timeout)
  10844. {
  10845. if (conn) {
  10846. /* Implementation of API function for HTTP clients */
  10847. int err, ret;
  10848. struct mg_context *octx = conn->ctx;
  10849. struct mg_context rctx = *(conn->ctx);
  10850. char txt[32]; /* will not overflow */
  10851. if (timeout >= 0) {
  10852. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10853. rctx.config[REQUEST_TIMEOUT] = txt;
  10854. set_sock_timeout(conn->client.sock, timeout);
  10855. } else {
  10856. rctx.config[REQUEST_TIMEOUT] = NULL;
  10857. }
  10858. conn->ctx = &rctx;
  10859. ret = getreq(conn, ebuf, ebuf_len, &err);
  10860. conn->ctx = octx;
  10861. /* TODO: 1) uri is deprecated;
  10862. * 2) here, ri.uri is the http response code */
  10863. conn->request_info.uri = conn->request_info.request_uri;
  10864. /* TODO (mid): Define proper return values - maybe return length?
  10865. * For the first test use <0 for error and >0 for OK */
  10866. return (ret == 0) ? -1 : +1;
  10867. }
  10868. return -1;
  10869. }
  10870. struct mg_connection *
  10871. mg_download(const char *host,
  10872. int port,
  10873. int use_ssl,
  10874. char *ebuf,
  10875. size_t ebuf_len,
  10876. const char *fmt,
  10877. ...)
  10878. {
  10879. struct mg_connection *conn;
  10880. va_list ap;
  10881. int i;
  10882. int reqerr;
  10883. va_start(ap, fmt);
  10884. ebuf[0] = '\0';
  10885. /* open a connection */
  10886. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10887. if (conn != NULL) {
  10888. i = mg_vprintf(conn, fmt, ap);
  10889. if (i <= 0) {
  10890. mg_snprintf(conn,
  10891. NULL, /* No truncation check for ebuf */
  10892. ebuf,
  10893. ebuf_len,
  10894. "%s",
  10895. "Error sending request");
  10896. } else {
  10897. getreq(conn, ebuf, ebuf_len, &reqerr);
  10898. /* TODO: 1) uri is deprecated;
  10899. * 2) here, ri.uri is the http response code */
  10900. conn->request_info.uri = conn->request_info.request_uri;
  10901. }
  10902. }
  10903. /* if an error occured, close the connection */
  10904. if (ebuf[0] != '\0' && conn != NULL) {
  10905. mg_close_connection(conn);
  10906. conn = NULL;
  10907. }
  10908. va_end(ap);
  10909. return conn;
  10910. }
  10911. struct websocket_client_thread_data {
  10912. struct mg_connection *conn;
  10913. mg_websocket_data_handler data_handler;
  10914. mg_websocket_close_handler close_handler;
  10915. void *callback_data;
  10916. };
  10917. #if defined(USE_WEBSOCKET)
  10918. #ifdef _WIN32
  10919. static unsigned __stdcall websocket_client_thread(void *data)
  10920. #else
  10921. static void *
  10922. websocket_client_thread(void *data)
  10923. #endif
  10924. {
  10925. struct websocket_client_thread_data *cdata =
  10926. (struct websocket_client_thread_data *)data;
  10927. mg_set_thread_name("ws-client");
  10928. if (cdata->conn->ctx) {
  10929. if (cdata->conn->ctx->callbacks.init_thread) {
  10930. /* 3 indicates a websocket client thread */
  10931. /* TODO: check if conn->ctx can be set */
  10932. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  10933. }
  10934. }
  10935. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10936. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10937. if (cdata->close_handler != NULL) {
  10938. cdata->close_handler(cdata->conn, cdata->callback_data);
  10939. }
  10940. mg_free((void *)cdata);
  10941. #ifdef _WIN32
  10942. return 0;
  10943. #else
  10944. return NULL;
  10945. #endif
  10946. }
  10947. #endif
  10948. struct mg_connection *
  10949. mg_connect_websocket_client(const char *host,
  10950. int port,
  10951. int use_ssl,
  10952. char *error_buffer,
  10953. size_t error_buffer_size,
  10954. const char *path,
  10955. const char *origin,
  10956. mg_websocket_data_handler data_func,
  10957. mg_websocket_close_handler close_func,
  10958. void *user_data)
  10959. {
  10960. struct mg_connection *conn = NULL;
  10961. #if defined(USE_WEBSOCKET)
  10962. struct mg_context *newctx = NULL;
  10963. struct websocket_client_thread_data *thread_data;
  10964. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10965. static const char *handshake_req;
  10966. if (origin != NULL) {
  10967. handshake_req = "GET %s HTTP/1.1\r\n"
  10968. "Host: %s\r\n"
  10969. "Upgrade: websocket\r\n"
  10970. "Connection: Upgrade\r\n"
  10971. "Sec-WebSocket-Key: %s\r\n"
  10972. "Sec-WebSocket-Version: 13\r\n"
  10973. "Origin: %s\r\n"
  10974. "\r\n";
  10975. } else {
  10976. handshake_req = "GET %s HTTP/1.1\r\n"
  10977. "Host: %s\r\n"
  10978. "Upgrade: websocket\r\n"
  10979. "Connection: Upgrade\r\n"
  10980. "Sec-WebSocket-Key: %s\r\n"
  10981. "Sec-WebSocket-Version: 13\r\n"
  10982. "\r\n";
  10983. }
  10984. /* Establish the client connection and request upgrade */
  10985. conn = mg_download(host,
  10986. port,
  10987. use_ssl,
  10988. error_buffer,
  10989. error_buffer_size,
  10990. handshake_req,
  10991. path,
  10992. host,
  10993. magic,
  10994. origin);
  10995. /* Connection object will be null if something goes wrong */
  10996. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10997. if (!*error_buffer) {
  10998. /* if there is a connection, but it did not return 101,
  10999. * error_buffer is not yet set */
  11000. mg_snprintf(conn,
  11001. NULL, /* No truncation check for ebuf */
  11002. error_buffer,
  11003. error_buffer_size,
  11004. "Unexpected server reply");
  11005. }
  11006. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11007. if (conn != NULL) {
  11008. mg_free(conn);
  11009. conn = NULL;
  11010. }
  11011. return conn;
  11012. }
  11013. /* For client connections, mg_context is fake. Since we need to set a
  11014. * callback function, we need to create a copy and modify it. */
  11015. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11016. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11017. newctx->user_data = user_data;
  11018. newctx->context_type = 2; /* client context type */
  11019. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11020. newctx->workerthreadids =
  11021. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11022. conn->ctx = newctx;
  11023. thread_data = (struct websocket_client_thread_data *)
  11024. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11025. thread_data->conn = conn;
  11026. thread_data->data_handler = data_func;
  11027. thread_data->close_handler = close_func;
  11028. thread_data->callback_data = NULL;
  11029. /* Start a thread to read the websocket client connection
  11030. * This thread will automatically stop when mg_disconnect is
  11031. * called on the client connection */
  11032. if (mg_start_thread_with_id(websocket_client_thread,
  11033. (void *)thread_data,
  11034. newctx->workerthreadids) != 0) {
  11035. mg_free((void *)thread_data);
  11036. mg_free((void *)newctx->workerthreadids);
  11037. mg_free((void *)newctx);
  11038. mg_free((void *)conn);
  11039. conn = NULL;
  11040. DEBUG_TRACE("%s",
  11041. "Websocket client connect thread could not be started\r\n");
  11042. }
  11043. #else
  11044. /* Appease "unused parameter" warnings */
  11045. (void)host;
  11046. (void)port;
  11047. (void)use_ssl;
  11048. (void)error_buffer;
  11049. (void)error_buffer_size;
  11050. (void)path;
  11051. (void)origin;
  11052. (void)user_data;
  11053. (void)data_func;
  11054. (void)close_func;
  11055. #endif
  11056. return conn;
  11057. }
  11058. static void
  11059. process_new_connection(struct mg_connection *conn)
  11060. {
  11061. if (conn && conn->ctx) {
  11062. struct mg_request_info *ri = &conn->request_info;
  11063. int keep_alive_enabled, keep_alive, discard_len;
  11064. char ebuf[100];
  11065. const char *hostend;
  11066. int reqerr, uri_type;
  11067. keep_alive_enabled =
  11068. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11069. /* Important: on new connection, reset the receiving buffer. Credit
  11070. * goes to crule42. */
  11071. conn->data_len = 0;
  11072. do {
  11073. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11074. /* The request sent by the client could not be understood by
  11075. * the server, or it was incomplete or a timeout. Send an
  11076. * error message and close the connection. */
  11077. if (reqerr > 0) {
  11078. /*assert(ebuf[0] != '\0');*/
  11079. send_http_error(conn, reqerr, "%s", ebuf);
  11080. }
  11081. } else if (strcmp(ri->http_version, "1.0")
  11082. && strcmp(ri->http_version, "1.1")) {
  11083. mg_snprintf(conn,
  11084. NULL, /* No truncation check for ebuf */
  11085. ebuf,
  11086. sizeof(ebuf),
  11087. "Bad HTTP version: [%s]",
  11088. ri->http_version);
  11089. send_http_error(conn, 505, "%s", ebuf);
  11090. }
  11091. if (ebuf[0] == '\0') {
  11092. uri_type = get_uri_type(conn->request_info.request_uri);
  11093. switch (uri_type) {
  11094. case 1:
  11095. /* Asterisk */
  11096. conn->request_info.local_uri = NULL;
  11097. break;
  11098. case 2:
  11099. /* relative uri */
  11100. conn->request_info.local_uri =
  11101. conn->request_info.request_uri;
  11102. break;
  11103. case 3:
  11104. case 4:
  11105. /* absolute uri (with/without port) */
  11106. hostend = get_rel_url_at_current_server(
  11107. conn->request_info.request_uri, conn);
  11108. if (hostend) {
  11109. conn->request_info.local_uri = hostend;
  11110. } else {
  11111. conn->request_info.local_uri = NULL;
  11112. }
  11113. break;
  11114. default:
  11115. mg_snprintf(conn,
  11116. NULL, /* No truncation check for ebuf */
  11117. ebuf,
  11118. sizeof(ebuf),
  11119. "Invalid URI");
  11120. send_http_error(conn, 400, "%s", ebuf);
  11121. conn->request_info.local_uri = NULL;
  11122. break;
  11123. }
  11124. /* TODO: cleanup uri, local_uri and request_uri */
  11125. conn->request_info.uri = conn->request_info.local_uri;
  11126. }
  11127. if (ebuf[0] == '\0') {
  11128. if (conn->request_info.local_uri) {
  11129. /* handle request to local server */
  11130. handle_request(conn);
  11131. if (conn->ctx->callbacks.end_request != NULL) {
  11132. conn->ctx->callbacks.end_request(conn,
  11133. conn->status_code);
  11134. }
  11135. log_access(conn);
  11136. } else {
  11137. /* TODO: handle non-local request (PROXY) */
  11138. conn->must_close = 1;
  11139. }
  11140. } else {
  11141. conn->must_close = 1;
  11142. }
  11143. if (ri->remote_user != NULL) {
  11144. mg_free((void *)ri->remote_user);
  11145. /* Important! When having connections with and without auth
  11146. * would cause double free and then crash */
  11147. ri->remote_user = NULL;
  11148. }
  11149. /* NOTE(lsm): order is important here. should_keep_alive() call
  11150. * is
  11151. * using parsed request, which will be invalid after memmove's
  11152. * below.
  11153. * Therefore, memorize should_keep_alive() result now for later
  11154. * use
  11155. * in loop exit condition. */
  11156. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  11157. && conn->content_len >= 0 && should_keep_alive(conn);
  11158. /* Discard all buffered data for this request */
  11159. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11160. && ((conn->request_len + conn->content_len)
  11161. < (int64_t)conn->data_len))
  11162. ? (int)(conn->request_len + conn->content_len)
  11163. : conn->data_len;
  11164. /*assert(discard_len >= 0);*/
  11165. if (discard_len < 0)
  11166. break;
  11167. conn->data_len -= discard_len;
  11168. if (conn->data_len > 0) {
  11169. memmove(conn->buf,
  11170. conn->buf + discard_len,
  11171. (size_t)conn->data_len);
  11172. }
  11173. /* assert(conn->data_len >= 0); */
  11174. /* assert(conn->data_len <= conn->buf_size); */
  11175. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11176. break;
  11177. }
  11178. } while (keep_alive);
  11179. }
  11180. }
  11181. #if defined(ALTERNATIVE_QUEUE)
  11182. static void
  11183. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11184. {
  11185. unsigned int i;
  11186. for (;;) {
  11187. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11188. /* find a free worker slot and signal it */
  11189. if (ctx->client_socks[i].in_use == 0) {
  11190. ctx->client_socks[i] = *sp;
  11191. ctx->client_socks[i].in_use = 1;
  11192. event_signal(ctx->client_wait_events[i]);
  11193. return;
  11194. }
  11195. }
  11196. /* queue is full */
  11197. mg_sleep(1);
  11198. }
  11199. }
  11200. static int
  11201. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11202. {
  11203. ctx->client_socks[thread_index].in_use = 0;
  11204. event_wait(ctx->client_wait_events[thread_index]);
  11205. *sp = ctx->client_socks[thread_index];
  11206. return !ctx->stop_flag;
  11207. }
  11208. #else /* ALTERNATIVE_QUEUE */
  11209. /* Worker threads take accepted socket from the queue */
  11210. static int
  11211. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11212. {
  11213. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11214. (void)thread_index;
  11215. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11216. DEBUG_TRACE("%s", "going idle");
  11217. /* If the queue is empty, wait. We're idle at this point. */
  11218. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11219. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11220. }
  11221. /* If we're stopping, sq_head may be equal to sq_tail. */
  11222. if (ctx->sq_head > ctx->sq_tail) {
  11223. /* Copy socket from the queue and increment tail */
  11224. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11225. ctx->sq_tail++;
  11226. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11227. /* Wrap pointers if needed */
  11228. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11229. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11230. ctx->sq_head -= QUEUE_SIZE(ctx);
  11231. }
  11232. }
  11233. (void)pthread_cond_signal(&ctx->sq_empty);
  11234. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11235. return !ctx->stop_flag;
  11236. #undef QUEUE_SIZE
  11237. }
  11238. /* Master thread adds accepted socket to a queue */
  11239. static void
  11240. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11241. {
  11242. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11243. if (!ctx) {
  11244. return;
  11245. }
  11246. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11247. /* If the queue is full, wait */
  11248. while (ctx->stop_flag == 0
  11249. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11250. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11251. }
  11252. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11253. /* Copy socket to the queue and increment head */
  11254. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11255. ctx->sq_head++;
  11256. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11257. }
  11258. (void)pthread_cond_signal(&ctx->sq_full);
  11259. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11260. #undef QUEUE_SIZE
  11261. }
  11262. #endif /* ALTERNATIVE_QUEUE */
  11263. struct worker_thread_args {
  11264. struct mg_context *ctx;
  11265. int index;
  11266. };
  11267. static void *
  11268. worker_thread_run(struct worker_thread_args *thread_args)
  11269. {
  11270. struct mg_context *ctx = thread_args->ctx;
  11271. struct mg_connection *conn;
  11272. struct mg_workerTLS tls;
  11273. #if defined(MG_LEGACY_INTERFACE)
  11274. uint32_t addr;
  11275. #endif
  11276. mg_set_thread_name("worker");
  11277. tls.is_master = 0;
  11278. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11279. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11280. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11281. #endif
  11282. if (ctx->callbacks.init_thread) {
  11283. /* call init_thread for a worker thread (type 1) */
  11284. ctx->callbacks.init_thread(ctx, 1);
  11285. }
  11286. conn =
  11287. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11288. if (conn == NULL) {
  11289. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11290. } else {
  11291. pthread_setspecific(sTlsKey, &tls);
  11292. conn->buf_size = MAX_REQUEST_SIZE;
  11293. conn->buf = (char *)(conn + 1);
  11294. conn->ctx = ctx;
  11295. conn->thread_index = thread_args->index;
  11296. conn->request_info.user_data = ctx->user_data;
  11297. /* Allocate a mutex for this connection to allow communication both
  11298. * within the request handler and from elsewhere in the application
  11299. */
  11300. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11301. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11302. * signal sq_empty condvar to wake up the master waiting in
  11303. * produce_socket() */
  11304. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11305. conn->conn_birth_time = time(NULL);
  11306. /* Fill in IP, port info early so even if SSL setup below fails,
  11307. * error handler would have the corresponding info.
  11308. * Thanks to Johannes Winkelmann for the patch.
  11309. */
  11310. #if defined(USE_IPV6)
  11311. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11312. conn->request_info.remote_port =
  11313. ntohs(conn->client.rsa.sin6.sin6_port);
  11314. } else
  11315. #endif
  11316. {
  11317. conn->request_info.remote_port =
  11318. ntohs(conn->client.rsa.sin.sin_port);
  11319. }
  11320. sockaddr_to_string(conn->request_info.remote_addr,
  11321. sizeof(conn->request_info.remote_addr),
  11322. &conn->client.rsa);
  11323. #if defined(MG_LEGACY_INTERFACE)
  11324. /* This legacy interface only works for the IPv4 case */
  11325. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11326. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11327. #endif
  11328. conn->request_info.is_ssl = conn->client.is_ssl;
  11329. if (conn->client.is_ssl) {
  11330. #ifndef NO_SSL
  11331. /* HTTPS connection */
  11332. if (sslize(conn, conn->ctx->ssl_ctx, SSL_accept)) {
  11333. /* Get SSL client certificate information (if set) */
  11334. ssl_get_client_cert_info(conn);
  11335. /* process HTTPS connection */
  11336. process_new_connection(conn);
  11337. /* Free client certificate info */
  11338. if (conn->request_info.client_cert) {
  11339. mg_free(
  11340. (void *)(conn->request_info.client_cert->subject));
  11341. mg_free(
  11342. (void *)(conn->request_info.client_cert->issuer));
  11343. mg_free(
  11344. (void *)(conn->request_info.client_cert->serial));
  11345. mg_free(
  11346. (void *)(conn->request_info.client_cert->finger));
  11347. conn->request_info.client_cert->subject = 0;
  11348. conn->request_info.client_cert->issuer = 0;
  11349. conn->request_info.client_cert->serial = 0;
  11350. conn->request_info.client_cert->finger = 0;
  11351. mg_free(conn->request_info.client_cert);
  11352. conn->request_info.client_cert = 0;
  11353. }
  11354. }
  11355. #endif
  11356. } else {
  11357. /* process HTTP connection */
  11358. process_new_connection(conn);
  11359. }
  11360. close_connection(conn);
  11361. }
  11362. }
  11363. pthread_setspecific(sTlsKey, NULL);
  11364. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11365. CloseHandle(tls.pthread_cond_helper_mutex);
  11366. #endif
  11367. pthread_mutex_destroy(&conn->mutex);
  11368. mg_free(conn);
  11369. DEBUG_TRACE("%s", "exiting");
  11370. return NULL;
  11371. }
  11372. /* Threads have different return types on Windows and Unix. */
  11373. #ifdef _WIN32
  11374. static unsigned __stdcall worker_thread(void *thread_func_param)
  11375. {
  11376. struct worker_thread_args *pwta =
  11377. (struct worker_thread_args *)thread_func_param;
  11378. worker_thread_run(pwta);
  11379. mg_free(thread_func_param);
  11380. return 0;
  11381. }
  11382. #else
  11383. static void *
  11384. worker_thread(void *thread_func_param)
  11385. {
  11386. struct worker_thread_args *pwta =
  11387. (struct worker_thread_args *)thread_func_param;
  11388. worker_thread_run(pwta);
  11389. mg_free(thread_func_param);
  11390. return NULL;
  11391. }
  11392. #endif /* _WIN32 */
  11393. static void
  11394. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11395. {
  11396. struct socket so;
  11397. char src_addr[IP_ADDR_STR_LEN];
  11398. socklen_t len = sizeof(so.rsa);
  11399. int on = 1;
  11400. int timeout;
  11401. if (!listener) {
  11402. return;
  11403. }
  11404. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11405. == INVALID_SOCKET) {
  11406. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11407. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11408. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11409. closesocket(so.sock);
  11410. so.sock = INVALID_SOCKET;
  11411. } else {
  11412. /* Put so socket structure into the queue */
  11413. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11414. set_close_on_exec(so.sock, fc(ctx));
  11415. so.is_ssl = listener->is_ssl;
  11416. so.ssl_redir = listener->ssl_redir;
  11417. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11418. mg_cry(fc(ctx),
  11419. "%s: getsockname() failed: %s",
  11420. __func__,
  11421. strerror(ERRNO));
  11422. }
  11423. /* Set TCP keep-alive. This is needed because if HTTP-level
  11424. * keep-alive
  11425. * is enabled, and client resets the connection, server won't get
  11426. * TCP FIN or RST and will keep the connection open forever. With
  11427. * TCP keep-alive, next keep-alive handshake will figure out that
  11428. * the client is down and will close the server end.
  11429. * Thanks to Igor Klopov who suggested the patch. */
  11430. if (setsockopt(so.sock,
  11431. SOL_SOCKET,
  11432. SO_KEEPALIVE,
  11433. (SOCK_OPT_TYPE)&on,
  11434. sizeof(on)) != 0) {
  11435. mg_cry(fc(ctx),
  11436. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11437. __func__,
  11438. strerror(ERRNO));
  11439. }
  11440. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11441. * to effectively fill up the underlying IP packet payload and
  11442. * reduce the overhead of sending lots of small buffers. However
  11443. * this hurts the server's throughput (ie. operations per second)
  11444. * when HTTP 1.1 persistent connections are used and the responses
  11445. * are relatively small (eg. less than 1400 bytes).
  11446. */
  11447. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11448. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11449. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11450. mg_cry(fc(ctx),
  11451. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11452. __func__,
  11453. strerror(ERRNO));
  11454. }
  11455. }
  11456. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11457. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11458. } else {
  11459. timeout = -1;
  11460. }
  11461. if (timeout > 0) {
  11462. set_sock_timeout(so.sock, timeout);
  11463. }
  11464. produce_socket(ctx, &so);
  11465. }
  11466. }
  11467. static void
  11468. master_thread_run(void *thread_func_param)
  11469. {
  11470. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11471. struct mg_workerTLS tls;
  11472. struct pollfd *pfd;
  11473. unsigned int i;
  11474. unsigned int workerthreadcount;
  11475. if (!ctx) {
  11476. return;
  11477. }
  11478. mg_set_thread_name("master");
  11479. /* Increase priority of the master thread */
  11480. #if defined(_WIN32)
  11481. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11482. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11483. int min_prio = sched_get_priority_min(SCHED_RR);
  11484. int max_prio = sched_get_priority_max(SCHED_RR);
  11485. if ((min_prio >= 0) && (max_prio >= 0)
  11486. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11487. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11488. struct sched_param sched_param = {0};
  11489. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11490. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11491. }
  11492. #endif
  11493. /* Initialize thread local storage */
  11494. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11495. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11496. #endif
  11497. tls.is_master = 1;
  11498. pthread_setspecific(sTlsKey, &tls);
  11499. if (ctx->callbacks.init_thread) {
  11500. /* Callback for the master thread (type 0) */
  11501. ctx->callbacks.init_thread(ctx, 0);
  11502. }
  11503. /* Server starts *now* */
  11504. ctx->start_time = time(NULL);
  11505. /* Start the server */
  11506. pfd = ctx->listening_socket_fds;
  11507. while (ctx->stop_flag == 0) {
  11508. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11509. pfd[i].fd = ctx->listening_sockets[i].sock;
  11510. pfd[i].events = POLLIN;
  11511. }
  11512. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11513. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11514. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11515. * successful poll, and POLLIN is defined as
  11516. * (POLLRDNORM | POLLRDBAND)
  11517. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11518. * pfd[i].revents == POLLIN. */
  11519. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11520. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11521. }
  11522. }
  11523. }
  11524. }
  11525. /* Here stop_flag is 1 - Initiate shutdown. */
  11526. DEBUG_TRACE("%s", "stopping workers");
  11527. /* Stop signal received: somebody called mg_stop. Quit. */
  11528. close_all_listening_sockets(ctx);
  11529. /* Wakeup workers that are waiting for connections to handle. */
  11530. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11531. #if defined(ALTERNATIVE_QUEUE)
  11532. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11533. event_signal(ctx->client_wait_events[i]);
  11534. /* Since we know all sockets, we can shutdown the connections. */
  11535. if (ctx->client_socks[i].in_use) {
  11536. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11537. }
  11538. }
  11539. #else
  11540. pthread_cond_broadcast(&ctx->sq_full);
  11541. #endif
  11542. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11543. /* Join all worker threads to avoid leaking threads. */
  11544. workerthreadcount = ctx->cfg_worker_threads;
  11545. for (i = 0; i < workerthreadcount; i++) {
  11546. if (ctx->workerthreadids[i] != 0) {
  11547. mg_join_thread(ctx->workerthreadids[i]);
  11548. }
  11549. }
  11550. #if !defined(NO_SSL)
  11551. if (ctx->ssl_ctx != NULL) {
  11552. uninitialize_ssl(ctx);
  11553. }
  11554. #endif
  11555. DEBUG_TRACE("%s", "exiting");
  11556. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11557. CloseHandle(tls.pthread_cond_helper_mutex);
  11558. #endif
  11559. pthread_setspecific(sTlsKey, NULL);
  11560. /* Signal mg_stop() that we're done.
  11561. * WARNING: This must be the very last thing this
  11562. * thread does, as ctx becomes invalid after this line. */
  11563. ctx->stop_flag = 2;
  11564. }
  11565. /* Threads have different return types on Windows and Unix. */
  11566. #ifdef _WIN32
  11567. static unsigned __stdcall master_thread(void *thread_func_param)
  11568. {
  11569. master_thread_run(thread_func_param);
  11570. return 0;
  11571. }
  11572. #else
  11573. static void *
  11574. master_thread(void *thread_func_param)
  11575. {
  11576. master_thread_run(thread_func_param);
  11577. return NULL;
  11578. }
  11579. #endif /* _WIN32 */
  11580. static void
  11581. free_context(struct mg_context *ctx)
  11582. {
  11583. int i;
  11584. struct mg_handler_info *tmp_rh;
  11585. if (ctx == NULL) {
  11586. return;
  11587. }
  11588. if (ctx->callbacks.exit_context) {
  11589. ctx->callbacks.exit_context(ctx);
  11590. }
  11591. /* All threads exited, no sync is needed. Destroy thread mutex and
  11592. * condvars
  11593. */
  11594. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11595. #if defined(ALTERNATIVE_QUEUE)
  11596. mg_free(ctx->client_socks);
  11597. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11598. event_destroy(ctx->client_wait_events[i]);
  11599. }
  11600. mg_free(ctx->client_wait_events);
  11601. #else
  11602. (void)pthread_cond_destroy(&ctx->sq_empty);
  11603. (void)pthread_cond_destroy(&ctx->sq_full);
  11604. #endif
  11605. /* Destroy other context global data structures mutex */
  11606. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  11607. #if defined(USE_TIMERS)
  11608. timers_exit(ctx);
  11609. #endif
  11610. /* Deallocate config parameters */
  11611. for (i = 0; i < NUM_OPTIONS; i++) {
  11612. if (ctx->config[i] != NULL) {
  11613. #if defined(_MSC_VER)
  11614. #pragma warning(suppress : 6001)
  11615. #endif
  11616. mg_free(ctx->config[i]);
  11617. }
  11618. }
  11619. /* Deallocate request handlers */
  11620. while (ctx->handlers) {
  11621. tmp_rh = ctx->handlers;
  11622. ctx->handlers = tmp_rh->next;
  11623. mg_free(tmp_rh->uri);
  11624. mg_free(tmp_rh);
  11625. }
  11626. #ifndef NO_SSL
  11627. /* Deallocate SSL context */
  11628. if (ctx->ssl_ctx != NULL) {
  11629. SSL_CTX_free(ctx->ssl_ctx);
  11630. }
  11631. #endif /* !NO_SSL */
  11632. /* Deallocate worker thread ID array */
  11633. if (ctx->workerthreadids != NULL) {
  11634. mg_free(ctx->workerthreadids);
  11635. }
  11636. /* Deallocate the tls variable */
  11637. if (mg_atomic_dec(&sTlsInit) == 0) {
  11638. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11639. DeleteCriticalSection(&global_log_file_lock);
  11640. #endif /* _WIN32 && !__SYMBIAN32__ */
  11641. #if !defined(_WIN32)
  11642. pthread_mutexattr_destroy(&pthread_mutex_attr);
  11643. #endif
  11644. pthread_key_delete(sTlsKey);
  11645. }
  11646. /* deallocate system name string */
  11647. mg_free(ctx->systemName);
  11648. /* Deallocate context itself */
  11649. mg_free(ctx);
  11650. }
  11651. void
  11652. mg_stop(struct mg_context *ctx)
  11653. {
  11654. pthread_t mt;
  11655. if (!ctx) {
  11656. return;
  11657. }
  11658. /* We don't use a lock here. Calling mg_stop with the same ctx from
  11659. * two threads is not allowed. */
  11660. mt = ctx->masterthreadid;
  11661. if (mt == 0) {
  11662. return;
  11663. }
  11664. ctx->masterthreadid = 0;
  11665. /* Set stop flag, so all threads know they have to exit. */
  11666. ctx->stop_flag = 1;
  11667. /* Wait until everything has stopped. */
  11668. while (ctx->stop_flag != 2) {
  11669. (void)mg_sleep(10);
  11670. }
  11671. mg_join_thread(mt);
  11672. free_context(ctx);
  11673. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11674. (void)WSACleanup();
  11675. #endif /* _WIN32 && !__SYMBIAN32__ */
  11676. }
  11677. static void
  11678. get_system_name(char **sysName)
  11679. {
  11680. #if defined(_WIN32)
  11681. #if !defined(__SYMBIAN32__)
  11682. #if defined(_WIN32_WCE)
  11683. *sysName = mg_strdup("WinCE");
  11684. #else
  11685. char name[128];
  11686. DWORD dwVersion = 0;
  11687. DWORD dwMajorVersion = 0;
  11688. DWORD dwMinorVersion = 0;
  11689. DWORD dwBuild = 0;
  11690. #ifdef _MSC_VER
  11691. #pragma warning(push)
  11692. // GetVersion was declared deprecated
  11693. #pragma warning(disable : 4996)
  11694. #endif
  11695. dwVersion = GetVersion();
  11696. #ifdef _MSC_VER
  11697. #pragma warning(pop)
  11698. #endif
  11699. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  11700. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  11701. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  11702. (void)dwBuild;
  11703. sprintf(name,
  11704. "Windows %u.%u",
  11705. (unsigned)dwMajorVersion,
  11706. (unsigned)dwMinorVersion);
  11707. *sysName = mg_strdup(name);
  11708. #endif
  11709. #else
  11710. *sysName = mg_strdup("Symbian");
  11711. #endif
  11712. #else
  11713. struct utsname name;
  11714. memset(&name, 0, sizeof(name));
  11715. uname(&name);
  11716. *sysName = mg_strdup(name.sysname);
  11717. #endif
  11718. }
  11719. struct mg_context *
  11720. mg_start(const struct mg_callbacks *callbacks,
  11721. void *user_data,
  11722. const char **options)
  11723. {
  11724. struct mg_context *ctx;
  11725. const char *name, *value, *default_value;
  11726. int idx, ok, workerthreadcount;
  11727. unsigned int i;
  11728. void (*exit_callback)(const struct mg_context *ctx) = 0;
  11729. struct mg_workerTLS tls;
  11730. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11731. WSADATA data;
  11732. WSAStartup(MAKEWORD(2, 2), &data);
  11733. #endif /* _WIN32 && !__SYMBIAN32__ */
  11734. /* Allocate context and initialize reasonable general case defaults. */
  11735. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  11736. return NULL;
  11737. }
  11738. /* Random number generator will initialize at the first call */
  11739. ctx->auth_nonce_mask =
  11740. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  11741. if (mg_atomic_inc(&sTlsInit) == 1) {
  11742. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11743. InitializeCriticalSection(&global_log_file_lock);
  11744. #endif /* _WIN32 && !__SYMBIAN32__ */
  11745. #if !defined(_WIN32)
  11746. pthread_mutexattr_init(&pthread_mutex_attr);
  11747. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  11748. #endif
  11749. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  11750. /* Fatal error - abort start. However, this situation should
  11751. * never
  11752. * occur in practice. */
  11753. mg_atomic_dec(&sTlsInit);
  11754. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  11755. mg_free(ctx);
  11756. return NULL;
  11757. }
  11758. } else {
  11759. /* TODO (low): istead of sleeping, check if sTlsKey is already
  11760. * initialized. */
  11761. mg_sleep(1);
  11762. }
  11763. tls.is_master = -1;
  11764. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11765. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11766. tls.pthread_cond_helper_mutex = NULL;
  11767. #endif
  11768. pthread_setspecific(sTlsKey, &tls);
  11769. #if defined(USE_LUA)
  11770. lua_init_optional_libraries();
  11771. #endif
  11772. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11773. #if !defined(ALTERNATIVE_QUEUE)
  11774. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11775. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11776. #endif
  11777. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11778. if (!ok) {
  11779. /* Fatal error - abort start. However, this situation should never
  11780. * occur in practice. */
  11781. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11782. mg_free(ctx);
  11783. pthread_setspecific(sTlsKey, NULL);
  11784. return NULL;
  11785. }
  11786. if (callbacks) {
  11787. ctx->callbacks = *callbacks;
  11788. exit_callback = callbacks->exit_context;
  11789. ctx->callbacks.exit_context = 0;
  11790. }
  11791. ctx->user_data = user_data;
  11792. ctx->handlers = NULL;
  11793. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11794. ctx->shared_lua_websockets = 0;
  11795. #endif
  11796. while (options && (name = *options++) != NULL) {
  11797. if ((idx = get_option_index(name)) == -1) {
  11798. mg_cry(fc(ctx), "Invalid option: %s", name);
  11799. free_context(ctx);
  11800. pthread_setspecific(sTlsKey, NULL);
  11801. return NULL;
  11802. } else if ((value = *options++) == NULL) {
  11803. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11804. free_context(ctx);
  11805. pthread_setspecific(sTlsKey, NULL);
  11806. return NULL;
  11807. }
  11808. if (ctx->config[idx] != NULL) {
  11809. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11810. mg_free(ctx->config[idx]);
  11811. }
  11812. ctx->config[idx] = mg_strdup(value);
  11813. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11814. }
  11815. /* Set default value if needed */
  11816. for (i = 0; config_options[i].name != NULL; i++) {
  11817. default_value = config_options[i].default_value;
  11818. if (ctx->config[i] == NULL && default_value != NULL) {
  11819. ctx->config[i] = mg_strdup(default_value);
  11820. }
  11821. }
  11822. #if defined(NO_FILES)
  11823. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11824. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11825. free_context(ctx);
  11826. pthread_setspecific(sTlsKey, NULL);
  11827. return NULL;
  11828. }
  11829. #endif
  11830. get_system_name(&ctx->systemName);
  11831. /* NOTE(lsm): order is important here. SSL certificates must
  11832. * be initialized before listening ports. UID must be set last. */
  11833. if (!set_gpass_option(ctx) ||
  11834. #if !defined(NO_SSL)
  11835. !set_ssl_option(ctx) ||
  11836. #endif
  11837. !set_ports_option(ctx) ||
  11838. #if !defined(_WIN32)
  11839. !set_uid_option(ctx) ||
  11840. #endif
  11841. !set_acl_option(ctx)) {
  11842. free_context(ctx);
  11843. pthread_setspecific(sTlsKey, NULL);
  11844. return NULL;
  11845. }
  11846. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11847. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11848. * won't kill the whole process. */
  11849. (void)signal(SIGPIPE, SIG_IGN);
  11850. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11851. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11852. if (workerthreadcount > MAX_WORKER_THREADS) {
  11853. mg_cry(fc(ctx), "Too many worker threads");
  11854. free_context(ctx);
  11855. pthread_setspecific(sTlsKey, NULL);
  11856. return NULL;
  11857. }
  11858. if (workerthreadcount > 0) {
  11859. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11860. ctx->workerthreadids =
  11861. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11862. if (ctx->workerthreadids == NULL) {
  11863. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11864. free_context(ctx);
  11865. pthread_setspecific(sTlsKey, NULL);
  11866. return NULL;
  11867. }
  11868. #if defined(ALTERNATIVE_QUEUE)
  11869. ctx->client_wait_events = mg_calloc(sizeof(ctx->client_wait_events[0]),
  11870. ctx->cfg_worker_threads);
  11871. if (ctx->client_wait_events == NULL) {
  11872. mg_cry(fc(ctx), "Not enough memory for worker event array");
  11873. mg_free(ctx->workerthreadids);
  11874. free_context(ctx);
  11875. pthread_setspecific(sTlsKey, NULL);
  11876. return NULL;
  11877. }
  11878. ctx->client_socks =
  11879. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  11880. if (ctx->client_wait_events == NULL) {
  11881. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  11882. mg_free(ctx->client_socks);
  11883. mg_free(ctx->workerthreadids);
  11884. free_context(ctx);
  11885. pthread_setspecific(sTlsKey, NULL);
  11886. return NULL;
  11887. }
  11888. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  11889. ctx->client_wait_events[i] = event_create();
  11890. if (ctx->client_wait_events[i] == 0) {
  11891. mg_cry(fc(ctx), "Error creating worker event %i", i);
  11892. /* TODO: clean all and exit */
  11893. }
  11894. }
  11895. #endif
  11896. }
  11897. #if defined(USE_TIMERS)
  11898. if (timers_init(ctx) != 0) {
  11899. mg_cry(fc(ctx), "Error creating timers");
  11900. free_context(ctx);
  11901. pthread_setspecific(sTlsKey, NULL);
  11902. return NULL;
  11903. }
  11904. #endif
  11905. /* Context has been created - init user libraries */
  11906. if (ctx->callbacks.init_context) {
  11907. ctx->callbacks.init_context(ctx);
  11908. }
  11909. ctx->callbacks.exit_context = exit_callback;
  11910. ctx->context_type = 1; /* server context */
  11911. /* Start master (listening) thread */
  11912. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11913. /* Start worker threads */
  11914. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11915. struct worker_thread_args *wta =
  11916. mg_malloc(sizeof(struct worker_thread_args));
  11917. if (wta) {
  11918. wta->ctx = ctx;
  11919. wta->index = (int)i;
  11920. }
  11921. if ((wta == NULL)
  11922. || (mg_start_thread_with_id(worker_thread,
  11923. wta,
  11924. &ctx->workerthreadids[i]) != 0)) {
  11925. /* thread was not created */
  11926. if (wta != NULL) {
  11927. mg_free(wta);
  11928. }
  11929. if (i > 0) {
  11930. mg_cry(fc(ctx),
  11931. "Cannot start worker thread %i: error %ld",
  11932. i + 1,
  11933. (long)ERRNO);
  11934. } else {
  11935. mg_cry(fc(ctx),
  11936. "Cannot create threads: error %ld",
  11937. (long)ERRNO);
  11938. free_context(ctx);
  11939. pthread_setspecific(sTlsKey, NULL);
  11940. return NULL;
  11941. }
  11942. break;
  11943. }
  11944. }
  11945. pthread_setspecific(sTlsKey, NULL);
  11946. return ctx;
  11947. }
  11948. /* Feature check API function */
  11949. unsigned
  11950. mg_check_feature(unsigned feature)
  11951. {
  11952. static const unsigned feature_set = 0
  11953. /* Set bits for available features according to API documentation.
  11954. * This bit mask is created at compile time, according to the active
  11955. * preprocessor defines. It is a single const value at runtime. */
  11956. #if !defined(NO_FILES)
  11957. | 0x0001u
  11958. #endif
  11959. #if !defined(NO_SSL)
  11960. | 0x0002u
  11961. #endif
  11962. #if !defined(NO_CGI)
  11963. | 0x0004u
  11964. #endif
  11965. #if defined(USE_IPV6)
  11966. | 0x0008u
  11967. #endif
  11968. #if defined(USE_WEBSOCKET)
  11969. | 0x0010u
  11970. #endif
  11971. #if defined(USE_LUA)
  11972. | 0x0020u
  11973. #endif
  11974. #if defined(USE_DUKTAPE)
  11975. | 0x0040u
  11976. #endif
  11977. #if !defined(NO_CACHING)
  11978. | 0x0080u
  11979. #endif
  11980. /* Set some extra bits not defined in the API documentation.
  11981. * These bits may change without further notice. */
  11982. #if defined(MG_LEGACY_INTERFACE)
  11983. | 0x8000u
  11984. #endif
  11985. #if defined(MEMORY_DEBUGGING)
  11986. | 0x0100u
  11987. #endif
  11988. #if defined(USE_TIMERS)
  11989. | 0x0200u
  11990. #endif
  11991. #if !defined(NO_NONCE_CHECK)
  11992. | 0x0400u
  11993. #endif
  11994. #if !defined(NO_POPEN)
  11995. | 0x0800u
  11996. #endif
  11997. ;
  11998. return (feature & feature_set);
  11999. }