civetweb.c 331 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793
  1. /* Copyright (c) 2013-2016 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t));
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t clock_start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (clock_start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. clock_start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - clock_start_time)
  150. * (double)timebase_ifo.numer
  151. / (double)timebase_ifo.denom);
  152. t->tv_sec = now / 1000000000;
  153. t->tv_nsec = now % 1000000000;
  154. return 0;
  155. }
  156. return -1; /* EINVAL - Clock ID is unknown */
  157. }
  158. #endif
  159. #include <time.h>
  160. #include <stdlib.h>
  161. #include <stdarg.h>
  162. #include <assert.h>
  163. #include <string.h>
  164. #include <ctype.h>
  165. #include <limits.h>
  166. #include <stddef.h>
  167. #include <stdio.h>
  168. #ifndef MAX_WORKER_THREADS
  169. #define MAX_WORKER_THREADS (1024 * 64)
  170. #endif
  171. #ifndef SOCKET_TIMEOUT_QUANTUM
  172. #define SOCKET_TIMEOUT_QUANTUM (10000)
  173. #endif
  174. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. typedef long off_t;
  201. #define errno ((int)(GetLastError()))
  202. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  203. #endif /* _WIN32_WCE */
  204. #define MAKEUQUAD(lo, hi) \
  205. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  206. #define RATE_DIFF (10000000) /* 100 nsecs */
  207. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  208. #define SYS2UNIX_TIME(lo, hi) \
  209. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  210. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  211. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  212. * Also use _strtoui64 on modern M$ compilers */
  213. #if defined(_MSC_VER)
  214. #if (_MSC_VER < 1300)
  215. #define STRX(x) #x
  216. #define STR(x) STRX(x)
  217. #define __func__ __FILE__ ":" STR(__LINE__)
  218. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  219. #define strtoll(x, y, z) (_atoi64(x))
  220. #else
  221. #define __func__ __FUNCTION__
  222. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  223. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  224. #endif
  225. #endif /* _MSC_VER */
  226. #define ERRNO ((int)(GetLastError()))
  227. #define NO_SOCKLEN_T
  228. #define SSL_LIB "ssleay32.dll"
  229. #define CRYPTO_LIB "libeay32.dll"
  230. #define O_NONBLOCK (0)
  231. #ifndef W_OK
  232. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  233. #endif
  234. #if !defined(EWOULDBLOCK)
  235. #define EWOULDBLOCK WSAEWOULDBLOCK
  236. #endif /* !EWOULDBLOCK */
  237. #define _POSIX_
  238. #define INT64_FMT "I64d"
  239. #define UINT64_FMT "I64u"
  240. #define WINCDECL __cdecl
  241. #define SHUT_RD (0)
  242. #define SHUT_WR (1)
  243. #define SHUT_BOTH (2)
  244. #define vsnprintf_impl _vsnprintf
  245. #define access _access
  246. #define mg_sleep(x) (Sleep(x))
  247. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  248. #ifndef popen
  249. #define popen(x, y) (_popen(x, y))
  250. #endif
  251. #ifndef pclose
  252. #define pclose(x) (_pclose(x))
  253. #endif
  254. #define close(x) (_close(x))
  255. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  256. #define RTLD_LAZY (0)
  257. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  258. #define fdopen(x, y) (_fdopen((x), (y)))
  259. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  260. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  261. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  262. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  263. #define sleep(x) (Sleep((x)*1000))
  264. #define rmdir(x) (_rmdir(x))
  265. #define timegm(x) (_mkgmtime(x))
  266. #if !defined(fileno)
  267. #define fileno(x) (_fileno(x))
  268. #endif /* !fileno MINGW #defines fileno */
  269. typedef HANDLE pthread_mutex_t;
  270. typedef DWORD pthread_key_t;
  271. typedef HANDLE pthread_t;
  272. typedef struct {
  273. CRITICAL_SECTION threadIdSec;
  274. int waitingthreadcount; /* The number of threads queued. */
  275. pthread_t *waitingthreadhdls; /* The thread handles. */
  276. } pthread_cond_t;
  277. #ifndef __clockid_t_defined
  278. typedef DWORD clockid_t;
  279. #endif
  280. #ifndef CLOCK_MONOTONIC
  281. #define CLOCK_MONOTONIC (1)
  282. #endif
  283. #ifndef CLOCK_REALTIME
  284. #define CLOCK_REALTIME (2)
  285. #endif
  286. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  287. #define _TIMESPEC_DEFINED
  288. #endif
  289. #ifndef _TIMESPEC_DEFINED
  290. struct timespec {
  291. time_t tv_sec; /* seconds */
  292. long tv_nsec; /* nanoseconds */
  293. };
  294. #endif
  295. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  296. static int pthread_mutex_lock(pthread_mutex_t *);
  297. static int pthread_mutex_unlock(pthread_mutex_t *);
  298. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  299. struct file;
  300. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  301. #if defined(HAVE_STDINT)
  302. #include <stdint.h>
  303. #else
  304. typedef unsigned char uint8_t;
  305. typedef unsigned short uint16_t;
  306. typedef unsigned int uint32_t;
  307. typedef unsigned __int64 uint64_t;
  308. typedef __int64 int64_t;
  309. #define INT64_MAX (9223372036854775807)
  310. #endif /* HAVE_STDINT */
  311. /* POSIX dirent interface */
  312. struct dirent {
  313. char d_name[PATH_MAX];
  314. };
  315. typedef struct DIR {
  316. HANDLE handle;
  317. WIN32_FIND_DATAW info;
  318. struct dirent result;
  319. } DIR;
  320. #if defined(_WIN32) && !defined(POLLIN)
  321. #ifndef HAVE_POLL
  322. struct pollfd {
  323. SOCKET fd;
  324. short events;
  325. short revents;
  326. };
  327. #define POLLIN (0x0300)
  328. #endif
  329. #endif
  330. /* Mark required libraries */
  331. #if defined(_MSC_VER)
  332. #pragma comment(lib, "Ws2_32.lib")
  333. #endif
  334. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  335. block */
  336. #include <sys/wait.h>
  337. #include <sys/socket.h>
  338. #include <sys/poll.h>
  339. #include <netinet/in.h>
  340. #include <arpa/inet.h>
  341. #include <sys/time.h>
  342. #include <sys/utsname.h>
  343. #include <stdint.h>
  344. #include <inttypes.h>
  345. #include <netdb.h>
  346. #include <netinet/tcp.h>
  347. typedef const void *SOCK_OPT_TYPE;
  348. #if defined(ANDROID)
  349. typedef unsigned short int in_port_t;
  350. #endif
  351. #include <pwd.h>
  352. #include <unistd.h>
  353. #include <grp.h>
  354. #include <dirent.h>
  355. #define vsnprintf_impl vsnprintf
  356. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  357. #include <dlfcn.h>
  358. #endif
  359. #include <pthread.h>
  360. #if defined(__MACH__)
  361. #define SSL_LIB "libssl.dylib"
  362. #define CRYPTO_LIB "libcrypto.dylib"
  363. #else
  364. #if !defined(SSL_LIB)
  365. #define SSL_LIB "libssl.so"
  366. #endif
  367. #if !defined(CRYPTO_LIB)
  368. #define CRYPTO_LIB "libcrypto.so"
  369. #endif
  370. #endif
  371. #ifndef O_BINARY
  372. #define O_BINARY (0)
  373. #endif /* O_BINARY */
  374. #define closesocket(a) (close(a))
  375. #define mg_mkdir(x, y) (mkdir(x, y))
  376. #define mg_remove(x) (remove(x))
  377. #define mg_sleep(x) (usleep((x)*1000))
  378. #define ERRNO (errno)
  379. #define INVALID_SOCKET (-1)
  380. #define INT64_FMT PRId64
  381. #define UINT64_FMT PRIu64
  382. typedef int SOCKET;
  383. #define WINCDECL
  384. #if defined(__hpux)
  385. /* HPUX 11 does not have monotonic, fall back to realtime */
  386. #ifndef CLOCK_MONOTONIC
  387. #define CLOCK_MONOTONIC CLOCK_REALTIME
  388. #endif
  389. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  390. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  391. * the prototypes use int* rather than socklen_t* which matches the
  392. * actual library expectation. When called with the wrong size arg
  393. * accept() returns a zero client inet addr and check_acl() always
  394. * fails. Since socklen_t is widely used below, just force replace
  395. * their typedef with int. - DTL
  396. */
  397. #define socklen_t int
  398. #endif /* hpux */
  399. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  400. block */
  401. /* va_copy should always be a macro, C99 and C++11 - DTL */
  402. #ifndef va_copy
  403. #define va_copy(x, y) ((x) = (y))
  404. #endif
  405. #ifdef _WIN32
  406. /* Create substitutes for POSIX functions in Win32. */
  407. #if defined(__MINGW32__)
  408. /* Show no warning in case system functions are not used. */
  409. #pragma GCC diagnostic push
  410. #pragma GCC diagnostic ignored "-Wunused-function"
  411. #endif
  412. static CRITICAL_SECTION global_log_file_lock;
  413. static DWORD
  414. pthread_self(void)
  415. {
  416. return GetCurrentThreadId();
  417. }
  418. static int
  419. pthread_key_create(
  420. pthread_key_t *key,
  421. void (*_ignored)(void *) /* destructor not supported for Windows */
  422. )
  423. {
  424. (void)_ignored;
  425. if ((key != 0)) {
  426. *key = TlsAlloc();
  427. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  428. }
  429. return -2;
  430. }
  431. static int
  432. pthread_key_delete(pthread_key_t key)
  433. {
  434. return TlsFree(key) ? 0 : 1;
  435. }
  436. static int
  437. pthread_setspecific(pthread_key_t key, void *value)
  438. {
  439. return TlsSetValue(key, value) ? 0 : 1;
  440. }
  441. static void *
  442. pthread_getspecific(pthread_key_t key)
  443. {
  444. return TlsGetValue(key);
  445. }
  446. #if defined(__MINGW32__)
  447. /* Enable unused function warning again */
  448. #pragma GCC diagnostic pop
  449. #endif
  450. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  451. #else
  452. static pthread_mutexattr_t pthread_mutex_attr;
  453. #endif /* _WIN32 */
  454. #include "civetweb.h"
  455. #define PASSWORDS_FILE_NAME ".htpasswd"
  456. #define CGI_ENVIRONMENT_SIZE (4096)
  457. #define MAX_CGI_ENVIR_VARS (256)
  458. #define MG_BUF_LEN (8192)
  459. #ifndef MAX_REQUEST_SIZE
  460. #define MAX_REQUEST_SIZE (16384)
  461. #endif
  462. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  463. "request size length must be a positive number");
  464. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  465. #if !defined(DEBUG_TRACE)
  466. #if defined(DEBUG)
  467. static void DEBUG_TRACE_FUNC(const char *func,
  468. unsigned line,
  469. PRINTF_FORMAT_STRING(const char *fmt),
  470. ...) PRINTF_ARGS(3, 4);
  471. static void
  472. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  473. {
  474. va_list args;
  475. flockfile(stdout);
  476. printf("*** %lu.%p.%s.%u: ",
  477. (unsigned long)time(NULL),
  478. (void *)pthread_self(),
  479. func,
  480. line);
  481. va_start(args, fmt);
  482. vprintf(fmt, args);
  483. va_end(args);
  484. putchar('\n');
  485. fflush(stdout);
  486. funlockfile(stdout);
  487. }
  488. #define DEBUG_TRACE(fmt, ...) \
  489. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  490. #else
  491. #define DEBUG_TRACE(fmt, ...) \
  492. do { \
  493. } while (0)
  494. #endif /* DEBUG */
  495. #endif /* DEBUG_TRACE */
  496. #if defined(MEMORY_DEBUGGING)
  497. unsigned long mg_memory_debug_blockCount = 0;
  498. unsigned long mg_memory_debug_totalMemUsed = 0;
  499. static void *
  500. mg_malloc_ex(size_t size, const char *file, unsigned line)
  501. {
  502. void *data = malloc(size + sizeof(size_t));
  503. void *memory = 0;
  504. char mallocStr[256];
  505. if (data) {
  506. *(size_t *)data = size;
  507. mg_memory_debug_totalMemUsed += size;
  508. mg_memory_debug_blockCount++;
  509. memory = (void *)(((char *)data) + sizeof(size_t));
  510. }
  511. sprintf(mallocStr,
  512. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  513. memory,
  514. (unsigned long)size,
  515. mg_memory_debug_totalMemUsed,
  516. mg_memory_debug_blockCount,
  517. file,
  518. line);
  519. #if defined(_WIN32)
  520. OutputDebugStringA(mallocStr);
  521. #else
  522. DEBUG_TRACE("%s", mallocStr);
  523. #endif
  524. return memory;
  525. }
  526. static void *
  527. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  528. {
  529. void *data = mg_malloc_ex(size * count, file, line);
  530. if (data) {
  531. memset(data, 0, size);
  532. }
  533. return data;
  534. }
  535. static void
  536. mg_free_ex(void *memory, const char *file, unsigned line)
  537. {
  538. char mallocStr[256];
  539. void *data = (void *)(((char *)memory) - sizeof(size_t));
  540. size_t size;
  541. if (memory) {
  542. size = *(size_t *)data;
  543. mg_memory_debug_totalMemUsed -= size;
  544. mg_memory_debug_blockCount--;
  545. sprintf(mallocStr,
  546. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  547. memory,
  548. (unsigned long)size,
  549. mg_memory_debug_totalMemUsed,
  550. mg_memory_debug_blockCount,
  551. file,
  552. line);
  553. #if defined(_WIN32)
  554. OutputDebugStringA(mallocStr);
  555. #else
  556. DEBUG_TRACE("%s", mallocStr);
  557. #endif
  558. free(data);
  559. }
  560. }
  561. static void *
  562. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  563. {
  564. char mallocStr[256];
  565. void *data;
  566. void *_realloc;
  567. size_t oldsize;
  568. if (newsize) {
  569. if (memory) {
  570. data = (void *)(((char *)memory) - sizeof(size_t));
  571. oldsize = *(size_t *)data;
  572. _realloc = realloc(data, newsize + sizeof(size_t));
  573. if (_realloc) {
  574. data = _realloc;
  575. mg_memory_debug_totalMemUsed -= oldsize;
  576. sprintf(mallocStr,
  577. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  578. memory,
  579. (unsigned long)oldsize,
  580. mg_memory_debug_totalMemUsed,
  581. mg_memory_debug_blockCount,
  582. file,
  583. line);
  584. #if defined(_WIN32)
  585. OutputDebugStringA(mallocStr);
  586. #else
  587. DEBUG_TRACE("%s", mallocStr);
  588. #endif
  589. mg_memory_debug_totalMemUsed += newsize;
  590. sprintf(mallocStr,
  591. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  592. memory,
  593. (unsigned long)newsize,
  594. mg_memory_debug_totalMemUsed,
  595. mg_memory_debug_blockCount,
  596. file,
  597. line);
  598. #if defined(_WIN32)
  599. OutputDebugStringA(mallocStr);
  600. #else
  601. DEBUG_TRACE("%s", mallocStr);
  602. #endif
  603. *(size_t *)data = newsize;
  604. data = (void *)(((char *)data) + sizeof(size_t));
  605. } else {
  606. #if defined(_WIN32)
  607. OutputDebugStringA("MEM: realloc failed\n");
  608. #else
  609. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  610. #endif
  611. return _realloc;
  612. }
  613. } else {
  614. data = mg_malloc_ex(newsize, file, line);
  615. }
  616. } else {
  617. data = 0;
  618. mg_free_ex(memory, file, line);
  619. }
  620. return data;
  621. }
  622. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  623. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  624. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  625. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  626. #else
  627. static __inline void *
  628. mg_malloc(size_t a)
  629. {
  630. return malloc(a);
  631. }
  632. static __inline void *
  633. mg_calloc(size_t a, size_t b)
  634. {
  635. return calloc(a, b);
  636. }
  637. static __inline void *
  638. mg_realloc(void *a, size_t b)
  639. {
  640. return realloc(a, b);
  641. }
  642. static __inline void
  643. mg_free(void *a)
  644. {
  645. free(a);
  646. }
  647. #endif
  648. static void mg_vsnprintf(const struct mg_connection *conn,
  649. int *truncated,
  650. char *buf,
  651. size_t buflen,
  652. const char *fmt,
  653. va_list ap);
  654. static void mg_snprintf(const struct mg_connection *conn,
  655. int *truncated,
  656. char *buf,
  657. size_t buflen,
  658. PRINTF_FORMAT_STRING(const char *fmt),
  659. ...) PRINTF_ARGS(5, 6);
  660. /* This following lines are just meant as a reminder to use the mg-functions
  661. * for memory management */
  662. #ifdef malloc
  663. #undef malloc
  664. #endif
  665. #ifdef calloc
  666. #undef calloc
  667. #endif
  668. #ifdef realloc
  669. #undef realloc
  670. #endif
  671. #ifdef free
  672. #undef free
  673. #endif
  674. #ifdef snprintf
  675. #undef snprintf
  676. #endif
  677. #ifdef vsnprintf
  678. #undef vsnprintf
  679. #endif
  680. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  681. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  682. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  683. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  684. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  685. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  686. * but this define only works well for Windows. */
  687. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  688. #endif
  689. #define MD5_STATIC static
  690. #include "md5.inl"
  691. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  692. #ifdef NO_SOCKLEN_T
  693. typedef int socklen_t;
  694. #endif /* NO_SOCKLEN_T */
  695. #define _DARWIN_UNLIMITED_SELECT
  696. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  697. #if !defined(MSG_NOSIGNAL)
  698. #define MSG_NOSIGNAL (0)
  699. #endif
  700. #if !defined(SOMAXCONN)
  701. #define SOMAXCONN (100)
  702. #endif
  703. /* Size of the accepted socket queue */
  704. #if !defined(MGSQLEN)
  705. #define MGSQLEN (20)
  706. #endif
  707. #if defined(NO_SSL_DL)
  708. #include <openssl/ssl.h>
  709. #include <openssl/err.h>
  710. #include <openssl/crypto.h>
  711. #include <openssl/x509.h>
  712. #include <openssl/pem.h>
  713. #else
  714. /* SSL loaded dynamically from DLL.
  715. * I put the prototypes here to be independent from OpenSSL source
  716. * installation. */
  717. typedef struct ssl_st SSL;
  718. typedef struct ssl_method_st SSL_METHOD;
  719. typedef struct ssl_ctx_st SSL_CTX;
  720. typedef struct x509_store_ctx_st X509_STORE_CTX;
  721. #define SSL_CTRL_OPTIONS (32)
  722. #define SSL_CTRL_CLEAR_OPTIONS (77)
  723. #define SSL_CTRL_SET_ECDH_AUTO (94)
  724. #define SSL_VERIFY_NONE (0)
  725. #define SSL_VERIFY_PEER (1)
  726. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  727. #define SSL_VERIFY_CLIENT_ONCE (4)
  728. #define SSL_OP_ALL (0x80000BFFL)
  729. #define SSL_OP_NO_SSLv2 (0x01000000L)
  730. #define SSL_OP_NO_SSLv3 (0x02000000L)
  731. #define SSL_OP_NO_TLSv1 (0x04000000L)
  732. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  733. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  734. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  735. struct ssl_func {
  736. const char *name; /* SSL function name */
  737. void (*ptr)(void); /* Function pointer */
  738. };
  739. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  740. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  741. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  742. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  743. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  744. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  745. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  746. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  747. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  748. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  749. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  750. #define SSL_CTX_use_PrivateKey_file \
  751. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  752. #define SSL_CTX_use_certificate_file \
  753. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  754. #define SSL_CTX_set_default_passwd_cb \
  755. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  756. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  757. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  758. #define SSL_CTX_use_certificate_chain_file \
  759. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  760. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  761. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  762. #define SSL_CTX_set_verify \
  763. (*(void (*)(SSL_CTX *, \
  764. int, \
  765. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  766. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  767. #define SSL_CTX_load_verify_locations \
  768. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  769. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  770. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  771. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  772. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  773. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  774. #define SSL_CIPHER_get_name \
  775. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  776. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  777. #define SSL_CTX_set_session_id_context \
  778. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  779. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  780. #define SSL_CTX_set_cipher_list \
  781. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  782. #define SSL_CTX_set_options(ctx, op) \
  783. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  784. #define SSL_CTX_clear_options(ctx, op) \
  785. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  786. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  787. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  788. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  789. #define CRYPTO_set_locking_callback \
  790. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  791. #define CRYPTO_set_id_callback \
  792. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  793. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  794. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  795. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  796. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  797. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  798. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  799. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  800. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  801. /* set_ssl_option() function updates this array.
  802. * It loads SSL library dynamically and changes NULLs to the actual addresses
  803. * of respective functions. The macros above (like SSL_connect()) are really
  804. * just calling these functions indirectly via the pointer. */
  805. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  806. {"SSL_accept", NULL},
  807. {"SSL_connect", NULL},
  808. {"SSL_read", NULL},
  809. {"SSL_write", NULL},
  810. {"SSL_get_error", NULL},
  811. {"SSL_set_fd", NULL},
  812. {"SSL_new", NULL},
  813. {"SSL_CTX_new", NULL},
  814. {"SSLv23_server_method", NULL},
  815. {"SSL_library_init", NULL},
  816. {"SSL_CTX_use_PrivateKey_file", NULL},
  817. {"SSL_CTX_use_certificate_file", NULL},
  818. {"SSL_CTX_set_default_passwd_cb", NULL},
  819. {"SSL_CTX_free", NULL},
  820. {"SSL_load_error_strings", NULL},
  821. {"SSL_CTX_use_certificate_chain_file", NULL},
  822. {"SSLv23_client_method", NULL},
  823. {"SSL_pending", NULL},
  824. {"SSL_CTX_set_verify", NULL},
  825. {"SSL_shutdown", NULL},
  826. {"SSL_CTX_load_verify_locations", NULL},
  827. {"SSL_CTX_set_default_verify_paths", NULL},
  828. {"SSL_CTX_set_verify_depth", NULL},
  829. {"SSL_get_peer_certificate", NULL},
  830. {"SSL_get_version", NULL},
  831. {"SSL_get_current_cipher", NULL},
  832. {"SSL_CIPHER_get_name", NULL},
  833. {"SSL_CTX_check_private_key", NULL},
  834. {"SSL_CTX_set_session_id_context", NULL},
  835. {"SSL_CTX_ctrl", NULL},
  836. {"SSL_CTX_set_cipher_list", NULL},
  837. {NULL, NULL}};
  838. /* Similar array as ssl_sw. These functions could be located in different
  839. * lib. */
  840. #if !defined(NO_SSL)
  841. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  842. {"CRYPTO_set_locking_callback", NULL},
  843. {"CRYPTO_set_id_callback", NULL},
  844. {"ERR_get_error", NULL},
  845. {"ERR_error_string", NULL},
  846. {"ERR_remove_state", NULL},
  847. {"ERR_free_strings", NULL},
  848. {"ENGINE_cleanup", NULL},
  849. {"CONF_modules_unload", NULL},
  850. {"CRYPTO_cleanup_all_ex_data", NULL},
  851. {"EVP_cleanup", NULL},
  852. {NULL, NULL}};
  853. #endif /* NO_SSL */
  854. #endif /* NO_SSL_DL */
  855. static const char *month_names[] = {"Jan",
  856. "Feb",
  857. "Mar",
  858. "Apr",
  859. "May",
  860. "Jun",
  861. "Jul",
  862. "Aug",
  863. "Sep",
  864. "Oct",
  865. "Nov",
  866. "Dec"};
  867. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  868. * union u. */
  869. union usa {
  870. struct sockaddr sa;
  871. struct sockaddr_in sin;
  872. #if defined(USE_IPV6)
  873. struct sockaddr_in6 sin6;
  874. #endif
  875. };
  876. /* Describes a string (chunk of memory). */
  877. struct vec {
  878. const char *ptr;
  879. size_t len;
  880. };
  881. struct file {
  882. uint64_t size;
  883. time_t last_modified;
  884. FILE *fp;
  885. const char *membuf; /* Non-NULL if file data is in memory */
  886. int is_directory;
  887. int gzipped; /* set to 1 if the content is gzipped
  888. * in which case we need a content-encoding: gzip header */
  889. };
  890. #define STRUCT_FILE_INITIALIZER \
  891. { \
  892. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  893. }
  894. /* Describes listening socket, or socket which was accept()-ed by the master
  895. * thread and queued for future handling by the worker thread. */
  896. struct socket {
  897. SOCKET sock; /* Listening socket */
  898. union usa lsa; /* Local socket address */
  899. union usa rsa; /* Remote socket address */
  900. unsigned char is_ssl; /* Is port SSL-ed */
  901. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  902. * port */
  903. };
  904. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  905. enum {
  906. CGI_EXTENSIONS,
  907. CGI_ENVIRONMENT,
  908. PUT_DELETE_PASSWORDS_FILE,
  909. CGI_INTERPRETER,
  910. PROTECT_URI,
  911. AUTHENTICATION_DOMAIN,
  912. SSI_EXTENSIONS,
  913. THROTTLE,
  914. ACCESS_LOG_FILE,
  915. ENABLE_DIRECTORY_LISTING,
  916. ERROR_LOG_FILE,
  917. GLOBAL_PASSWORDS_FILE,
  918. INDEX_FILES,
  919. ENABLE_KEEP_ALIVE,
  920. ACCESS_CONTROL_LIST,
  921. EXTRA_MIME_TYPES,
  922. LISTENING_PORTS,
  923. DOCUMENT_ROOT,
  924. SSL_CERTIFICATE,
  925. NUM_THREADS,
  926. RUN_AS_USER,
  927. REWRITE,
  928. HIDE_FILES,
  929. REQUEST_TIMEOUT,
  930. SSL_DO_VERIFY_PEER,
  931. SSL_CA_PATH,
  932. SSL_CA_FILE,
  933. SSL_VERIFY_DEPTH,
  934. SSL_DEFAULT_VERIFY_PATHS,
  935. SSL_CIPHER_LIST,
  936. SSL_PROTOCOL_VERSION,
  937. #if defined(USE_WEBSOCKET)
  938. WEBSOCKET_TIMEOUT,
  939. #endif
  940. DECODE_URL,
  941. #if defined(USE_LUA)
  942. LUA_PRELOAD_FILE,
  943. LUA_SCRIPT_EXTENSIONS,
  944. LUA_SERVER_PAGE_EXTENSIONS,
  945. #endif
  946. #if defined(USE_DUKTAPE)
  947. DUKTAPE_SCRIPT_EXTENSIONS,
  948. #endif
  949. #if defined(USE_WEBSOCKET)
  950. WEBSOCKET_ROOT,
  951. #endif
  952. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  953. LUA_WEBSOCKET_EXTENSIONS,
  954. #endif
  955. ACCESS_CONTROL_ALLOW_ORIGIN,
  956. ERROR_PAGES,
  957. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  958. * socket option typedef TCP_NODELAY. */
  959. STATIC_FILE_MAX_AGE,
  960. NUM_OPTIONS
  961. };
  962. /* Config option name, config types, default value */
  963. static struct mg_option config_options[] = {
  964. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  965. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  966. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  967. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  968. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  969. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  970. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  971. {"throttle", CONFIG_TYPE_STRING, NULL},
  972. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  973. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  974. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  975. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  976. {"index_files",
  977. CONFIG_TYPE_STRING,
  978. #ifdef USE_LUA
  979. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  980. "index.shtml,index.php"},
  981. #else
  982. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  983. #endif
  984. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  985. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  986. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  987. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  988. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  989. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  990. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  991. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  992. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  993. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  994. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  995. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  996. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  997. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  998. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  999. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1000. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1001. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1002. #if defined(USE_WEBSOCKET)
  1003. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1004. #endif
  1005. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1006. #if defined(USE_LUA)
  1007. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1008. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1009. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1010. #endif
  1011. #if defined(USE_DUKTAPE)
  1012. {"_experimental_duktape_script_pattern",
  1013. CONFIG_TYPE_EXT_PATTERN,
  1014. "**.ssjs$"}, /* TODO: redefine parameter */
  1015. #endif
  1016. #if defined(USE_WEBSOCKET)
  1017. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1018. #endif
  1019. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1020. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1021. #endif
  1022. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1023. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1024. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1025. {"_experimental_static_file_max_age",
  1026. CONFIG_TYPE_NUMBER,
  1027. "3600"}, /* TODO: redefine parameter */
  1028. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1029. /* Check if the config_options and the corresponding enum have compatible
  1030. * sizes. */
  1031. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1032. == (NUM_OPTIONS + 1),
  1033. "config_options and enum not sync");
  1034. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1035. struct mg_handler_info {
  1036. /* Name/Pattern of the URI. */
  1037. char *uri;
  1038. size_t uri_len;
  1039. /* handler type */
  1040. int handler_type;
  1041. /* Handler for http/https or authorization requests. */
  1042. mg_request_handler handler;
  1043. /* Handler for ws/wss (websocket) requests. */
  1044. mg_websocket_connect_handler connect_handler;
  1045. mg_websocket_ready_handler ready_handler;
  1046. mg_websocket_data_handler data_handler;
  1047. mg_websocket_close_handler close_handler;
  1048. /* Handler for authorization requests */
  1049. mg_authorization_handler auth_handler;
  1050. /* User supplied argument for the handler function. */
  1051. void *cbdata;
  1052. /* next handler in a linked list */
  1053. struct mg_handler_info *next;
  1054. };
  1055. struct mg_context {
  1056. volatile int stop_flag; /* Should we stop event loop */
  1057. SSL_CTX *ssl_ctx; /* SSL context */
  1058. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1059. struct mg_callbacks callbacks; /* User-defined callback function */
  1060. void *user_data; /* User-defined data */
  1061. int context_type; /* 1 = server context, 2 = client context */
  1062. struct socket *listening_sockets;
  1063. in_port_t *listening_ports;
  1064. unsigned int num_listening_sockets;
  1065. volatile int
  1066. running_worker_threads; /* Number of currently running worker threads */
  1067. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1068. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1069. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1070. volatile int sq_head; /* Head of the socket queue */
  1071. volatile int sq_tail; /* Tail of the socket queue */
  1072. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1073. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1074. pthread_t masterthreadid; /* The master thread ID */
  1075. unsigned int
  1076. cfg_worker_threads; /* The number of configured worker threads. */
  1077. pthread_t *workerthreadids; /* The worker thread IDs */
  1078. time_t start_time; /* Server start time, used for authentication */
  1079. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1080. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1081. unsigned long nonce_count; /* Used nonces, used for authentication */
  1082. char *systemName; /* What operating system is running */
  1083. /* linked list of uri handlers */
  1084. struct mg_handler_info *handlers;
  1085. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1086. /* linked list of shared lua websockets */
  1087. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1088. #endif
  1089. #ifdef USE_TIMERS
  1090. struct ttimers *timers;
  1091. #endif
  1092. };
  1093. struct mg_connection {
  1094. struct mg_request_info request_info;
  1095. struct mg_context *ctx;
  1096. SSL *ssl; /* SSL descriptor */
  1097. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1098. struct socket client; /* Connected client */
  1099. time_t conn_birth_time; /* Time (wall clock) when connection was
  1100. * established */
  1101. struct timespec req_time; /* Time (since system start) when the request
  1102. * was received */
  1103. int64_t num_bytes_sent; /* Total bytes sent to client */
  1104. int64_t content_len; /* Content-Length header value */
  1105. int64_t consumed_content; /* How many bytes of content have been read */
  1106. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1107. * data available, 2: all data read */
  1108. size_t chunk_remainder; /* Unread data from the last chunk */
  1109. char *buf; /* Buffer for received data */
  1110. char *path_info; /* PATH_INFO part of the URL */
  1111. int must_close; /* 1 if connection must be closed */
  1112. int in_error_handler; /* 1 if in handler for user defined error
  1113. * pages */
  1114. int internal_error; /* 1 if an error occured while processing the
  1115. * request */
  1116. int buf_size; /* Buffer size */
  1117. int request_len; /* Size of the request + headers in a buffer */
  1118. int data_len; /* Total size of data in a buffer */
  1119. int status_code; /* HTTP reply status code, e.g. 200 */
  1120. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1121. * throttle */
  1122. time_t last_throttle_time; /* Last time throttled data was sent */
  1123. int64_t last_throttle_bytes; /* Bytes sent this second */
  1124. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1125. * atomic transmissions for websockets */
  1126. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1127. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1128. #endif
  1129. };
  1130. static pthread_key_t sTlsKey; /* Thread local storage index */
  1131. static int sTlsInit = 0;
  1132. static int thread_idx_max = 0;
  1133. struct mg_workerTLS {
  1134. int is_master;
  1135. unsigned long thread_idx;
  1136. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1137. HANDLE pthread_cond_helper_mutex;
  1138. #endif
  1139. };
  1140. /* Directory entry */
  1141. struct de {
  1142. struct mg_connection *conn;
  1143. char *file_name;
  1144. struct file file;
  1145. };
  1146. #if defined(USE_WEBSOCKET)
  1147. static int is_websocket_protocol(const struct mg_connection *conn);
  1148. #else
  1149. #define is_websocket_protocol(conn) (0)
  1150. #endif
  1151. static int
  1152. mg_atomic_inc(volatile int *addr)
  1153. {
  1154. int ret;
  1155. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1156. /* Depending on the SDK, this function uses either
  1157. * (volatile unsigned int *) or (volatile LONG *),
  1158. * so whatever you use, the other SDK is likely to raise a warning. */
  1159. ret = InterlockedIncrement((volatile long *)addr);
  1160. #elif defined(__GNUC__) \
  1161. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1162. ret = __sync_add_and_fetch(addr, 1);
  1163. #else
  1164. ret = (++(*addr));
  1165. #endif
  1166. return ret;
  1167. }
  1168. static int
  1169. mg_atomic_dec(volatile int *addr)
  1170. {
  1171. int ret;
  1172. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1173. /* Depending on the SDK, this function uses either
  1174. * (volatile unsigned int *) or (volatile LONG *),
  1175. * so whatever you use, the other SDK is likely to raise a warning. */
  1176. ret = InterlockedDecrement((volatile long *)addr);
  1177. #elif defined(__GNUC__) \
  1178. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1179. ret = __sync_sub_and_fetch(addr, 1);
  1180. #else
  1181. ret = (--(*addr));
  1182. #endif
  1183. return ret;
  1184. }
  1185. #if !defined(NO_THREAD_NAME)
  1186. #if defined(_WIN32) && defined(_MSC_VER)
  1187. /* Set the thread name for debugging purposes in Visual Studio
  1188. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1189. */
  1190. #pragma pack(push, 8)
  1191. typedef struct tagTHREADNAME_INFO {
  1192. DWORD dwType; /* Must be 0x1000. */
  1193. LPCSTR szName; /* Pointer to name (in user addr space). */
  1194. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1195. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1196. } THREADNAME_INFO;
  1197. #pragma pack(pop)
  1198. #elif defined(__linux__)
  1199. #include <sys/prctl.h>
  1200. #include <sys/sendfile.h>
  1201. #endif
  1202. static void
  1203. mg_set_thread_name(const char *name)
  1204. {
  1205. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1206. mg_snprintf(
  1207. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1208. #if defined(_WIN32)
  1209. #if defined(_MSC_VER)
  1210. /* Windows and Visual Studio Compiler */
  1211. __try
  1212. {
  1213. THREADNAME_INFO info;
  1214. info.dwType = 0x1000;
  1215. info.szName = threadName;
  1216. info.dwThreadID = ~0U;
  1217. info.dwFlags = 0;
  1218. RaiseException(0x406D1388,
  1219. 0,
  1220. sizeof(info) / sizeof(ULONG_PTR),
  1221. (ULONG_PTR *)&info);
  1222. }
  1223. __except(EXCEPTION_EXECUTE_HANDLER)
  1224. {
  1225. }
  1226. #elif defined(__MINGW32__)
  1227. /* No option known to set thread name for MinGW */
  1228. #endif
  1229. #elif defined(__GLIBC__) \
  1230. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1231. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1232. (void)pthread_setname_np(pthread_self(), threadName);
  1233. #elif defined(__linux__)
  1234. /* on linux we can use the old prctl function */
  1235. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1236. #endif
  1237. }
  1238. #else /* !defined(NO_THREAD_NAME) */
  1239. void
  1240. mg_set_thread_name(const char *threadName)
  1241. {
  1242. }
  1243. #endif
  1244. #if defined(MG_LEGACY_INTERFACE)
  1245. const char **
  1246. mg_get_valid_option_names(void)
  1247. {
  1248. /* This function is deprecated. Use mg_get_valid_options instead. */
  1249. static const char *
  1250. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1251. int i;
  1252. for (i = 0; config_options[i].name != NULL; i++) {
  1253. data[i * 2] = config_options[i].name;
  1254. data[i * 2 + 1] = config_options[i].default_value;
  1255. }
  1256. return data;
  1257. }
  1258. #endif
  1259. const struct mg_option *
  1260. mg_get_valid_options(void)
  1261. {
  1262. return config_options;
  1263. }
  1264. static int
  1265. is_file_in_memory(const struct mg_connection *conn,
  1266. const char *path,
  1267. struct file *filep)
  1268. {
  1269. size_t size = 0;
  1270. if (!conn || !filep) {
  1271. return 0;
  1272. }
  1273. if (conn->ctx->callbacks.open_file) {
  1274. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1275. if (filep->membuf != NULL) {
  1276. /* NOTE: override filep->size only on success. Otherwise, it might
  1277. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1278. filep->size = size;
  1279. }
  1280. }
  1281. return filep->membuf != NULL;
  1282. }
  1283. static int
  1284. is_file_opened(const struct file *filep)
  1285. {
  1286. if (!filep) {
  1287. return 0;
  1288. }
  1289. return filep->membuf != NULL || filep->fp != NULL;
  1290. }
  1291. static int
  1292. mg_fopen(const struct mg_connection *conn,
  1293. const char *path,
  1294. const char *mode,
  1295. struct file *filep)
  1296. {
  1297. struct stat st;
  1298. if (!filep) {
  1299. return 0;
  1300. }
  1301. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1302. * only get the file status. They should not work on different members of
  1303. * the same structure (bad cohesion). */
  1304. memset(filep, 0, sizeof(*filep));
  1305. if (stat(path, &st) == 0) {
  1306. filep->size = (uint64_t)(st.st_size);
  1307. }
  1308. if (!is_file_in_memory(conn, path, filep)) {
  1309. #ifdef _WIN32
  1310. wchar_t wbuf[PATH_MAX], wmode[20];
  1311. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1312. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1313. filep->fp = _wfopen(wbuf, wmode);
  1314. #else
  1315. /* Linux et al already use unicode. No need to convert. */
  1316. filep->fp = fopen(path, mode);
  1317. #endif
  1318. }
  1319. return is_file_opened(filep);
  1320. }
  1321. static void
  1322. mg_fclose(struct file *filep)
  1323. {
  1324. if (filep != NULL && filep->fp != NULL) {
  1325. fclose(filep->fp);
  1326. }
  1327. }
  1328. static void
  1329. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1330. {
  1331. for (; *src != '\0' && n > 1; n--) {
  1332. *dst++ = *src++;
  1333. }
  1334. *dst = '\0';
  1335. }
  1336. static int
  1337. lowercase(const char *s)
  1338. {
  1339. return tolower(*(const unsigned char *)s);
  1340. }
  1341. int
  1342. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1343. {
  1344. int diff = 0;
  1345. if (len > 0) {
  1346. do {
  1347. diff = lowercase(s1++) - lowercase(s2++);
  1348. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1349. }
  1350. return diff;
  1351. }
  1352. static int
  1353. mg_strcasecmp(const char *s1, const char *s2)
  1354. {
  1355. int diff;
  1356. do {
  1357. diff = lowercase(s1++) - lowercase(s2++);
  1358. } while (diff == 0 && s1[-1] != '\0');
  1359. return diff;
  1360. }
  1361. static char *
  1362. mg_strndup(const char *ptr, size_t len)
  1363. {
  1364. char *p;
  1365. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1366. mg_strlcpy(p, ptr, len + 1);
  1367. }
  1368. return p;
  1369. }
  1370. static char *
  1371. mg_strdup(const char *str)
  1372. {
  1373. return mg_strndup(str, strlen(str));
  1374. }
  1375. static const char *
  1376. mg_strcasestr(const char *big_str, const char *small_str)
  1377. {
  1378. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1379. if (big_len >= small_len) {
  1380. for (i = 0; i <= (big_len - small_len); i++) {
  1381. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1382. return big_str + i;
  1383. }
  1384. }
  1385. }
  1386. return NULL;
  1387. }
  1388. /* Return null terminated string of given maximum length.
  1389. * Report errors if length is exceeded. */
  1390. static void
  1391. mg_vsnprintf(const struct mg_connection *conn,
  1392. int *truncated,
  1393. char *buf,
  1394. size_t buflen,
  1395. const char *fmt,
  1396. va_list ap)
  1397. {
  1398. int n, ok;
  1399. if (buflen == 0) {
  1400. return;
  1401. }
  1402. #ifdef __clang__
  1403. #pragma clang diagnostic push
  1404. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1405. /* Using fmt as a non-literal is intended here, since it is mostly called
  1406. * indirectly by mg_snprintf */
  1407. #endif
  1408. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1409. ok = (n >= 0) && ((size_t)n < buflen);
  1410. #ifdef __clang__
  1411. #pragma clang diagnostic pop
  1412. #endif
  1413. if (ok) {
  1414. if (truncated) {
  1415. *truncated = 0;
  1416. }
  1417. } else {
  1418. if (truncated) {
  1419. *truncated = 1;
  1420. }
  1421. mg_cry(conn,
  1422. "truncating vsnprintf buffer: [%.*s]",
  1423. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1424. buf);
  1425. n = (int)buflen - 1;
  1426. }
  1427. buf[n] = '\0';
  1428. }
  1429. static void
  1430. mg_snprintf(const struct mg_connection *conn,
  1431. int *truncated,
  1432. char *buf,
  1433. size_t buflen,
  1434. const char *fmt,
  1435. ...)
  1436. {
  1437. va_list ap;
  1438. va_start(ap, fmt);
  1439. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1440. va_end(ap);
  1441. }
  1442. static int
  1443. get_option_index(const char *name)
  1444. {
  1445. int i;
  1446. for (i = 0; config_options[i].name != NULL; i++) {
  1447. if (strcmp(config_options[i].name, name) == 0) {
  1448. return i;
  1449. }
  1450. }
  1451. return -1;
  1452. }
  1453. const char *
  1454. mg_get_option(const struct mg_context *ctx, const char *name)
  1455. {
  1456. int i;
  1457. if ((i = get_option_index(name)) == -1) {
  1458. return NULL;
  1459. } else if (!ctx || ctx->config[i] == NULL) {
  1460. return "";
  1461. } else {
  1462. return ctx->config[i];
  1463. }
  1464. }
  1465. struct mg_context *
  1466. mg_get_context(const struct mg_connection *conn)
  1467. {
  1468. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1469. }
  1470. void *
  1471. mg_get_user_data(const struct mg_context *ctx)
  1472. {
  1473. return (ctx == NULL) ? NULL : ctx->user_data;
  1474. }
  1475. void
  1476. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1477. {
  1478. if (conn != NULL) {
  1479. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1480. }
  1481. }
  1482. void *
  1483. mg_get_user_connection_data(const struct mg_connection *conn)
  1484. {
  1485. if (conn != NULL) {
  1486. return conn->request_info.conn_data;
  1487. }
  1488. return NULL;
  1489. }
  1490. size_t
  1491. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1492. {
  1493. size_t i;
  1494. if (!ctx) {
  1495. return 0;
  1496. }
  1497. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1498. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1499. ports[i] = ctx->listening_ports[i];
  1500. }
  1501. return i;
  1502. }
  1503. int
  1504. mg_get_server_ports(const struct mg_context *ctx,
  1505. int size,
  1506. struct mg_server_ports *ports)
  1507. {
  1508. int i, cnt = 0;
  1509. if (size <= 0) {
  1510. return -1;
  1511. }
  1512. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1513. if (!ctx) {
  1514. return -1;
  1515. }
  1516. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1517. return -1;
  1518. }
  1519. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1520. ports[cnt].port = ctx->listening_ports[i];
  1521. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1522. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1523. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1524. /* IPv4 */
  1525. ports[cnt].protocol = 1;
  1526. cnt++;
  1527. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1528. /* IPv6 */
  1529. ports[cnt].protocol = 3;
  1530. cnt++;
  1531. }
  1532. }
  1533. return cnt;
  1534. }
  1535. static void
  1536. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1537. {
  1538. buf[0] = '\0';
  1539. if (!usa) {
  1540. return;
  1541. }
  1542. if (usa->sa.sa_family == AF_INET) {
  1543. getnameinfo(&usa->sa,
  1544. sizeof(usa->sin),
  1545. buf,
  1546. (unsigned)len,
  1547. NULL,
  1548. 0,
  1549. NI_NUMERICHOST);
  1550. }
  1551. #if defined(USE_IPV6)
  1552. else if (usa->sa.sa_family == AF_INET6) {
  1553. getnameinfo(&usa->sa,
  1554. sizeof(usa->sin6),
  1555. buf,
  1556. (unsigned)len,
  1557. NULL,
  1558. 0,
  1559. NI_NUMERICHOST);
  1560. }
  1561. #endif
  1562. }
  1563. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1564. * included in all responses other than 100, 101, 5xx. */
  1565. static void
  1566. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1567. {
  1568. struct tm *tm;
  1569. tm = gmtime(t);
  1570. if (tm != NULL) {
  1571. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1572. } else {
  1573. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1574. buf[buf_len - 1] = '\0';
  1575. }
  1576. }
  1577. /* difftime for struct timespec. Return value is in seconds. */
  1578. static double
  1579. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1580. {
  1581. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1582. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1583. }
  1584. /* Print error message to the opened error log stream. */
  1585. void
  1586. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1587. {
  1588. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1589. va_list ap;
  1590. struct file fi;
  1591. time_t timestamp;
  1592. va_start(ap, fmt);
  1593. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1594. va_end(ap);
  1595. buf[sizeof(buf) - 1] = 0;
  1596. if (!conn) {
  1597. puts(buf);
  1598. return;
  1599. }
  1600. /* Do not lock when getting the callback value, here and below.
  1601. * I suppose this is fine, since function cannot disappear in the
  1602. * same way string option can. */
  1603. if ((conn->ctx->callbacks.log_message == NULL)
  1604. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1605. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1606. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1607. == 0) {
  1608. fi.fp = NULL;
  1609. }
  1610. } else {
  1611. fi.fp = NULL;
  1612. }
  1613. if (fi.fp != NULL) {
  1614. flockfile(fi.fp);
  1615. timestamp = time(NULL);
  1616. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1617. fprintf(fi.fp,
  1618. "[%010lu] [error] [client %s] ",
  1619. (unsigned long)timestamp,
  1620. src_addr);
  1621. if (conn->request_info.request_method != NULL) {
  1622. fprintf(fi.fp,
  1623. "%s %s: ",
  1624. conn->request_info.request_method,
  1625. conn->request_info.request_uri);
  1626. }
  1627. fprintf(fi.fp, "%s", buf);
  1628. fputc('\n', fi.fp);
  1629. fflush(fi.fp);
  1630. funlockfile(fi.fp);
  1631. mg_fclose(&fi);
  1632. }
  1633. }
  1634. }
  1635. /* Return fake connection structure. Used for logging, if connection
  1636. * is not applicable at the moment of logging. */
  1637. static struct mg_connection *
  1638. fc(struct mg_context *ctx)
  1639. {
  1640. static struct mg_connection fake_connection;
  1641. fake_connection.ctx = ctx;
  1642. return &fake_connection;
  1643. }
  1644. const char *
  1645. mg_version(void)
  1646. {
  1647. return CIVETWEB_VERSION;
  1648. }
  1649. const struct mg_request_info *
  1650. mg_get_request_info(const struct mg_connection *conn)
  1651. {
  1652. if (!conn) {
  1653. return NULL;
  1654. }
  1655. return &conn->request_info;
  1656. }
  1657. /* Skip the characters until one of the delimiters characters found.
  1658. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1659. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1660. * Delimiters can be quoted with quotechar. */
  1661. static char *
  1662. skip_quoted(char **buf,
  1663. const char *delimiters,
  1664. const char *whitespace,
  1665. char quotechar)
  1666. {
  1667. char *p, *begin_word, *end_word, *end_whitespace;
  1668. begin_word = *buf;
  1669. end_word = begin_word + strcspn(begin_word, delimiters);
  1670. /* Check for quotechar */
  1671. if (end_word > begin_word) {
  1672. p = end_word - 1;
  1673. while (*p == quotechar) {
  1674. /* While the delimiter is quoted, look for the next delimiter. */
  1675. /* This happens, e.g., in calls from parse_auth_header,
  1676. * if the user name contains a " character. */
  1677. /* If there is anything beyond end_word, copy it. */
  1678. if (*end_word != '\0') {
  1679. size_t end_off = strcspn(end_word + 1, delimiters);
  1680. memmove(p, end_word, end_off + 1);
  1681. p += end_off; /* p must correspond to end_word - 1 */
  1682. end_word += end_off + 1;
  1683. } else {
  1684. *p = '\0';
  1685. break;
  1686. }
  1687. }
  1688. for (p++; p < end_word; p++) {
  1689. *p = '\0';
  1690. }
  1691. }
  1692. if (*end_word == '\0') {
  1693. *buf = end_word;
  1694. } else {
  1695. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1696. for (p = end_word; p < end_whitespace; p++) {
  1697. *p = '\0';
  1698. }
  1699. *buf = end_whitespace;
  1700. }
  1701. return begin_word;
  1702. }
  1703. /* Simplified version of skip_quoted without quote char
  1704. * and whitespace == delimiters */
  1705. static char *
  1706. skip(char **buf, const char *delimiters)
  1707. {
  1708. return skip_quoted(buf, delimiters, delimiters, 0);
  1709. }
  1710. /* Return HTTP header value, or NULL if not found. */
  1711. static const char *
  1712. get_header(const struct mg_request_info *ri, const char *name)
  1713. {
  1714. int i;
  1715. if (ri) {
  1716. for (i = 0; i < ri->num_headers; i++) {
  1717. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1718. return ri->http_headers[i].value;
  1719. }
  1720. }
  1721. }
  1722. return NULL;
  1723. }
  1724. const char *
  1725. mg_get_header(const struct mg_connection *conn, const char *name)
  1726. {
  1727. if (!conn) {
  1728. return NULL;
  1729. }
  1730. return get_header(&conn->request_info, name);
  1731. }
  1732. /* A helper function for traversing a comma separated list of values.
  1733. * It returns a list pointer shifted to the next value, or NULL if the end
  1734. * of the list found.
  1735. * Value is stored in val vector. If value has form "x=y", then eq_val
  1736. * vector is initialized to point to the "y" part, and val vector length
  1737. * is adjusted to point only to "x". */
  1738. static const char *
  1739. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1740. {
  1741. if (val == NULL || list == NULL || *list == '\0') {
  1742. /* End of the list */
  1743. list = NULL;
  1744. } else {
  1745. val->ptr = list;
  1746. if ((list = strchr(val->ptr, ',')) != NULL) {
  1747. /* Comma found. Store length and shift the list ptr */
  1748. val->len = ((size_t)(list - val->ptr));
  1749. list++;
  1750. } else {
  1751. /* This value is the last one */
  1752. list = val->ptr + strlen(val->ptr);
  1753. val->len = ((size_t)(list - val->ptr));
  1754. }
  1755. if (eq_val != NULL) {
  1756. /* Value has form "x=y", adjust pointers and lengths
  1757. * so that val points to "x", and eq_val points to "y". */
  1758. eq_val->len = 0;
  1759. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1760. if (eq_val->ptr != NULL) {
  1761. eq_val->ptr++; /* Skip over '=' character */
  1762. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1763. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1764. }
  1765. }
  1766. }
  1767. return list;
  1768. }
  1769. /* Perform case-insensitive match of string against pattern */
  1770. static int
  1771. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1772. {
  1773. const char *or_str;
  1774. size_t i;
  1775. int j, len, res;
  1776. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1777. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1778. return res > 0 ? res : match_prefix(or_str + 1,
  1779. (size_t)((pattern + pattern_len)
  1780. - (or_str + 1)),
  1781. str);
  1782. }
  1783. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1784. if (pattern[i] == '?' && str[j] != '\0') {
  1785. continue;
  1786. } else if (pattern[i] == '$') {
  1787. return str[j] == '\0' ? j : -1;
  1788. } else if (pattern[i] == '*') {
  1789. i++;
  1790. if (pattern[i] == '*') {
  1791. i++;
  1792. len = (int)strlen(str + j);
  1793. } else {
  1794. len = (int)strcspn(str + j, "/");
  1795. }
  1796. if (i == pattern_len) {
  1797. return j + len;
  1798. }
  1799. do {
  1800. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1801. } while (res == -1 && len-- > 0);
  1802. return res == -1 ? -1 : j + res + len;
  1803. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1804. return -1;
  1805. }
  1806. }
  1807. return j;
  1808. }
  1809. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1810. * This function must tolerate situations when connection info is not
  1811. * set up, for example if request parsing failed. */
  1812. static int
  1813. should_keep_alive(const struct mg_connection *conn)
  1814. {
  1815. if (conn != NULL) {
  1816. const char *http_version = conn->request_info.http_version;
  1817. const char *header = mg_get_header(conn, "Connection");
  1818. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1819. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1820. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1821. || (header == NULL && http_version
  1822. && 0 != strcmp(http_version, "1.1"))) {
  1823. return 0;
  1824. }
  1825. return 1;
  1826. }
  1827. return 0;
  1828. }
  1829. static int
  1830. should_decode_url(const struct mg_connection *conn)
  1831. {
  1832. if (!conn || !conn->ctx) {
  1833. return 0;
  1834. }
  1835. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1836. }
  1837. static const char *
  1838. suggest_connection_header(const struct mg_connection *conn)
  1839. {
  1840. return should_keep_alive(conn) ? "keep-alive" : "close";
  1841. }
  1842. static int
  1843. send_no_cache_header(struct mg_connection *conn)
  1844. {
  1845. /* Send all current and obsolete cache opt-out directives. */
  1846. return mg_printf(conn,
  1847. "Cache-Control: no-cache, no-store, "
  1848. "must-revalidate, private, max-age=0\r\n"
  1849. "Pragma: no-cache\r\n"
  1850. "Expires: 0\r\n");
  1851. }
  1852. static int
  1853. send_static_cache_header(struct mg_connection *conn)
  1854. {
  1855. /* Read the server config to check how long a file may be cached.
  1856. * The configuration is in seconds. */
  1857. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1858. if (max_age <= 0) {
  1859. /* 0 means "do not cache". All values <0 are reserved
  1860. * and may be used differently in the future. */
  1861. /* If a file should not be cached, do not only send
  1862. * max-age=0, but also pragmas and Expires headers. */
  1863. return send_no_cache_header(conn);
  1864. }
  1865. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1866. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1867. /* See also https://www.mnot.net/cache_docs/ */
  1868. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1869. }
  1870. static void handle_file_based_request(struct mg_connection *conn,
  1871. const char *path,
  1872. struct file *filep);
  1873. static int
  1874. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1875. static const char *
  1876. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1877. {
  1878. /* See IANA HTTP status code assignment:
  1879. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1880. */
  1881. switch (response_code) {
  1882. /* RFC2616 Section 10.1 - Informational 1xx */
  1883. case 100:
  1884. return "Continue"; /* RFC2616 Section 10.1.1 */
  1885. case 101:
  1886. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1887. case 102:
  1888. return "Processing"; /* RFC2518 Section 10.1 */
  1889. /* RFC2616 Section 10.2 - Successful 2xx */
  1890. case 200:
  1891. return "OK"; /* RFC2616 Section 10.2.1 */
  1892. case 201:
  1893. return "Created"; /* RFC2616 Section 10.2.2 */
  1894. case 202:
  1895. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1896. case 203:
  1897. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1898. case 204:
  1899. return "No Content"; /* RFC2616 Section 10.2.5 */
  1900. case 205:
  1901. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1902. case 206:
  1903. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1904. case 207:
  1905. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1906. case 208:
  1907. return "Already Reported"; /* RFC5842 Section 7.1 */
  1908. case 226:
  1909. return "IM used"; /* RFC3229 Section 10.4.1 */
  1910. /* RFC2616 Section 10.3 - Redirection 3xx */
  1911. case 300:
  1912. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1913. case 301:
  1914. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1915. case 302:
  1916. return "Found"; /* RFC2616 Section 10.3.3 */
  1917. case 303:
  1918. return "See Other"; /* RFC2616 Section 10.3.4 */
  1919. case 304:
  1920. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1921. case 305:
  1922. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1923. case 307:
  1924. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1925. case 308:
  1926. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1927. /* RFC2616 Section 10.4 - Client Error 4xx */
  1928. case 400:
  1929. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1930. case 401:
  1931. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1932. case 402:
  1933. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1934. case 403:
  1935. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1936. case 404:
  1937. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1938. case 405:
  1939. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1940. case 406:
  1941. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1942. case 407:
  1943. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1944. case 408:
  1945. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1946. case 409:
  1947. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1948. case 410:
  1949. return "Gone"; /* RFC2616 Section 10.4.11 */
  1950. case 411:
  1951. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1952. case 412:
  1953. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1954. case 413:
  1955. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1956. case 414:
  1957. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1958. case 415:
  1959. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1960. case 416:
  1961. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1962. case 417:
  1963. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1964. case 421:
  1965. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  1966. case 422:
  1967. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1968. * Section 11.2 */
  1969. case 423:
  1970. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1971. case 424:
  1972. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1973. * Section 11.4 */
  1974. case 426:
  1975. return "Upgrade Required"; /* RFC 2817 Section 4 */
  1976. case 428:
  1977. return "Precondition Required"; /* RFC 6585, Section 3 */
  1978. case 429:
  1979. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1980. case 431:
  1981. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1982. case 451:
  1983. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1984. * Section 3 */
  1985. /* RFC2616 Section 10.5 - Server Error 5xx */
  1986. case 500:
  1987. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1988. case 501:
  1989. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1990. case 502:
  1991. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1992. case 503:
  1993. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1994. case 504:
  1995. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1996. case 505:
  1997. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1998. case 506:
  1999. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2000. case 507:
  2001. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2002. * Section 11.5 */
  2003. case 508:
  2004. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2005. case 510:
  2006. return "Not Extended"; /* RFC 2774, Section 7 */
  2007. case 511:
  2008. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2009. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2010. * E.g., "de facto" standards due to common use, ... */
  2011. case 418:
  2012. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2013. case 419:
  2014. return "Authentication Timeout"; /* common use */
  2015. default:
  2016. /* This error code is unknown. This should not happen. */
  2017. if (conn) {
  2018. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2019. }
  2020. /* Return at least a category according to RFC 2616 Section 10. */
  2021. if (response_code >= 100 && response_code < 200) {
  2022. /* Unknown informational status code */
  2023. return "Information";
  2024. }
  2025. if (response_code >= 200 && response_code < 300) {
  2026. /* Unknown success code */
  2027. return "Success";
  2028. }
  2029. if (response_code >= 300 && response_code < 400) {
  2030. /* Unknown redirection code */
  2031. return "Redirection";
  2032. }
  2033. if (response_code >= 400 && response_code < 500) {
  2034. /* Unknown request error code */
  2035. return "Client Error";
  2036. }
  2037. if (response_code >= 500 && response_code < 600) {
  2038. /* Unknown server error code */
  2039. return "Server Error";
  2040. }
  2041. /* Response code not even within reasonable range */
  2042. return "";
  2043. }
  2044. }
  2045. static void send_http_error(struct mg_connection *,
  2046. int,
  2047. PRINTF_FORMAT_STRING(const char *fmt),
  2048. ...) PRINTF_ARGS(3, 4);
  2049. static void
  2050. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2051. {
  2052. char buf[MG_BUF_LEN];
  2053. va_list ap;
  2054. int len, i, page_handler_found, scope, truncated;
  2055. char date[64];
  2056. time_t curtime = time(NULL);
  2057. const char *error_handler = NULL;
  2058. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2059. const char *error_page_file_ext, *tstr;
  2060. const char *status_text = mg_get_response_code_text(status, conn);
  2061. if (conn == NULL) {
  2062. return;
  2063. }
  2064. conn->status_code = status;
  2065. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2066. || conn->ctx->callbacks.http_error(conn, status)) {
  2067. if (!conn->in_error_handler) {
  2068. /* Send user defined error pages, if defined */
  2069. error_handler = conn->ctx->config[ERROR_PAGES];
  2070. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2071. page_handler_found = 0;
  2072. if (error_handler != NULL) {
  2073. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2074. switch (scope) {
  2075. case 1: /* Handler for specific error, e.g. 404 error */
  2076. mg_snprintf(conn,
  2077. &truncated,
  2078. buf,
  2079. sizeof(buf) - 32,
  2080. "%serror%03u.",
  2081. error_handler,
  2082. status);
  2083. break;
  2084. case 2: /* Handler for error group, e.g., 5xx error handler
  2085. * for all server errors (500-599) */
  2086. mg_snprintf(conn,
  2087. &truncated,
  2088. buf,
  2089. sizeof(buf) - 32,
  2090. "%serror%01uxx.",
  2091. error_handler,
  2092. status / 100);
  2093. break;
  2094. default: /* Handler for all errors */
  2095. mg_snprintf(conn,
  2096. &truncated,
  2097. buf,
  2098. sizeof(buf) - 32,
  2099. "%serror.",
  2100. error_handler);
  2101. break;
  2102. }
  2103. /* String truncation in buf may only occur if error_handler
  2104. * is too long. This string is from the config, not from a
  2105. * client. */
  2106. (void)truncated;
  2107. len = (int)strlen(buf);
  2108. tstr = strchr(error_page_file_ext, '.');
  2109. while (tstr) {
  2110. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2111. i++)
  2112. buf[len + i - 1] = tstr[i];
  2113. buf[len + i - 1] = 0;
  2114. if (mg_stat(conn, buf, &error_page_file)) {
  2115. page_handler_found = 1;
  2116. break;
  2117. }
  2118. tstr = strchr(tstr + i, '.');
  2119. }
  2120. }
  2121. }
  2122. if (page_handler_found) {
  2123. conn->in_error_handler = 1;
  2124. handle_file_based_request(conn, buf, &error_page_file);
  2125. conn->in_error_handler = 0;
  2126. return;
  2127. }
  2128. }
  2129. /* No custom error page. Send default error page. */
  2130. gmt_time_string(date, sizeof(date), &curtime);
  2131. conn->must_close = 1;
  2132. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2133. send_no_cache_header(conn);
  2134. mg_printf(conn,
  2135. "Date: %s\r\n"
  2136. "Connection: close\r\n\r\n",
  2137. date);
  2138. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2139. if (status > 199 && status != 204 && status != 304) {
  2140. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2141. if (fmt != NULL) {
  2142. va_start(ap, fmt);
  2143. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2144. va_end(ap);
  2145. mg_write(conn, buf, strlen(buf));
  2146. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2147. }
  2148. } else {
  2149. /* No body allowed. Close the connection. */
  2150. DEBUG_TRACE("Error %i", status);
  2151. }
  2152. }
  2153. }
  2154. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2155. /* Create substitutes for POSIX functions in Win32. */
  2156. #if defined(__MINGW32__)
  2157. /* Show no warning in case system functions are not used. */
  2158. #pragma GCC diagnostic push
  2159. #pragma GCC diagnostic ignored "-Wunused-function"
  2160. #endif
  2161. static int
  2162. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2163. {
  2164. (void)unused;
  2165. *mutex = CreateMutex(NULL, FALSE, NULL);
  2166. return *mutex == NULL ? -1 : 0;
  2167. }
  2168. static int
  2169. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2170. {
  2171. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2172. }
  2173. static int
  2174. pthread_mutex_lock(pthread_mutex_t *mutex)
  2175. {
  2176. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2177. }
  2178. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2179. static int
  2180. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2181. {
  2182. switch (WaitForSingleObject(*mutex, 0)) {
  2183. case WAIT_OBJECT_0:
  2184. return 0;
  2185. case WAIT_TIMEOUT:
  2186. return -2; /* EBUSY */
  2187. }
  2188. return -1;
  2189. }
  2190. #endif
  2191. static int
  2192. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2193. {
  2194. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2195. }
  2196. #ifndef WIN_PTHREADS_TIME_H
  2197. static int
  2198. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2199. {
  2200. FILETIME ft;
  2201. ULARGE_INTEGER li;
  2202. BOOL ok = FALSE;
  2203. double d;
  2204. static double perfcnt_per_sec = 0.0;
  2205. if (tp) {
  2206. memset(tp, 0, sizeof(*tp));
  2207. if (clk_id == CLOCK_REALTIME) {
  2208. GetSystemTimeAsFileTime(&ft);
  2209. li.LowPart = ft.dwLowDateTime;
  2210. li.HighPart = ft.dwHighDateTime;
  2211. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2212. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2213. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2214. ok = TRUE;
  2215. } else if (clk_id == CLOCK_MONOTONIC) {
  2216. if (perfcnt_per_sec == 0.0) {
  2217. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2218. perfcnt_per_sec = 1.0 / li.QuadPart;
  2219. }
  2220. if (perfcnt_per_sec != 0.0) {
  2221. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2222. d = li.QuadPart * perfcnt_per_sec;
  2223. tp->tv_sec = (time_t)d;
  2224. d -= tp->tv_sec;
  2225. tp->tv_nsec = (long)(d * 1.0E9);
  2226. ok = TRUE;
  2227. }
  2228. }
  2229. }
  2230. return ok ? 0 : -1;
  2231. }
  2232. #endif
  2233. static int
  2234. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2235. {
  2236. (void)unused;
  2237. InitializeCriticalSection(&cv->threadIdSec);
  2238. cv->waitingthreadcount = 0;
  2239. cv->waitingthreadhdls =
  2240. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2241. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2242. }
  2243. static int
  2244. pthread_cond_timedwait(pthread_cond_t *cv,
  2245. pthread_mutex_t *mutex,
  2246. const struct timespec *abstime)
  2247. {
  2248. struct mg_workerTLS *tls =
  2249. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2250. int ok;
  2251. struct timespec tsnow;
  2252. int64_t nsnow, nswaitabs, nswaitrel;
  2253. DWORD mswaitrel;
  2254. EnterCriticalSection(&cv->threadIdSec);
  2255. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2256. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2257. tls->pthread_cond_helper_mutex;
  2258. cv->waitingthreadcount++;
  2259. LeaveCriticalSection(&cv->threadIdSec);
  2260. if (abstime) {
  2261. clock_gettime(CLOCK_REALTIME, &tsnow);
  2262. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2263. nswaitabs =
  2264. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2265. nswaitrel = nswaitabs - nsnow;
  2266. if (nswaitrel < 0) {
  2267. nswaitrel = 0;
  2268. }
  2269. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2270. } else {
  2271. mswaitrel = INFINITE;
  2272. }
  2273. pthread_mutex_unlock(mutex);
  2274. ok = (WAIT_OBJECT_0
  2275. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2276. pthread_mutex_lock(mutex);
  2277. return ok ? 0 : -1;
  2278. }
  2279. static int
  2280. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2281. {
  2282. return pthread_cond_timedwait(cv, mutex, NULL);
  2283. }
  2284. static int
  2285. pthread_cond_signal(pthread_cond_t *cv)
  2286. {
  2287. int i;
  2288. HANDLE wkup = NULL;
  2289. BOOL ok = FALSE;
  2290. EnterCriticalSection(&cv->threadIdSec);
  2291. if (cv->waitingthreadcount) {
  2292. wkup = cv->waitingthreadhdls[0];
  2293. ok = SetEvent(wkup);
  2294. for (i = 1; i < cv->waitingthreadcount; i++) {
  2295. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2296. }
  2297. cv->waitingthreadcount--;
  2298. assert(ok);
  2299. }
  2300. LeaveCriticalSection(&cv->threadIdSec);
  2301. return ok ? 0 : 1;
  2302. }
  2303. static int
  2304. pthread_cond_broadcast(pthread_cond_t *cv)
  2305. {
  2306. EnterCriticalSection(&cv->threadIdSec);
  2307. while (cv->waitingthreadcount) {
  2308. pthread_cond_signal(cv);
  2309. }
  2310. LeaveCriticalSection(&cv->threadIdSec);
  2311. return 0;
  2312. }
  2313. static int
  2314. pthread_cond_destroy(pthread_cond_t *cv)
  2315. {
  2316. EnterCriticalSection(&cv->threadIdSec);
  2317. assert(cv->waitingthreadcount == 0);
  2318. mg_free(cv->waitingthreadhdls);
  2319. cv->waitingthreadhdls = 0;
  2320. LeaveCriticalSection(&cv->threadIdSec);
  2321. DeleteCriticalSection(&cv->threadIdSec);
  2322. return 0;
  2323. }
  2324. #if defined(__MINGW32__)
  2325. /* Enable unused function warning again */
  2326. #pragma GCC diagnostic pop
  2327. #endif
  2328. /* For Windows, change all slashes to backslashes in path names. */
  2329. static void
  2330. change_slashes_to_backslashes(char *path)
  2331. {
  2332. int i;
  2333. for (i = 0; path[i] != '\0'; i++) {
  2334. if (path[i] == '/') {
  2335. path[i] = '\\';
  2336. }
  2337. /* remove double backslash (check i > 0 to preserve UNC paths,
  2338. * like \\server\file.txt) */
  2339. if ((path[i] == '\\') && (i > 0)) {
  2340. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2341. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2342. }
  2343. }
  2344. }
  2345. }
  2346. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2347. * wbuf and wbuf_len is a target buffer and its length. */
  2348. static void
  2349. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2350. {
  2351. char buf[PATH_MAX], buf2[PATH_MAX];
  2352. mg_strlcpy(buf, path, sizeof(buf));
  2353. change_slashes_to_backslashes(buf);
  2354. /* Convert to Unicode and back. If doubly-converted string does not
  2355. * match the original, something is fishy, reject. */
  2356. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2357. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2358. WideCharToMultiByte(
  2359. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2360. if (strcmp(buf, buf2) != 0) {
  2361. wbuf[0] = L'\0';
  2362. }
  2363. }
  2364. #if defined(_WIN32_WCE)
  2365. /* Create substitutes for POSIX functions in Win32. */
  2366. #if defined(__MINGW32__)
  2367. /* Show no warning in case system functions are not used. */
  2368. #pragma GCC diagnostic push
  2369. #pragma GCC diagnostic ignored "-Wunused-function"
  2370. #endif
  2371. static time_t
  2372. time(time_t *ptime)
  2373. {
  2374. time_t t;
  2375. SYSTEMTIME st;
  2376. FILETIME ft;
  2377. GetSystemTime(&st);
  2378. SystemTimeToFileTime(&st, &ft);
  2379. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2380. if (ptime != NULL) {
  2381. *ptime = t;
  2382. }
  2383. return t;
  2384. }
  2385. static struct tm *
  2386. localtime(const time_t *ptime, struct tm *ptm)
  2387. {
  2388. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2389. FILETIME ft, lft;
  2390. SYSTEMTIME st;
  2391. TIME_ZONE_INFORMATION tzinfo;
  2392. if (ptm == NULL) {
  2393. return NULL;
  2394. }
  2395. *(int64_t *)&ft = t;
  2396. FileTimeToLocalFileTime(&ft, &lft);
  2397. FileTimeToSystemTime(&lft, &st);
  2398. ptm->tm_year = st.wYear - 1900;
  2399. ptm->tm_mon = st.wMonth - 1;
  2400. ptm->tm_wday = st.wDayOfWeek;
  2401. ptm->tm_mday = st.wDay;
  2402. ptm->tm_hour = st.wHour;
  2403. ptm->tm_min = st.wMinute;
  2404. ptm->tm_sec = st.wSecond;
  2405. ptm->tm_yday = 0; /* hope nobody uses this */
  2406. ptm->tm_isdst =
  2407. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2408. return ptm;
  2409. }
  2410. static struct tm *
  2411. gmtime(const time_t *ptime, struct tm *ptm)
  2412. {
  2413. /* FIXME(lsm): fix this. */
  2414. return localtime(ptime, ptm);
  2415. }
  2416. static size_t
  2417. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2418. {
  2419. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2420. return 0;
  2421. }
  2422. #if defined(__MINGW32__)
  2423. /* Enable unused function warning again */
  2424. #pragma GCC diagnostic pop
  2425. #endif
  2426. #endif
  2427. /* Windows happily opens files with some garbage at the end of file name.
  2428. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2429. * "a.cgi", despite one would expect an error back.
  2430. * This function returns non-0 if path ends with some garbage. */
  2431. static int
  2432. path_cannot_disclose_cgi(const char *path)
  2433. {
  2434. static const char *allowed_last_characters = "_-";
  2435. int last = path[strlen(path) - 1];
  2436. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2437. }
  2438. static int
  2439. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2440. {
  2441. wchar_t wbuf[PATH_MAX];
  2442. WIN32_FILE_ATTRIBUTE_DATA info;
  2443. time_t creation_time;
  2444. if (!filep) {
  2445. return 0;
  2446. }
  2447. memset(filep, 0, sizeof(*filep));
  2448. if (conn && is_file_in_memory(conn, path, filep)) {
  2449. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2450. * memset */
  2451. filep->last_modified = time(NULL);
  2452. /* last_modified = now ... assumes the file may change during runtime,
  2453. * so every mg_fopen call may return different data */
  2454. /* last_modified = conn->ctx.start_time;
  2455. * May be used it the data does not change during runtime. This allows
  2456. * browser caching. Since we do not know, we have to assume the file
  2457. * in memory may change. */
  2458. return 1;
  2459. }
  2460. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2461. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2462. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2463. filep->last_modified =
  2464. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2465. info.ftLastWriteTime.dwHighDateTime);
  2466. /* On Windows, the file creation time can be higher than the
  2467. * modification time, e.g. when a file is copied.
  2468. * Since the Last-Modified timestamp is used for caching
  2469. * it should be based on the most recent timestamp. */
  2470. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2471. info.ftCreationTime.dwHighDateTime);
  2472. if (creation_time > filep->last_modified) {
  2473. filep->last_modified = creation_time;
  2474. }
  2475. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2476. /* If file name is fishy, reset the file structure and return
  2477. * error.
  2478. * Note it is important to reset, not just return the error, cause
  2479. * functions like is_file_opened() check the struct. */
  2480. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2481. memset(filep, 0, sizeof(*filep));
  2482. return 0;
  2483. }
  2484. return 1;
  2485. }
  2486. return 0;
  2487. }
  2488. static int
  2489. mg_remove(const char *path)
  2490. {
  2491. wchar_t wbuf[PATH_MAX];
  2492. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2493. return DeleteFileW(wbuf) ? 0 : -1;
  2494. }
  2495. static int
  2496. mg_mkdir(const char *path, int mode)
  2497. {
  2498. char buf[PATH_MAX];
  2499. wchar_t wbuf[PATH_MAX];
  2500. (void)mode;
  2501. mg_strlcpy(buf, path, sizeof(buf));
  2502. change_slashes_to_backslashes(buf);
  2503. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2504. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2505. }
  2506. /* Create substitutes for POSIX functions in Win32. */
  2507. #if defined(__MINGW32__)
  2508. /* Show no warning in case system functions are not used. */
  2509. #pragma GCC diagnostic push
  2510. #pragma GCC diagnostic ignored "-Wunused-function"
  2511. #endif
  2512. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2513. static DIR *
  2514. opendir(const char *name)
  2515. {
  2516. DIR *dir = NULL;
  2517. wchar_t wpath[PATH_MAX];
  2518. DWORD attrs;
  2519. if (name == NULL) {
  2520. SetLastError(ERROR_BAD_ARGUMENTS);
  2521. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2522. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2523. } else {
  2524. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2525. attrs = GetFileAttributesW(wpath);
  2526. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2527. == FILE_ATTRIBUTE_DIRECTORY)) {
  2528. (void)wcscat(wpath, L"\\*");
  2529. dir->handle = FindFirstFileW(wpath, &dir->info);
  2530. dir->result.d_name[0] = '\0';
  2531. } else {
  2532. mg_free(dir);
  2533. dir = NULL;
  2534. }
  2535. }
  2536. return dir;
  2537. }
  2538. static int
  2539. closedir(DIR *dir)
  2540. {
  2541. int result = 0;
  2542. if (dir != NULL) {
  2543. if (dir->handle != INVALID_HANDLE_VALUE)
  2544. result = FindClose(dir->handle) ? 0 : -1;
  2545. mg_free(dir);
  2546. } else {
  2547. result = -1;
  2548. SetLastError(ERROR_BAD_ARGUMENTS);
  2549. }
  2550. return result;
  2551. }
  2552. static struct dirent *
  2553. readdir(DIR *dir)
  2554. {
  2555. struct dirent *result = 0;
  2556. if (dir) {
  2557. if (dir->handle != INVALID_HANDLE_VALUE) {
  2558. result = &dir->result;
  2559. (void)WideCharToMultiByte(CP_UTF8,
  2560. 0,
  2561. dir->info.cFileName,
  2562. -1,
  2563. result->d_name,
  2564. sizeof(result->d_name),
  2565. NULL,
  2566. NULL);
  2567. if (!FindNextFileW(dir->handle, &dir->info)) {
  2568. (void)FindClose(dir->handle);
  2569. dir->handle = INVALID_HANDLE_VALUE;
  2570. }
  2571. } else {
  2572. SetLastError(ERROR_FILE_NOT_FOUND);
  2573. }
  2574. } else {
  2575. SetLastError(ERROR_BAD_ARGUMENTS);
  2576. }
  2577. return result;
  2578. }
  2579. #ifndef HAVE_POLL
  2580. static int
  2581. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2582. {
  2583. struct timeval tv;
  2584. fd_set set;
  2585. unsigned int i;
  2586. int result;
  2587. SOCKET maxfd = 0;
  2588. memset(&tv, 0, sizeof(tv));
  2589. tv.tv_sec = milliseconds / 1000;
  2590. tv.tv_usec = (milliseconds % 1000) * 1000;
  2591. FD_ZERO(&set);
  2592. for (i = 0; i < n; i++) {
  2593. FD_SET((SOCKET)pfd[i].fd, &set);
  2594. pfd[i].revents = 0;
  2595. if (pfd[i].fd > maxfd) {
  2596. maxfd = pfd[i].fd;
  2597. }
  2598. }
  2599. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2600. for (i = 0; i < n; i++) {
  2601. if (FD_ISSET(pfd[i].fd, &set)) {
  2602. pfd[i].revents = POLLIN;
  2603. }
  2604. }
  2605. }
  2606. return result;
  2607. }
  2608. #endif /* HAVE_POLL */
  2609. #if defined(__MINGW32__)
  2610. /* Enable unused function warning again */
  2611. #pragma GCC diagnostic pop
  2612. #endif
  2613. static void
  2614. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2615. {
  2616. (void)conn; /* Unused. */
  2617. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2618. }
  2619. int
  2620. mg_start_thread(mg_thread_func_t f, void *p)
  2621. {
  2622. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2623. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2624. */
  2625. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2626. == ((uintptr_t)(-1L)))
  2627. ? -1
  2628. : 0);
  2629. #else
  2630. return (
  2631. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2632. ? -1
  2633. : 0);
  2634. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2635. }
  2636. /* Start a thread storing the thread context. */
  2637. static int
  2638. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2639. void *p,
  2640. pthread_t *threadidptr)
  2641. {
  2642. uintptr_t uip;
  2643. HANDLE threadhandle;
  2644. int result = -1;
  2645. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2646. threadhandle = (HANDLE)uip;
  2647. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2648. *threadidptr = threadhandle;
  2649. result = 0;
  2650. }
  2651. return result;
  2652. }
  2653. /* Wait for a thread to finish. */
  2654. static int
  2655. mg_join_thread(pthread_t threadid)
  2656. {
  2657. int result;
  2658. DWORD dwevent;
  2659. result = -1;
  2660. dwevent = WaitForSingleObject(threadid, INFINITE);
  2661. if (dwevent == WAIT_FAILED) {
  2662. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2663. } else {
  2664. if (dwevent == WAIT_OBJECT_0) {
  2665. CloseHandle(threadid);
  2666. result = 0;
  2667. }
  2668. }
  2669. return result;
  2670. }
  2671. #if !defined(NO_SSL_DL)
  2672. /* Create substitutes for POSIX functions in Win32. */
  2673. #if defined(__MINGW32__)
  2674. /* Show no warning in case system functions are not used. */
  2675. #pragma GCC diagnostic push
  2676. #pragma GCC diagnostic ignored "-Wunused-function"
  2677. #endif
  2678. static HANDLE
  2679. dlopen(const char *dll_name, int flags)
  2680. {
  2681. wchar_t wbuf[PATH_MAX];
  2682. (void)flags;
  2683. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2684. return LoadLibraryW(wbuf);
  2685. }
  2686. static int
  2687. dlclose(void *handle)
  2688. {
  2689. int result;
  2690. if (FreeLibrary((HMODULE)handle) != 0) {
  2691. result = 0;
  2692. } else {
  2693. result = -1;
  2694. }
  2695. return result;
  2696. }
  2697. #if defined(__MINGW32__)
  2698. /* Enable unused function warning again */
  2699. #pragma GCC diagnostic pop
  2700. #endif
  2701. #endif
  2702. #if !defined(NO_CGI)
  2703. #define SIGKILL (0)
  2704. static int
  2705. kill(pid_t pid, int sig_num)
  2706. {
  2707. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2708. (void)CloseHandle((HANDLE)pid);
  2709. return 0;
  2710. }
  2711. static void
  2712. trim_trailing_whitespaces(char *s)
  2713. {
  2714. char *e = s + strlen(s) - 1;
  2715. while (e > s && isspace(*(unsigned char *)e)) {
  2716. *e-- = '\0';
  2717. }
  2718. }
  2719. static pid_t
  2720. spawn_process(struct mg_connection *conn,
  2721. const char *prog,
  2722. char *envblk,
  2723. char *envp[],
  2724. int fdin,
  2725. int fdout,
  2726. int fderr,
  2727. const char *dir)
  2728. {
  2729. HANDLE me;
  2730. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2731. cmdline[PATH_MAX], buf[PATH_MAX];
  2732. int truncated;
  2733. struct file file = STRUCT_FILE_INITIALIZER;
  2734. STARTUPINFOA si;
  2735. PROCESS_INFORMATION pi = {0};
  2736. (void)envp;
  2737. memset(&si, 0, sizeof(si));
  2738. si.cb = sizeof(si);
  2739. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2740. si.wShowWindow = SW_HIDE;
  2741. me = GetCurrentProcess();
  2742. DuplicateHandle(me,
  2743. (HANDLE)_get_osfhandle(fdin),
  2744. me,
  2745. &si.hStdInput,
  2746. 0,
  2747. TRUE,
  2748. DUPLICATE_SAME_ACCESS);
  2749. DuplicateHandle(me,
  2750. (HANDLE)_get_osfhandle(fdout),
  2751. me,
  2752. &si.hStdOutput,
  2753. 0,
  2754. TRUE,
  2755. DUPLICATE_SAME_ACCESS);
  2756. DuplicateHandle(me,
  2757. (HANDLE)_get_osfhandle(fderr),
  2758. me,
  2759. &si.hStdError,
  2760. 0,
  2761. TRUE,
  2762. DUPLICATE_SAME_ACCESS);
  2763. /* If CGI file is a script, try to read the interpreter line */
  2764. interp = conn->ctx->config[CGI_INTERPRETER];
  2765. if (interp == NULL) {
  2766. buf[0] = buf[1] = '\0';
  2767. /* Read the first line of the script into the buffer */
  2768. mg_snprintf(
  2769. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2770. if (truncated) {
  2771. pi.hProcess = (pid_t)-1;
  2772. goto spawn_cleanup;
  2773. }
  2774. if (mg_fopen(conn, cmdline, "r", &file)) {
  2775. p = (char *)file.membuf;
  2776. mg_fgets(buf, sizeof(buf), &file, &p);
  2777. mg_fclose(&file);
  2778. buf[sizeof(buf) - 1] = '\0';
  2779. }
  2780. if (buf[0] == '#' && buf[1] == '!') {
  2781. trim_trailing_whitespaces(buf + 2);
  2782. } else {
  2783. buf[2] = '\0';
  2784. }
  2785. interp = buf + 2;
  2786. }
  2787. if (interp[0] != '\0') {
  2788. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2789. interp = full_interp;
  2790. }
  2791. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2792. if (interp[0] != '\0') {
  2793. mg_snprintf(conn,
  2794. &truncated,
  2795. cmdline,
  2796. sizeof(cmdline),
  2797. "\"%s\" \"%s\\%s\"",
  2798. interp,
  2799. full_dir,
  2800. prog);
  2801. } else {
  2802. mg_snprintf(conn,
  2803. &truncated,
  2804. cmdline,
  2805. sizeof(cmdline),
  2806. "\"%s\\%s\"",
  2807. full_dir,
  2808. prog);
  2809. }
  2810. if (truncated) {
  2811. pi.hProcess = (pid_t)-1;
  2812. goto spawn_cleanup;
  2813. }
  2814. DEBUG_TRACE("Running [%s]", cmdline);
  2815. if (CreateProcessA(NULL,
  2816. cmdline,
  2817. NULL,
  2818. NULL,
  2819. TRUE,
  2820. CREATE_NEW_PROCESS_GROUP,
  2821. envblk,
  2822. NULL,
  2823. &si,
  2824. &pi) == 0) {
  2825. mg_cry(
  2826. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2827. pi.hProcess = (pid_t)-1;
  2828. /* goto spawn_cleanup; */
  2829. }
  2830. spawn_cleanup:
  2831. (void)CloseHandle(si.hStdOutput);
  2832. (void)CloseHandle(si.hStdError);
  2833. (void)CloseHandle(si.hStdInput);
  2834. if (pi.hThread != NULL) {
  2835. (void)CloseHandle(pi.hThread);
  2836. }
  2837. return (pid_t)pi.hProcess;
  2838. }
  2839. #endif /* !NO_CGI */
  2840. static int
  2841. set_non_blocking_mode(SOCKET sock)
  2842. {
  2843. unsigned long on = 1;
  2844. return ioctlsocket(sock, (long)FIONBIO, &on);
  2845. }
  2846. #else
  2847. static int
  2848. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2849. {
  2850. struct stat st;
  2851. if (!filep) {
  2852. return 0;
  2853. }
  2854. memset(filep, 0, sizeof(*filep));
  2855. if (conn && is_file_in_memory(conn, path, filep)) {
  2856. return 1;
  2857. }
  2858. if (0 == stat(path, &st)) {
  2859. filep->size = (uint64_t)(st.st_size);
  2860. filep->last_modified = st.st_mtime;
  2861. filep->is_directory = S_ISDIR(st.st_mode);
  2862. return 1;
  2863. }
  2864. return 0;
  2865. }
  2866. static void
  2867. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2868. {
  2869. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2870. if (conn) {
  2871. mg_cry(conn,
  2872. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2873. __func__,
  2874. strerror(ERRNO));
  2875. }
  2876. }
  2877. }
  2878. int
  2879. mg_start_thread(mg_thread_func_t func, void *param)
  2880. {
  2881. pthread_t thread_id;
  2882. pthread_attr_t attr;
  2883. int result;
  2884. (void)pthread_attr_init(&attr);
  2885. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2886. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2887. /* Compile-time option to control stack size,
  2888. * e.g. -DUSE_STACK_SIZE=16384 */
  2889. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2890. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2891. result = pthread_create(&thread_id, &attr, func, param);
  2892. pthread_attr_destroy(&attr);
  2893. return result;
  2894. }
  2895. /* Start a thread storing the thread context. */
  2896. static int
  2897. mg_start_thread_with_id(mg_thread_func_t func,
  2898. void *param,
  2899. pthread_t *threadidptr)
  2900. {
  2901. pthread_t thread_id;
  2902. pthread_attr_t attr;
  2903. int result;
  2904. (void)pthread_attr_init(&attr);
  2905. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2906. /* Compile-time option to control stack size,
  2907. * e.g. -DUSE_STACK_SIZE=16384 */
  2908. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2909. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2910. result = pthread_create(&thread_id, &attr, func, param);
  2911. pthread_attr_destroy(&attr);
  2912. if ((result == 0) && (threadidptr != NULL)) {
  2913. *threadidptr = thread_id;
  2914. }
  2915. return result;
  2916. }
  2917. /* Wait for a thread to finish. */
  2918. static int
  2919. mg_join_thread(pthread_t threadid)
  2920. {
  2921. int result;
  2922. result = pthread_join(threadid, NULL);
  2923. return result;
  2924. }
  2925. #ifndef NO_CGI
  2926. static pid_t
  2927. spawn_process(struct mg_connection *conn,
  2928. const char *prog,
  2929. char *envblk,
  2930. char *envp[],
  2931. int fdin,
  2932. int fdout,
  2933. int fderr,
  2934. const char *dir)
  2935. {
  2936. pid_t pid;
  2937. const char *interp;
  2938. (void)envblk;
  2939. if (conn == NULL) {
  2940. return 0;
  2941. }
  2942. if ((pid = fork()) == -1) {
  2943. /* Parent */
  2944. send_http_error(conn,
  2945. 500,
  2946. "Error: Creating CGI process\nfork(): %s",
  2947. strerror(ERRNO));
  2948. } else if (pid == 0) {
  2949. /* Child */
  2950. if (chdir(dir) != 0) {
  2951. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2952. } else if (dup2(fdin, 0) == -1) {
  2953. mg_cry(
  2954. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2955. } else if (dup2(fdout, 1) == -1) {
  2956. mg_cry(
  2957. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2958. } else if (dup2(fderr, 2) == -1) {
  2959. mg_cry(
  2960. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2961. } else {
  2962. /* Keep stderr and stdout in two different pipes.
  2963. * Stdout will be sent back to the client,
  2964. * stderr should go into a server error log. */
  2965. (void)close(fdin);
  2966. (void)close(fdout);
  2967. (void)close(fderr);
  2968. /* After exec, all signal handlers are restored to their default
  2969. * values, with one exception of SIGCHLD. According to
  2970. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2971. * leave unchanged after exec if it was set to be ignored. Restore
  2972. * it to default action. */
  2973. signal(SIGCHLD, SIG_DFL);
  2974. interp = conn->ctx->config[CGI_INTERPRETER];
  2975. if (interp == NULL) {
  2976. (void)execle(prog, prog, NULL, envp);
  2977. mg_cry(conn,
  2978. "%s: execle(%s): %s",
  2979. __func__,
  2980. prog,
  2981. strerror(ERRNO));
  2982. } else {
  2983. (void)execle(interp, interp, prog, NULL, envp);
  2984. mg_cry(conn,
  2985. "%s: execle(%s %s): %s",
  2986. __func__,
  2987. interp,
  2988. prog,
  2989. strerror(ERRNO));
  2990. }
  2991. }
  2992. exit(EXIT_FAILURE);
  2993. }
  2994. return pid;
  2995. }
  2996. #endif /* !NO_CGI */
  2997. static int
  2998. set_non_blocking_mode(SOCKET sock)
  2999. {
  3000. int flags;
  3001. flags = fcntl(sock, F_GETFL, 0);
  3002. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3003. return 0;
  3004. }
  3005. #endif /* _WIN32 */
  3006. /* End of initial operating system specific define block. */
  3007. /* Get a random number (independent of C rand function) */
  3008. static uint64_t
  3009. get_random(void)
  3010. {
  3011. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3012. static uint64_t lcg = 0; /* Linear congruential generator */
  3013. struct timespec now;
  3014. memset(&now, 0, sizeof(now));
  3015. clock_gettime(CLOCK_MONOTONIC, &now);
  3016. if (lfsr == 0) {
  3017. /* lfsr will be only 0 if has not been initialized,
  3018. * so this code is called only once. */
  3019. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3020. ^ ((uint64_t)(ptrdiff_t)&now) ^ ((uint64_t)pthread_self())
  3021. ^ (((uint64_t)time(NULL)) << 33);
  3022. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3023. + (uint64_t)(ptrdiff_t)&now;
  3024. } else {
  3025. /* Get the next step of both random number generators. */
  3026. lfsr = (lfsr >> 1)
  3027. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3028. << 63);
  3029. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3030. }
  3031. /* Combining two pseudo-random number generators and a high resolution part
  3032. * of the current server time will make it hard (impossible?) to guess the
  3033. * next number. */
  3034. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3035. }
  3036. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3037. * descriptor. Return number of bytes written. */
  3038. static int
  3039. push(struct mg_context *ctx,
  3040. FILE *fp,
  3041. SOCKET sock,
  3042. SSL *ssl,
  3043. const char *buf,
  3044. int len,
  3045. double timeout)
  3046. {
  3047. struct timespec start, now;
  3048. int n, err;
  3049. #ifdef _WIN32
  3050. typedef int len_t;
  3051. #else
  3052. typedef size_t len_t;
  3053. #endif
  3054. if (timeout > 0) {
  3055. memset(&start, 0, sizeof(start));
  3056. memset(&now, 0, sizeof(now));
  3057. clock_gettime(CLOCK_MONOTONIC, &start);
  3058. }
  3059. if (ctx == NULL) {
  3060. return -1;
  3061. }
  3062. #ifdef NO_SSL
  3063. if (ssl) {
  3064. return -1;
  3065. }
  3066. #endif
  3067. do {
  3068. #ifndef NO_SSL
  3069. if (ssl != NULL) {
  3070. n = SSL_write(ssl, buf, len);
  3071. if (n <= 0) {
  3072. err = SSL_get_error(ssl, n);
  3073. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3074. err = ERRNO;
  3075. } else {
  3076. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3077. return -1;
  3078. }
  3079. } else {
  3080. err = 0;
  3081. }
  3082. } else
  3083. #endif
  3084. if (fp != NULL) {
  3085. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3086. if (ferror(fp)) {
  3087. n = -1;
  3088. err = ERRNO;
  3089. } else {
  3090. err = 0;
  3091. }
  3092. } else {
  3093. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3094. err = (n < 0) ? ERRNO : 0;
  3095. }
  3096. if (ctx->stop_flag) {
  3097. return -1;
  3098. }
  3099. if ((n > 0) || (n == 0 && len == 0)) {
  3100. /* some data has been read, or no data was requested */
  3101. return n;
  3102. }
  3103. if (n == 0) {
  3104. /* shutdown of the socket at client side */
  3105. return -1;
  3106. }
  3107. if (n < 0) {
  3108. /* socket error - check errno */
  3109. DEBUG_TRACE("send() failed, error %d", err);
  3110. /* TODO: error handling depending on the error code.
  3111. * These codes are different between Windows and Linux.
  3112. */
  3113. return -1;
  3114. }
  3115. /* This code is not reached in the moment.
  3116. * ==> Fix the TODOs above first. */
  3117. if (timeout > 0) {
  3118. clock_gettime(CLOCK_MONOTONIC, &now);
  3119. }
  3120. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3121. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3122. used */
  3123. return -1;
  3124. }
  3125. static int64_t
  3126. push_all(struct mg_context *ctx,
  3127. FILE *fp,
  3128. SOCKET sock,
  3129. SSL *ssl,
  3130. const char *buf,
  3131. int64_t len)
  3132. {
  3133. double timeout = -1.0;
  3134. int64_t n, nwritten = 0;
  3135. if (ctx == NULL) {
  3136. return -1;
  3137. }
  3138. if (ctx->config[REQUEST_TIMEOUT]) {
  3139. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3140. }
  3141. while (len > 0 && ctx->stop_flag == 0) {
  3142. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3143. if (n < 0) {
  3144. if (nwritten == 0) {
  3145. nwritten = n; /* Propagate the error */
  3146. }
  3147. break;
  3148. } else if (n == 0) {
  3149. break; /* No more data to write */
  3150. } else {
  3151. nwritten += n;
  3152. len -= n;
  3153. }
  3154. }
  3155. return nwritten;
  3156. }
  3157. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3158. * Return negative value on error, or number of bytes read on success. */
  3159. static int
  3160. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3161. {
  3162. int nread, err;
  3163. struct timespec start, now;
  3164. #ifdef _WIN32
  3165. typedef int len_t;
  3166. #else
  3167. typedef size_t len_t;
  3168. #endif
  3169. if (timeout > 0) {
  3170. memset(&start, 0, sizeof(start));
  3171. memset(&now, 0, sizeof(now));
  3172. clock_gettime(CLOCK_MONOTONIC, &start);
  3173. }
  3174. do {
  3175. if (fp != NULL) {
  3176. /* Use read() instead of fread(), because if we're reading from the
  3177. * CGI pipe, fread() may block until IO buffer is filled up. We
  3178. * cannot afford to block and must pass all read bytes immediately
  3179. * to the client. */
  3180. nread = (int)read(fileno(fp), buf, (size_t)len);
  3181. err = (nread < 0) ? ERRNO : 0;
  3182. #ifndef NO_SSL
  3183. } else if (conn->ssl != NULL) {
  3184. nread = SSL_read(conn->ssl, buf, len);
  3185. if (nread <= 0) {
  3186. err = SSL_get_error(conn->ssl, nread);
  3187. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3188. err = ERRNO;
  3189. } else {
  3190. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3191. return -1;
  3192. }
  3193. } else {
  3194. err = 0;
  3195. }
  3196. #endif
  3197. } else {
  3198. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3199. err = (nread < 0) ? ERRNO : 0;
  3200. }
  3201. if (conn->ctx->stop_flag) {
  3202. return -1;
  3203. }
  3204. if ((nread > 0) || (nread == 0 && len == 0)) {
  3205. /* some data has been read, or no data was requested */
  3206. return nread;
  3207. }
  3208. if (nread == 0) {
  3209. /* shutdown of the socket at client side */
  3210. return -1;
  3211. }
  3212. if (nread < 0) {
  3213. /* socket error - check errno */
  3214. #ifdef _WIN32
  3215. if (err == WSAEWOULDBLOCK) {
  3216. /* standard case if called from close_socket_gracefully */
  3217. return -1;
  3218. } else if (err == WSAETIMEDOUT) {
  3219. /* timeout is handled by the while loop */
  3220. } else {
  3221. DEBUG_TRACE("recv() failed, error %d", err);
  3222. return -1;
  3223. }
  3224. #else
  3225. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3226. * if the timeout is reached and if the socket was set to non-
  3227. * blocking in close_socket_gracefully, so we can not distinguish
  3228. * here. We have to wait for the timeout in both cases for now.
  3229. */
  3230. if (err == EAGAIN || err == EWOULDBLOCK) {
  3231. /* standard case if called from close_socket_gracefully
  3232. * => should return -1 */
  3233. /* or timeout occured
  3234. * => the code must stay in the while loop */
  3235. } else {
  3236. DEBUG_TRACE("recv() failed, error %d", err);
  3237. return -1;
  3238. }
  3239. #endif
  3240. }
  3241. if (timeout > 0) {
  3242. clock_gettime(CLOCK_MONOTONIC, &now);
  3243. }
  3244. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3245. /* Timeout occured, but no data available. */
  3246. return -1;
  3247. }
  3248. static int
  3249. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3250. {
  3251. int n, nread = 0;
  3252. double timeout = -1.0;
  3253. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3254. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3255. }
  3256. while (len > 0 && conn->ctx->stop_flag == 0) {
  3257. n = pull(fp, conn, buf + nread, len, timeout);
  3258. if (n < 0) {
  3259. if (nread == 0) {
  3260. nread = n; /* Propagate the error */
  3261. }
  3262. break;
  3263. } else if (n == 0) {
  3264. break; /* No more data to read */
  3265. } else {
  3266. conn->consumed_content += n;
  3267. nread += n;
  3268. len -= n;
  3269. }
  3270. }
  3271. return nread;
  3272. }
  3273. static void
  3274. discard_unread_request_data(struct mg_connection *conn)
  3275. {
  3276. char buf[MG_BUF_LEN];
  3277. size_t to_read;
  3278. int nread;
  3279. if (conn == NULL) {
  3280. return;
  3281. }
  3282. to_read = sizeof(buf);
  3283. if (conn->is_chunked) {
  3284. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3285. * completely */
  3286. while (conn->is_chunked == 1) {
  3287. nread = mg_read(conn, buf, to_read);
  3288. if (nread <= 0) {
  3289. break;
  3290. }
  3291. }
  3292. } else {
  3293. /* Not chunked: content length is known */
  3294. while (conn->consumed_content < conn->content_len) {
  3295. if (to_read
  3296. > (size_t)(conn->content_len - conn->consumed_content)) {
  3297. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3298. }
  3299. nread = mg_read(conn, buf, to_read);
  3300. if (nread <= 0) {
  3301. break;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. static int
  3307. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3308. {
  3309. int64_t n, buffered_len, nread;
  3310. int64_t len64 =
  3311. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3312. * int, we may not read more
  3313. * bytes */
  3314. const char *body;
  3315. if (conn == NULL) {
  3316. return 0;
  3317. }
  3318. /* If Content-Length is not set for a PUT or POST request, read until
  3319. * socket is closed */
  3320. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3321. conn->content_len = INT64_MAX;
  3322. conn->must_close = 1;
  3323. }
  3324. nread = 0;
  3325. if (conn->consumed_content < conn->content_len) {
  3326. /* Adjust number of bytes to read. */
  3327. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3328. if (left_to_read < len64) {
  3329. /* Do not read more than the total content length of the request.
  3330. */
  3331. len64 = left_to_read;
  3332. }
  3333. /* Return buffered data */
  3334. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3335. - conn->consumed_content;
  3336. if (buffered_len > 0) {
  3337. if (len64 < buffered_len) {
  3338. buffered_len = len64;
  3339. }
  3340. body = conn->buf + conn->request_len + conn->consumed_content;
  3341. memcpy(buf, body, (size_t)buffered_len);
  3342. len64 -= buffered_len;
  3343. conn->consumed_content += buffered_len;
  3344. nread += buffered_len;
  3345. buf = (char *)buf + buffered_len;
  3346. }
  3347. /* We have returned all buffered data. Read new data from the remote
  3348. * socket.
  3349. */
  3350. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3351. nread += n;
  3352. } else {
  3353. nread = (nread > 0 ? nread : n);
  3354. }
  3355. }
  3356. return (int)nread;
  3357. }
  3358. static char
  3359. mg_getc(struct mg_connection *conn)
  3360. {
  3361. char c;
  3362. if (conn == NULL) {
  3363. return 0;
  3364. }
  3365. conn->content_len++;
  3366. if (mg_read_inner(conn, &c, 1) <= 0) {
  3367. return (char)0;
  3368. }
  3369. return c;
  3370. }
  3371. int
  3372. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3373. {
  3374. if (len > INT_MAX) {
  3375. len = INT_MAX;
  3376. }
  3377. if (conn == NULL) {
  3378. return 0;
  3379. }
  3380. if (conn->is_chunked) {
  3381. size_t all_read = 0;
  3382. while (len > 0) {
  3383. if (conn->chunk_remainder) {
  3384. /* copy from the remainder of the last received chunk */
  3385. long read_ret;
  3386. size_t read_now =
  3387. ((conn->chunk_remainder > len) ? (len)
  3388. : (conn->chunk_remainder));
  3389. conn->content_len += (int)read_now;
  3390. read_ret =
  3391. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3392. all_read += (size_t)read_ret;
  3393. conn->chunk_remainder -= read_now;
  3394. len -= read_now;
  3395. if (conn->chunk_remainder == 0) {
  3396. /* the rest of the data in the current chunk has been read
  3397. */
  3398. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3399. /* Protocol violation */
  3400. return -1;
  3401. }
  3402. }
  3403. } else {
  3404. /* fetch a new chunk */
  3405. int i = 0;
  3406. char lenbuf[64];
  3407. char *end = 0;
  3408. unsigned long chunkSize = 0;
  3409. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3410. lenbuf[i] = mg_getc(conn);
  3411. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3412. continue;
  3413. }
  3414. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3415. lenbuf[i + 1] = 0;
  3416. chunkSize = strtoul(lenbuf, &end, 16);
  3417. break;
  3418. }
  3419. if (!isalnum(lenbuf[i])) {
  3420. /* illegal character for chunk length */
  3421. return -1;
  3422. }
  3423. }
  3424. if ((end == NULL) || (*end != '\r')) {
  3425. /* chunksize not set correctly */
  3426. return -1;
  3427. }
  3428. conn->chunk_remainder = chunkSize;
  3429. if (chunkSize == 0) {
  3430. /* regular end of content */
  3431. conn->is_chunked = 2;
  3432. break;
  3433. }
  3434. }
  3435. }
  3436. return (int)all_read;
  3437. }
  3438. return mg_read_inner(conn, buf, len);
  3439. }
  3440. int
  3441. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3442. {
  3443. time_t now;
  3444. int64_t n, total, allowed;
  3445. if (conn == NULL) {
  3446. return 0;
  3447. }
  3448. if (conn->throttle > 0) {
  3449. if ((now = time(NULL)) != conn->last_throttle_time) {
  3450. conn->last_throttle_time = now;
  3451. conn->last_throttle_bytes = 0;
  3452. }
  3453. allowed = conn->throttle - conn->last_throttle_bytes;
  3454. if (allowed > (int64_t)len) {
  3455. allowed = (int64_t)len;
  3456. }
  3457. if ((total = push_all(conn->ctx,
  3458. NULL,
  3459. conn->client.sock,
  3460. conn->ssl,
  3461. (const char *)buf,
  3462. (int64_t)allowed)) == allowed) {
  3463. buf = (char *)buf + total;
  3464. conn->last_throttle_bytes += total;
  3465. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3466. allowed = conn->throttle > (int64_t)len - total
  3467. ? (int64_t)len - total
  3468. : conn->throttle;
  3469. if ((n = push_all(conn->ctx,
  3470. NULL,
  3471. conn->client.sock,
  3472. conn->ssl,
  3473. (const char *)buf,
  3474. (int64_t)allowed)) != allowed) {
  3475. break;
  3476. }
  3477. sleep(1);
  3478. conn->last_throttle_bytes = allowed;
  3479. conn->last_throttle_time = time(NULL);
  3480. buf = (char *)buf + n;
  3481. total += n;
  3482. }
  3483. }
  3484. } else {
  3485. total = push_all(conn->ctx,
  3486. NULL,
  3487. conn->client.sock,
  3488. conn->ssl,
  3489. (const char *)buf,
  3490. (int64_t)len);
  3491. }
  3492. return (int)total;
  3493. }
  3494. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3495. static int
  3496. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3497. {
  3498. va_list ap_copy;
  3499. size_t size = MG_BUF_LEN;
  3500. int len = -1;
  3501. *buf = NULL;
  3502. while (len < 0) {
  3503. if (*buf) {
  3504. mg_free(*buf);
  3505. }
  3506. *buf = (char *)mg_malloc(size *= 4);
  3507. if (!*buf) {
  3508. break;
  3509. }
  3510. va_copy(ap_copy, ap);
  3511. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3512. va_end(ap_copy);
  3513. *buf[size - 1] = 0;
  3514. }
  3515. return len;
  3516. }
  3517. /* Print message to buffer. If buffer is large enough to hold the message,
  3518. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3519. * and return allocated buffer. */
  3520. static int
  3521. alloc_vprintf(char **out_buf,
  3522. char *prealloc_buf,
  3523. size_t prealloc_size,
  3524. const char *fmt,
  3525. va_list ap)
  3526. {
  3527. va_list ap_copy;
  3528. int len;
  3529. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3530. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3531. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3532. * Therefore, we make two passes: on first pass, get required message
  3533. * length.
  3534. * On second pass, actually print the message. */
  3535. va_copy(ap_copy, ap);
  3536. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3537. va_end(ap_copy);
  3538. if (len < 0) {
  3539. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3540. * Switch to alternative code path that uses incremental allocations.
  3541. */
  3542. va_copy(ap_copy, ap);
  3543. len = alloc_vprintf2(out_buf, fmt, ap);
  3544. va_end(ap_copy);
  3545. } else if ((size_t)(len) >= prealloc_size) {
  3546. /* The pre-allocated buffer not large enough. */
  3547. /* Allocate a new buffer. */
  3548. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3549. if (!*out_buf) {
  3550. /* Allocation failed. Return -1 as "out of memory" error. */
  3551. return -1;
  3552. }
  3553. /* Buffer allocation successful. Store the string there. */
  3554. va_copy(ap_copy, ap);
  3555. IGNORE_UNUSED_RESULT(
  3556. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3557. va_end(ap_copy);
  3558. } else {
  3559. /* The pre-allocated buffer is large enough.
  3560. * Use it to store the string and return the address. */
  3561. va_copy(ap_copy, ap);
  3562. IGNORE_UNUSED_RESULT(
  3563. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3564. va_end(ap_copy);
  3565. *out_buf = prealloc_buf;
  3566. }
  3567. return len;
  3568. }
  3569. static int
  3570. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3571. {
  3572. char mem[MG_BUF_LEN];
  3573. char *buf = NULL;
  3574. int len;
  3575. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3576. len = mg_write(conn, buf, (size_t)len);
  3577. }
  3578. if (buf != mem && buf != NULL) {
  3579. mg_free(buf);
  3580. }
  3581. return len;
  3582. }
  3583. int
  3584. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3585. {
  3586. va_list ap;
  3587. int result;
  3588. va_start(ap, fmt);
  3589. result = mg_vprintf(conn, fmt, ap);
  3590. va_end(ap);
  3591. return result;
  3592. }
  3593. int
  3594. mg_url_decode(const char *src,
  3595. int src_len,
  3596. char *dst,
  3597. int dst_len,
  3598. int is_form_url_encoded)
  3599. {
  3600. int i, j, a, b;
  3601. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3602. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3603. if (i < src_len - 2 && src[i] == '%'
  3604. && isxdigit(*(const unsigned char *)(src + i + 1))
  3605. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3606. a = tolower(*(const unsigned char *)(src + i + 1));
  3607. b = tolower(*(const unsigned char *)(src + i + 2));
  3608. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3609. i += 2;
  3610. } else if (is_form_url_encoded && src[i] == '+') {
  3611. dst[j] = ' ';
  3612. } else {
  3613. dst[j] = src[i];
  3614. }
  3615. }
  3616. dst[j] = '\0'; /* Null-terminate the destination */
  3617. return i >= src_len ? j : -1;
  3618. }
  3619. int
  3620. mg_get_var(const char *data,
  3621. size_t data_len,
  3622. const char *name,
  3623. char *dst,
  3624. size_t dst_len)
  3625. {
  3626. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3627. }
  3628. int
  3629. mg_get_var2(const char *data,
  3630. size_t data_len,
  3631. const char *name,
  3632. char *dst,
  3633. size_t dst_len,
  3634. size_t occurrence)
  3635. {
  3636. const char *p, *e, *s;
  3637. size_t name_len;
  3638. int len;
  3639. if (dst == NULL || dst_len == 0) {
  3640. len = -2;
  3641. } else if (data == NULL || name == NULL || data_len == 0) {
  3642. len = -1;
  3643. dst[0] = '\0';
  3644. } else {
  3645. name_len = strlen(name);
  3646. e = data + data_len;
  3647. len = -1;
  3648. dst[0] = '\0';
  3649. /* data is "var1=val1&var2=val2...". Find variable first */
  3650. for (p = data; p + name_len < e; p++) {
  3651. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3652. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3653. /* Point p to variable value */
  3654. p += name_len + 1;
  3655. /* Point s to the end of the value */
  3656. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3657. if (s == NULL) {
  3658. s = e;
  3659. }
  3660. /* assert(s >= p); */
  3661. if (s < p) {
  3662. return -3;
  3663. }
  3664. /* Decode variable into destination buffer */
  3665. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3666. /* Redirect error code from -1 to -2 (destination buffer too
  3667. * small). */
  3668. if (len == -1) {
  3669. len = -2;
  3670. }
  3671. break;
  3672. }
  3673. }
  3674. }
  3675. return len;
  3676. }
  3677. int
  3678. mg_get_cookie(const char *cookie_header,
  3679. const char *var_name,
  3680. char *dst,
  3681. size_t dst_size)
  3682. {
  3683. const char *s, *p, *end;
  3684. int name_len, len = -1;
  3685. if (dst == NULL || dst_size == 0) {
  3686. len = -2;
  3687. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3688. len = -1;
  3689. dst[0] = '\0';
  3690. } else {
  3691. name_len = (int)strlen(var_name);
  3692. end = s + strlen(s);
  3693. dst[0] = '\0';
  3694. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3695. if (s[name_len] == '=') {
  3696. s += name_len + 1;
  3697. if ((p = strchr(s, ' ')) == NULL) {
  3698. p = end;
  3699. }
  3700. if (p[-1] == ';') {
  3701. p--;
  3702. }
  3703. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3704. s++;
  3705. p--;
  3706. }
  3707. if ((size_t)(p - s) < dst_size) {
  3708. len = (int)(p - s);
  3709. mg_strlcpy(dst, s, (size_t)len + 1);
  3710. } else {
  3711. len = -3;
  3712. }
  3713. break;
  3714. }
  3715. }
  3716. }
  3717. return len;
  3718. }
  3719. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3720. static void
  3721. base64_encode(const unsigned char *src, int src_len, char *dst)
  3722. {
  3723. static const char *b64 =
  3724. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3725. int i, j, a, b, c;
  3726. for (i = j = 0; i < src_len; i += 3) {
  3727. a = src[i];
  3728. b = i + 1 >= src_len ? 0 : src[i + 1];
  3729. c = i + 2 >= src_len ? 0 : src[i + 2];
  3730. dst[j++] = b64[a >> 2];
  3731. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3732. if (i + 1 < src_len) {
  3733. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3734. }
  3735. if (i + 2 < src_len) {
  3736. dst[j++] = b64[c & 63];
  3737. }
  3738. }
  3739. while (j % 4 != 0) {
  3740. dst[j++] = '=';
  3741. }
  3742. dst[j++] = '\0';
  3743. }
  3744. #endif
  3745. #if defined(USE_LUA)
  3746. static unsigned char
  3747. b64reverse(char letter)
  3748. {
  3749. if (letter >= 'A' && letter <= 'Z') {
  3750. return letter - 'A';
  3751. }
  3752. if (letter >= 'a' && letter <= 'z') {
  3753. return letter - 'a' + 26;
  3754. }
  3755. if (letter >= '0' && letter <= '9') {
  3756. return letter - '0' + 52;
  3757. }
  3758. if (letter == '+') {
  3759. return 62;
  3760. }
  3761. if (letter == '/') {
  3762. return 63;
  3763. }
  3764. if (letter == '=') {
  3765. return 255; /* normal end */
  3766. }
  3767. return 254; /* error */
  3768. }
  3769. static int
  3770. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3771. {
  3772. int i;
  3773. unsigned char a, b, c, d;
  3774. *dst_len = 0;
  3775. for (i = 0; i < src_len; i += 4) {
  3776. a = b64reverse(src[i]);
  3777. if (a >= 254) {
  3778. return i;
  3779. }
  3780. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3781. if (b >= 254) {
  3782. return i + 1;
  3783. }
  3784. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3785. if (c == 254) {
  3786. return i + 2;
  3787. }
  3788. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3789. if (d == 254) {
  3790. return i + 3;
  3791. }
  3792. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3793. if (c != 255) {
  3794. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3795. if (d != 255) {
  3796. dst[(*dst_len)++] = (c << 6) + d;
  3797. }
  3798. }
  3799. }
  3800. return -1;
  3801. }
  3802. #endif
  3803. static int
  3804. is_put_or_delete_method(const struct mg_connection *conn)
  3805. {
  3806. if (conn) {
  3807. const char *s = conn->request_info.request_method;
  3808. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3809. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3810. }
  3811. return 0;
  3812. }
  3813. static void
  3814. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3815. char *filename, /* out: filename */
  3816. size_t filename_buf_len, /* in: size of filename buffer */
  3817. struct file *filep, /* out: file structure */
  3818. int *is_found, /* out: file is found (directly) */
  3819. int *is_script_resource, /* out: handled by a script? */
  3820. int *is_websocket_request, /* out: websocket connetion? */
  3821. int *is_put_or_delete_request /* out: put/delete a file? */
  3822. )
  3823. {
  3824. /* TODO (high): Restructure this function */
  3825. #if !defined(NO_FILES)
  3826. const char *uri = conn->request_info.local_uri;
  3827. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3828. const char *rewrite;
  3829. struct vec a, b;
  3830. int match_len;
  3831. char gz_path[PATH_MAX];
  3832. char const *accept_encoding;
  3833. int truncated;
  3834. #if !defined(NO_CGI) || defined(USE_LUA)
  3835. char *p;
  3836. #endif
  3837. #else
  3838. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3839. #endif
  3840. memset(filep, 0, sizeof(*filep));
  3841. *filename = 0;
  3842. *is_found = 0;
  3843. *is_script_resource = 0;
  3844. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3845. #if defined(USE_WEBSOCKET)
  3846. *is_websocket_request = is_websocket_protocol(conn);
  3847. #if !defined(NO_FILES)
  3848. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3849. root = conn->ctx->config[WEBSOCKET_ROOT];
  3850. }
  3851. #endif /* !NO_FILES */
  3852. #else /* USE_WEBSOCKET */
  3853. *is_websocket_request = 0;
  3854. #endif /* USE_WEBSOCKET */
  3855. #if !defined(NO_FILES)
  3856. /* Note that root == NULL is a regular use case here. This occurs,
  3857. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3858. * config is not required. */
  3859. if (root == NULL) {
  3860. /* all file related outputs have already been set to 0, just return
  3861. */
  3862. return;
  3863. }
  3864. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3865. * of the path one byte on the right.
  3866. * If document_root is NULL, leave the file empty. */
  3867. mg_snprintf(
  3868. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3869. if (truncated) {
  3870. goto interpret_cleanup;
  3871. }
  3872. rewrite = conn->ctx->config[REWRITE];
  3873. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3874. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3875. mg_snprintf(conn,
  3876. &truncated,
  3877. filename,
  3878. filename_buf_len - 1,
  3879. "%.*s%s",
  3880. (int)b.len,
  3881. b.ptr,
  3882. uri + match_len);
  3883. break;
  3884. }
  3885. }
  3886. if (truncated) {
  3887. goto interpret_cleanup;
  3888. }
  3889. /* Local file path and name, corresponding to requested URI
  3890. * is now stored in "filename" variable. */
  3891. if (mg_stat(conn, filename, filep)) {
  3892. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3893. /* File exists. Check if it is a script type. */
  3894. if (0
  3895. #if !defined(NO_CGI)
  3896. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3897. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3898. filename) > 0
  3899. #endif
  3900. #if defined(USE_LUA)
  3901. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3902. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3903. filename) > 0
  3904. #endif
  3905. #if defined(USE_DUKTAPE)
  3906. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3907. strlen(
  3908. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3909. filename) > 0
  3910. #endif
  3911. ) {
  3912. /* The request addresses a CGI script or a Lua script. The URI
  3913. * corresponds to the script itself (like /path/script.cgi),
  3914. * and there is no additional resource path
  3915. * (like /path/script.cgi/something).
  3916. * Requests that modify (replace or delete) a resource, like
  3917. * PUT and DELETE requests, should replace/delete the script
  3918. * file.
  3919. * Requests that read or write from/to a resource, like GET and
  3920. * POST requests, should call the script and return the
  3921. * generated response. */
  3922. *is_script_resource = !*is_put_or_delete_request;
  3923. }
  3924. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3925. *is_found = 1;
  3926. return;
  3927. }
  3928. /* If we can't find the actual file, look for the file
  3929. * with the same name but a .gz extension. If we find it,
  3930. * use that and set the gzipped flag in the file struct
  3931. * to indicate that the response need to have the content-
  3932. * encoding: gzip header.
  3933. * We can only do this if the browser declares support. */
  3934. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3935. if (strstr(accept_encoding, "gzip") != NULL) {
  3936. mg_snprintf(
  3937. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3938. if (truncated) {
  3939. goto interpret_cleanup;
  3940. }
  3941. if (mg_stat(conn, gz_path, filep)) {
  3942. if (filep) {
  3943. filep->gzipped = 1;
  3944. *is_found = 1;
  3945. }
  3946. /* Currently gz files can not be scripts. */
  3947. return;
  3948. }
  3949. }
  3950. }
  3951. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3952. /* Support PATH_INFO for CGI scripts. */
  3953. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3954. if (*p == '/') {
  3955. *p = '\0';
  3956. if ((0
  3957. #if !defined(NO_CGI)
  3958. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3959. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3960. filename) > 0
  3961. #endif
  3962. #if defined(USE_LUA)
  3963. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3964. strlen(
  3965. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3966. filename) > 0
  3967. #endif
  3968. #if defined(USE_DUKTAPE)
  3969. || match_prefix(
  3970. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3971. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3972. filename) > 0
  3973. #endif
  3974. ) && mg_stat(conn, filename, filep)) {
  3975. /* Shift PATH_INFO block one character right, e.g.
  3976. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3977. * conn->path_info is pointing to the local variable "path"
  3978. * declared in handle_request(), so PATH_INFO is not valid
  3979. * after handle_request returns. */
  3980. conn->path_info = p + 1;
  3981. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3982. * trailing \0 */
  3983. p[1] = '/';
  3984. *is_script_resource = 1;
  3985. break;
  3986. } else {
  3987. *p = '/';
  3988. }
  3989. }
  3990. }
  3991. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3992. #endif /* !defined(NO_FILES) */
  3993. return;
  3994. #if !defined(NO_FILES)
  3995. /* Reset all outputs */
  3996. interpret_cleanup:
  3997. memset(filep, 0, sizeof(*filep));
  3998. *filename = 0;
  3999. *is_found = 0;
  4000. *is_script_resource = 0;
  4001. *is_websocket_request = 0;
  4002. *is_put_or_delete_request = 0;
  4003. #endif /* !defined(NO_FILES) */
  4004. }
  4005. /* Check whether full request is buffered. Return:
  4006. * -1 if request is malformed
  4007. * 0 if request is not yet fully buffered
  4008. * >0 actual request length, including last \r\n\r\n */
  4009. static int
  4010. get_request_len(const char *buf, int buflen)
  4011. {
  4012. const char *s, *e;
  4013. int len = 0;
  4014. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4015. /* Control characters are not allowed but >=128 is. */
  4016. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4017. && *(const unsigned char *)s < 128) {
  4018. len = -1;
  4019. break; /* [i_a] abort scan as soon as one malformed character is
  4020. * found; */
  4021. /* don't let subsequent \r\n\r\n win us over anyhow */
  4022. } else if (s[0] == '\n' && s[1] == '\n') {
  4023. len = (int)(s - buf) + 2;
  4024. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4025. len = (int)(s - buf) + 3;
  4026. }
  4027. return len;
  4028. }
  4029. /* Convert month to the month number. Return -1 on error, or month number */
  4030. static int
  4031. get_month_index(const char *s)
  4032. {
  4033. size_t i;
  4034. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4035. if (!strcmp(s, month_names[i])) {
  4036. return (int)i;
  4037. }
  4038. }
  4039. return -1;
  4040. }
  4041. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4042. static time_t
  4043. parse_date_string(const char *datetime)
  4044. {
  4045. char month_str[32] = {0};
  4046. int second, minute, hour, day, month, year;
  4047. time_t result = (time_t)0;
  4048. struct tm tm;
  4049. if ((sscanf(datetime,
  4050. "%d/%3s/%d %d:%d:%d",
  4051. &day,
  4052. month_str,
  4053. &year,
  4054. &hour,
  4055. &minute,
  4056. &second) == 6) || (sscanf(datetime,
  4057. "%d %3s %d %d:%d:%d",
  4058. &day,
  4059. month_str,
  4060. &year,
  4061. &hour,
  4062. &minute,
  4063. &second) == 6)
  4064. || (sscanf(datetime,
  4065. "%*3s, %d %3s %d %d:%d:%d",
  4066. &day,
  4067. month_str,
  4068. &year,
  4069. &hour,
  4070. &minute,
  4071. &second) == 6) || (sscanf(datetime,
  4072. "%d-%3s-%d %d:%d:%d",
  4073. &day,
  4074. month_str,
  4075. &year,
  4076. &hour,
  4077. &minute,
  4078. &second) == 6)) {
  4079. month = get_month_index(month_str);
  4080. if ((month >= 0) && (year >= 1970)) {
  4081. memset(&tm, 0, sizeof(tm));
  4082. tm.tm_year = year - 1900;
  4083. tm.tm_mon = month;
  4084. tm.tm_mday = day;
  4085. tm.tm_hour = hour;
  4086. tm.tm_min = minute;
  4087. tm.tm_sec = second;
  4088. result = timegm(&tm);
  4089. }
  4090. }
  4091. return result;
  4092. }
  4093. /* Protect against directory disclosure attack by removing '..',
  4094. * excessive '/' and '\' characters */
  4095. static void
  4096. remove_double_dots_and_double_slashes(char *s)
  4097. {
  4098. char *p = s;
  4099. while (*s != '\0') {
  4100. *p++ = *s++;
  4101. if (s[-1] == '/' || s[-1] == '\\') {
  4102. /* Skip all following slashes, backslashes and double-dots */
  4103. while (s[0] != '\0') {
  4104. if (s[0] == '/' || s[0] == '\\') {
  4105. s++;
  4106. } else if (s[0] == '.' && s[1] == '.') {
  4107. s += 2;
  4108. } else {
  4109. break;
  4110. }
  4111. }
  4112. }
  4113. }
  4114. *p = '\0';
  4115. }
  4116. static const struct {
  4117. const char *extension;
  4118. size_t ext_len;
  4119. const char *mime_type;
  4120. } builtin_mime_types[] = {
  4121. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4122. * application types */
  4123. {".doc", 4, "application/msword"},
  4124. {".eps", 4, "application/postscript"},
  4125. {".exe", 4, "application/octet-stream"},
  4126. {".js", 3, "application/javascript"},
  4127. {".json", 5, "application/json"},
  4128. {".pdf", 4, "application/pdf"},
  4129. {".ps", 3, "application/postscript"},
  4130. {".rtf", 4, "application/rtf"},
  4131. {".xhtml", 6, "application/xhtml+xml"},
  4132. {".xsl", 4, "application/xml"},
  4133. {".xslt", 5, "application/xml"},
  4134. /* fonts */
  4135. {".ttf", 4, "application/font-sfnt"},
  4136. {".cff", 4, "application/font-sfnt"},
  4137. {".otf", 4, "application/font-sfnt"},
  4138. {".aat", 4, "application/font-sfnt"},
  4139. {".sil", 4, "application/font-sfnt"},
  4140. {".pfr", 4, "application/font-tdpfr"},
  4141. {".woff", 5, "application/font-woff"},
  4142. /* audio */
  4143. {".mp3", 4, "audio/mpeg"},
  4144. {".oga", 4, "audio/ogg"},
  4145. {".ogg", 4, "audio/ogg"},
  4146. /* image */
  4147. {".gif", 4, "image/gif"},
  4148. {".ief", 4, "image/ief"},
  4149. {".jpeg", 5, "image/jpeg"},
  4150. {".jpg", 4, "image/jpeg"},
  4151. {".jpm", 4, "image/jpm"},
  4152. {".jpx", 4, "image/jpx"},
  4153. {".png", 4, "image/png"},
  4154. {".svg", 4, "image/svg+xml"},
  4155. {".tif", 4, "image/tiff"},
  4156. {".tiff", 5, "image/tiff"},
  4157. /* model */
  4158. {".wrl", 4, "model/vrml"},
  4159. /* text */
  4160. {".css", 4, "text/css"},
  4161. {".csv", 4, "text/csv"},
  4162. {".htm", 4, "text/html"},
  4163. {".html", 5, "text/html"},
  4164. {".sgm", 4, "text/sgml"},
  4165. {".shtm", 5, "text/html"},
  4166. {".shtml", 6, "text/html"},
  4167. {".txt", 4, "text/plain"},
  4168. {".xml", 4, "text/xml"},
  4169. /* video */
  4170. {".mov", 4, "video/quicktime"},
  4171. {".mp4", 4, "video/mp4"},
  4172. {".mpeg", 5, "video/mpeg"},
  4173. {".mpg", 4, "video/mpeg"},
  4174. {".ogv", 4, "video/ogg"},
  4175. {".qt", 3, "video/quicktime"},
  4176. /* not registered types
  4177. * (http://reference.sitepoint.com/html/mime-types-full,
  4178. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4179. {".arj", 4, "application/x-arj-compressed"},
  4180. {".gz", 3, "application/x-gunzip"},
  4181. {".rar", 4, "application/x-arj-compressed"},
  4182. {".swf", 4, "application/x-shockwave-flash"},
  4183. {".tar", 4, "application/x-tar"},
  4184. {".tgz", 4, "application/x-tar-gz"},
  4185. {".torrent", 8, "application/x-bittorrent"},
  4186. {".ppt", 4, "application/x-mspowerpoint"},
  4187. {".xls", 4, "application/x-msexcel"},
  4188. {".zip", 4, "application/x-zip-compressed"},
  4189. {".aac",
  4190. 4,
  4191. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4192. {".aif", 4, "audio/x-aif"},
  4193. {".m3u", 4, "audio/x-mpegurl"},
  4194. {".mid", 4, "audio/x-midi"},
  4195. {".ra", 3, "audio/x-pn-realaudio"},
  4196. {".ram", 4, "audio/x-pn-realaudio"},
  4197. {".wav", 4, "audio/x-wav"},
  4198. {".bmp", 4, "image/bmp"},
  4199. {".ico", 4, "image/x-icon"},
  4200. {".pct", 4, "image/x-pct"},
  4201. {".pict", 5, "image/pict"},
  4202. {".rgb", 4, "image/x-rgb"},
  4203. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4204. {".asf", 4, "video/x-ms-asf"},
  4205. {".avi", 4, "video/x-msvideo"},
  4206. {".m4v", 4, "video/x-m4v"},
  4207. {NULL, 0, NULL}};
  4208. const char *
  4209. mg_get_builtin_mime_type(const char *path)
  4210. {
  4211. const char *ext;
  4212. size_t i, path_len;
  4213. path_len = strlen(path);
  4214. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4215. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4216. if (path_len > builtin_mime_types[i].ext_len
  4217. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4218. return builtin_mime_types[i].mime_type;
  4219. }
  4220. }
  4221. return "text/plain";
  4222. }
  4223. /* Look at the "path" extension and figure what mime type it has.
  4224. * Store mime type in the vector. */
  4225. static void
  4226. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4227. {
  4228. struct vec ext_vec, mime_vec;
  4229. const char *list, *ext;
  4230. size_t path_len;
  4231. path_len = strlen(path);
  4232. if (ctx == NULL || vec == NULL) {
  4233. return;
  4234. }
  4235. /* Scan user-defined mime types first, in case user wants to
  4236. * override default mime types. */
  4237. list = ctx->config[EXTRA_MIME_TYPES];
  4238. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4239. /* ext now points to the path suffix */
  4240. ext = path + path_len - ext_vec.len;
  4241. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4242. *vec = mime_vec;
  4243. return;
  4244. }
  4245. }
  4246. vec->ptr = mg_get_builtin_mime_type(path);
  4247. vec->len = strlen(vec->ptr);
  4248. }
  4249. /* Stringify binary data. Output buffer must be twice as big as input,
  4250. * because each byte takes 2 bytes in string representation */
  4251. static void
  4252. bin2str(char *to, const unsigned char *p, size_t len)
  4253. {
  4254. static const char *hex = "0123456789abcdef";
  4255. for (; len--; p++) {
  4256. *to++ = hex[p[0] >> 4];
  4257. *to++ = hex[p[0] & 0x0f];
  4258. }
  4259. *to = '\0';
  4260. }
  4261. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4262. char *
  4263. mg_md5(char buf[33], ...)
  4264. {
  4265. md5_byte_t hash[16];
  4266. const char *p;
  4267. va_list ap;
  4268. md5_state_t ctx;
  4269. md5_init(&ctx);
  4270. va_start(ap, buf);
  4271. while ((p = va_arg(ap, const char *)) != NULL) {
  4272. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4273. }
  4274. va_end(ap);
  4275. md5_finish(&ctx, hash);
  4276. bin2str(buf, hash, sizeof(hash));
  4277. return buf;
  4278. }
  4279. /* Check the user's password, return 1 if OK */
  4280. static int
  4281. check_password(const char *method,
  4282. const char *ha1,
  4283. const char *uri,
  4284. const char *nonce,
  4285. const char *nc,
  4286. const char *cnonce,
  4287. const char *qop,
  4288. const char *response)
  4289. {
  4290. char ha2[32 + 1], expected_response[32 + 1];
  4291. /* Some of the parameters may be NULL */
  4292. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4293. || qop == NULL
  4294. || response == NULL) {
  4295. return 0;
  4296. }
  4297. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4298. if (strlen(response) != 32) {
  4299. return 0;
  4300. }
  4301. mg_md5(ha2, method, ":", uri, NULL);
  4302. mg_md5(expected_response,
  4303. ha1,
  4304. ":",
  4305. nonce,
  4306. ":",
  4307. nc,
  4308. ":",
  4309. cnonce,
  4310. ":",
  4311. qop,
  4312. ":",
  4313. ha2,
  4314. NULL);
  4315. return mg_strcasecmp(response, expected_response) == 0;
  4316. }
  4317. /* Use the global passwords file, if specified by auth_gpass option,
  4318. * or search for .htpasswd in the requested directory. */
  4319. static void
  4320. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4321. {
  4322. if (conn != NULL && conn->ctx != NULL) {
  4323. char name[PATH_MAX];
  4324. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4325. struct file file = STRUCT_FILE_INITIALIZER;
  4326. int truncated;
  4327. if (gpass != NULL) {
  4328. /* Use global passwords file */
  4329. if (!mg_fopen(conn, gpass, "r", filep)) {
  4330. #ifdef DEBUG
  4331. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4332. #endif
  4333. }
  4334. /* Important: using local struct file to test path for is_directory
  4335. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4336. * was opened. */
  4337. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4338. mg_snprintf(conn,
  4339. &truncated,
  4340. name,
  4341. sizeof(name),
  4342. "%s/%s",
  4343. path,
  4344. PASSWORDS_FILE_NAME);
  4345. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4346. #ifdef DEBUG
  4347. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4348. #endif
  4349. }
  4350. } else {
  4351. /* Try to find .htpasswd in requested directory. */
  4352. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4353. if (e[0] == '/') {
  4354. break;
  4355. }
  4356. }
  4357. mg_snprintf(conn,
  4358. &truncated,
  4359. name,
  4360. sizeof(name),
  4361. "%.*s%s",
  4362. (int)(e - p),
  4363. p,
  4364. PASSWORDS_FILE_NAME);
  4365. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4366. #ifdef DEBUG
  4367. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4368. #endif
  4369. }
  4370. }
  4371. }
  4372. }
  4373. /* Parsed Authorization header */
  4374. struct ah {
  4375. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4376. };
  4377. /* Return 1 on success. Always initializes the ah structure. */
  4378. static int
  4379. parse_auth_header(struct mg_connection *conn,
  4380. char *buf,
  4381. size_t buf_size,
  4382. struct ah *ah)
  4383. {
  4384. char *name, *value, *s;
  4385. const char *auth_header;
  4386. uint64_t nonce;
  4387. if (!ah || !conn) {
  4388. return 0;
  4389. }
  4390. (void)memset(ah, 0, sizeof(*ah));
  4391. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4392. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4393. return 0;
  4394. }
  4395. /* Make modifiable copy of the auth header */
  4396. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4397. s = buf;
  4398. /* Parse authorization header */
  4399. for (;;) {
  4400. /* Gobble initial spaces */
  4401. while (isspace(*(unsigned char *)s)) {
  4402. s++;
  4403. }
  4404. name = skip_quoted(&s, "=", " ", 0);
  4405. /* Value is either quote-delimited, or ends at first comma or space. */
  4406. if (s[0] == '\"') {
  4407. s++;
  4408. value = skip_quoted(&s, "\"", " ", '\\');
  4409. if (s[0] == ',') {
  4410. s++;
  4411. }
  4412. } else {
  4413. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4414. * spaces */
  4415. }
  4416. if (*name == '\0') {
  4417. break;
  4418. }
  4419. if (!strcmp(name, "username")) {
  4420. ah->user = value;
  4421. } else if (!strcmp(name, "cnonce")) {
  4422. ah->cnonce = value;
  4423. } else if (!strcmp(name, "response")) {
  4424. ah->response = value;
  4425. } else if (!strcmp(name, "uri")) {
  4426. ah->uri = value;
  4427. } else if (!strcmp(name, "qop")) {
  4428. ah->qop = value;
  4429. } else if (!strcmp(name, "nc")) {
  4430. ah->nc = value;
  4431. } else if (!strcmp(name, "nonce")) {
  4432. ah->nonce = value;
  4433. }
  4434. }
  4435. #ifndef NO_NONCE_CHECK
  4436. /* Read the nonce from the response. */
  4437. if (ah->nonce == NULL) {
  4438. return 0;
  4439. }
  4440. s = NULL;
  4441. nonce = strtoull(ah->nonce, &s, 10);
  4442. if ((s == NULL) || (*s != 0)) {
  4443. return 0;
  4444. }
  4445. /* Convert the nonce from the client to a number. */
  4446. nonce ^= conn->ctx->auth_nonce_mask;
  4447. /* The converted number corresponds to the time the nounce has been
  4448. * created. This should not be earlier than the server start. */
  4449. /* Server side nonce check is valuable in all situations but one:
  4450. * if the server restarts frequently, but the client should not see
  4451. * that, so the server should accept nonces from previous starts. */
  4452. /* However, the reasonable default is to not accept a nonce from a
  4453. * previous start, so if anyone changed the access rights between
  4454. * two restarts, a new login is required. */
  4455. if (nonce < (uint64_t)conn->ctx->start_time) {
  4456. /* nonce is from a previous start of the server and no longer valid
  4457. * (replay attack?) */
  4458. return 0;
  4459. }
  4460. /* Check if the nonce is too high, so it has not (yet) been used by the
  4461. * server. */
  4462. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4463. return 0;
  4464. }
  4465. #endif
  4466. /* CGI needs it as REMOTE_USER */
  4467. if (ah->user != NULL) {
  4468. conn->request_info.remote_user = mg_strdup(ah->user);
  4469. } else {
  4470. return 0;
  4471. }
  4472. return 1;
  4473. }
  4474. static char *
  4475. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4476. {
  4477. char *eof;
  4478. size_t len;
  4479. char *memend;
  4480. if (!filep) {
  4481. return NULL;
  4482. }
  4483. if (filep->membuf != NULL && *p != NULL) {
  4484. memend = (char *)&filep->membuf[filep->size];
  4485. /* Search for \n from p till the end of stream */
  4486. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4487. if (eof != NULL) {
  4488. eof += 1; /* Include \n */
  4489. } else {
  4490. eof = memend; /* Copy remaining data */
  4491. }
  4492. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4493. memcpy(buf, *p, len);
  4494. buf[len] = '\0';
  4495. *p += len;
  4496. return len ? eof : NULL;
  4497. } else if (filep->fp != NULL) {
  4498. return fgets(buf, (int)size, filep->fp);
  4499. } else {
  4500. return NULL;
  4501. }
  4502. }
  4503. struct read_auth_file_struct {
  4504. struct mg_connection *conn;
  4505. struct ah ah;
  4506. char *domain;
  4507. char buf[256 + 256 + 40];
  4508. char *f_user;
  4509. char *f_domain;
  4510. char *f_ha1;
  4511. };
  4512. static int
  4513. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4514. {
  4515. char *p;
  4516. int is_authorized = 0;
  4517. struct file fp;
  4518. size_t l;
  4519. if (!filep || !workdata) {
  4520. return 0;
  4521. }
  4522. /* Loop over passwords file */
  4523. p = (char *)filep->membuf;
  4524. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4525. l = strlen(workdata->buf);
  4526. while (l > 0) {
  4527. if (isspace(workdata->buf[l - 1])
  4528. || iscntrl(workdata->buf[l - 1])) {
  4529. l--;
  4530. workdata->buf[l] = 0;
  4531. } else
  4532. break;
  4533. }
  4534. if (l < 1) {
  4535. continue;
  4536. }
  4537. workdata->f_user = workdata->buf;
  4538. if (workdata->f_user[0] == ':') {
  4539. /* user names may not contain a ':' and may not be empty,
  4540. * so lines starting with ':' may be used for a special purpose */
  4541. if (workdata->f_user[1] == '#') {
  4542. /* :# is a comment */
  4543. continue;
  4544. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4545. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4546. is_authorized = read_auth_file(&fp, workdata);
  4547. mg_fclose(&fp);
  4548. } else {
  4549. mg_cry(workdata->conn,
  4550. "%s: cannot open authorization file: %s",
  4551. __func__,
  4552. workdata->buf);
  4553. }
  4554. continue;
  4555. }
  4556. /* everything is invalid for the moment (might change in the
  4557. * future) */
  4558. mg_cry(workdata->conn,
  4559. "%s: syntax error in authorization file: %s",
  4560. __func__,
  4561. workdata->buf);
  4562. continue;
  4563. }
  4564. workdata->f_domain = strchr(workdata->f_user, ':');
  4565. if (workdata->f_domain == NULL) {
  4566. mg_cry(workdata->conn,
  4567. "%s: syntax error in authorization file: %s",
  4568. __func__,
  4569. workdata->buf);
  4570. continue;
  4571. }
  4572. *(workdata->f_domain) = 0;
  4573. (workdata->f_domain)++;
  4574. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4575. if (workdata->f_ha1 == NULL) {
  4576. mg_cry(workdata->conn,
  4577. "%s: syntax error in authorization file: %s",
  4578. __func__,
  4579. workdata->buf);
  4580. continue;
  4581. }
  4582. *(workdata->f_ha1) = 0;
  4583. (workdata->f_ha1)++;
  4584. if (!strcmp(workdata->ah.user, workdata->f_user)
  4585. && !strcmp(workdata->domain, workdata->f_domain)) {
  4586. return check_password(workdata->conn->request_info.request_method,
  4587. workdata->f_ha1,
  4588. workdata->ah.uri,
  4589. workdata->ah.nonce,
  4590. workdata->ah.nc,
  4591. workdata->ah.cnonce,
  4592. workdata->ah.qop,
  4593. workdata->ah.response);
  4594. }
  4595. }
  4596. return is_authorized;
  4597. }
  4598. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4599. static int
  4600. authorize(struct mg_connection *conn, struct file *filep)
  4601. {
  4602. struct read_auth_file_struct workdata;
  4603. char buf[MG_BUF_LEN];
  4604. if (!conn || !conn->ctx) {
  4605. return 0;
  4606. }
  4607. memset(&workdata, 0, sizeof(workdata));
  4608. workdata.conn = conn;
  4609. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4610. return 0;
  4611. }
  4612. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4613. return read_auth_file(filep, &workdata);
  4614. }
  4615. /* Return 1 if request is authorised, 0 otherwise. */
  4616. static int
  4617. check_authorization(struct mg_connection *conn, const char *path)
  4618. {
  4619. char fname[PATH_MAX];
  4620. struct vec uri_vec, filename_vec;
  4621. const char *list;
  4622. struct file file = STRUCT_FILE_INITIALIZER;
  4623. int authorized = 1, truncated;
  4624. if (!conn || !conn->ctx) {
  4625. return 0;
  4626. }
  4627. list = conn->ctx->config[PROTECT_URI];
  4628. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4629. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4630. mg_snprintf(conn,
  4631. &truncated,
  4632. fname,
  4633. sizeof(fname),
  4634. "%.*s",
  4635. (int)filename_vec.len,
  4636. filename_vec.ptr);
  4637. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4638. mg_cry(conn,
  4639. "%s: cannot open %s: %s",
  4640. __func__,
  4641. fname,
  4642. strerror(errno));
  4643. }
  4644. break;
  4645. }
  4646. }
  4647. if (!is_file_opened(&file)) {
  4648. open_auth_file(conn, path, &file);
  4649. }
  4650. if (is_file_opened(&file)) {
  4651. authorized = authorize(conn, &file);
  4652. mg_fclose(&file);
  4653. }
  4654. return authorized;
  4655. }
  4656. static void
  4657. send_authorization_request(struct mg_connection *conn)
  4658. {
  4659. char date[64];
  4660. time_t curtime = time(NULL);
  4661. if (conn && conn->ctx) {
  4662. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4663. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4664. nonce += conn->ctx->nonce_count;
  4665. ++conn->ctx->nonce_count;
  4666. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4667. nonce ^= conn->ctx->auth_nonce_mask;
  4668. conn->status_code = 401;
  4669. conn->must_close = 1;
  4670. gmt_time_string(date, sizeof(date), &curtime);
  4671. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4672. send_no_cache_header(conn);
  4673. mg_printf(conn,
  4674. "Date: %s\r\n"
  4675. "Connection: %s\r\n"
  4676. "Content-Length: 0\r\n"
  4677. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4678. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4679. date,
  4680. suggest_connection_header(conn),
  4681. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4682. nonce);
  4683. }
  4684. }
  4685. #if !defined(NO_FILES)
  4686. static int
  4687. is_authorized_for_put(struct mg_connection *conn)
  4688. {
  4689. if (conn) {
  4690. struct file file = STRUCT_FILE_INITIALIZER;
  4691. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4692. int ret = 0;
  4693. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4694. ret = authorize(conn, &file);
  4695. mg_fclose(&file);
  4696. }
  4697. return ret;
  4698. }
  4699. return 0;
  4700. }
  4701. #endif
  4702. int
  4703. mg_modify_passwords_file(const char *fname,
  4704. const char *domain,
  4705. const char *user,
  4706. const char *pass)
  4707. {
  4708. int found, i;
  4709. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4710. FILE *fp, *fp2;
  4711. found = 0;
  4712. fp = fp2 = NULL;
  4713. /* Regard empty password as no password - remove user record. */
  4714. if (pass != NULL && pass[0] == '\0') {
  4715. pass = NULL;
  4716. }
  4717. /* Other arguments must not be empty */
  4718. if (fname == NULL || domain == NULL || user == NULL) {
  4719. return 0;
  4720. }
  4721. /* Using the given file format, user name and domain must not contain ':'
  4722. */
  4723. if (strchr(user, ':') != NULL) {
  4724. return 0;
  4725. }
  4726. if (strchr(domain, ':') != NULL) {
  4727. return 0;
  4728. }
  4729. /* Do not allow control characters like newline in user name and domain.
  4730. * Do not allow excessively long names either. */
  4731. for (i = 0; i < 255 && user[i] != 0; i++) {
  4732. if (iscntrl(user[i])) {
  4733. return 0;
  4734. }
  4735. }
  4736. if (user[i]) {
  4737. return 0;
  4738. }
  4739. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4740. if (iscntrl(domain[i])) {
  4741. return 0;
  4742. }
  4743. }
  4744. if (domain[i]) {
  4745. return 0;
  4746. }
  4747. /* The maximum length of the path to the password file is limited */
  4748. if ((strlen(fname) + 4) >= PATH_MAX) {
  4749. return 0;
  4750. }
  4751. /* Create a temporary file name. Length has been checked before. */
  4752. strcpy(tmp, fname);
  4753. strcat(tmp, ".tmp");
  4754. /* Create the file if does not exist */
  4755. /* Use of fopen here is OK, since fname is only ASCII */
  4756. if ((fp = fopen(fname, "a+")) != NULL) {
  4757. (void)fclose(fp);
  4758. }
  4759. /* Open the given file and temporary file */
  4760. if ((fp = fopen(fname, "r")) == NULL) {
  4761. return 0;
  4762. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4763. fclose(fp);
  4764. return 0;
  4765. }
  4766. /* Copy the stuff to temporary file */
  4767. while (fgets(line, sizeof(line), fp) != NULL) {
  4768. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4769. continue;
  4770. }
  4771. u[255] = 0;
  4772. d[255] = 0;
  4773. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4774. found++;
  4775. if (pass != NULL) {
  4776. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4777. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4778. }
  4779. } else {
  4780. fprintf(fp2, "%s", line);
  4781. }
  4782. }
  4783. /* If new user, just add it */
  4784. if (!found && pass != NULL) {
  4785. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4786. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4787. }
  4788. /* Close files */
  4789. fclose(fp);
  4790. fclose(fp2);
  4791. /* Put the temp file in place of real file */
  4792. IGNORE_UNUSED_RESULT(remove(fname));
  4793. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4794. return 1;
  4795. }
  4796. static int
  4797. is_valid_port(unsigned long port)
  4798. {
  4799. return port < 0xffff;
  4800. }
  4801. static int
  4802. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4803. {
  4804. struct addrinfo hints, *res, *ressave;
  4805. int ret = 0;
  4806. memset(&hints, 0, sizeof(struct addrinfo));
  4807. hints.ai_family = af;
  4808. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4809. /* bad src string or bad address family */
  4810. return 0;
  4811. }
  4812. ressave = res;
  4813. while (res) {
  4814. if (dstlen >= res->ai_addrlen) {
  4815. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4816. ret = 1;
  4817. }
  4818. res = res->ai_next;
  4819. }
  4820. freeaddrinfo(ressave);
  4821. return ret;
  4822. }
  4823. static int
  4824. connect_socket(struct mg_context *ctx /* may be NULL */,
  4825. const char *host,
  4826. int port,
  4827. int use_ssl,
  4828. char *ebuf,
  4829. size_t ebuf_len,
  4830. SOCKET *sock /* output: socket, must not be NULL */,
  4831. union usa *sa /* output: socket address, must not be NULL */
  4832. )
  4833. {
  4834. int ip_ver = 0;
  4835. *sock = INVALID_SOCKET;
  4836. memset(sa, 0, sizeof(*sa));
  4837. if (ebuf_len > 0) {
  4838. *ebuf = 0;
  4839. }
  4840. if (host == NULL) {
  4841. mg_snprintf(NULL,
  4842. NULL, /* No truncation check for ebuf */
  4843. ebuf,
  4844. ebuf_len,
  4845. "%s",
  4846. "NULL host");
  4847. return 0;
  4848. }
  4849. if (port < 0 || !is_valid_port((unsigned)port)) {
  4850. mg_snprintf(NULL,
  4851. NULL, /* No truncation check for ebuf */
  4852. ebuf,
  4853. ebuf_len,
  4854. "%s",
  4855. "invalid port");
  4856. return 0;
  4857. }
  4858. if (use_ssl && (SSLv23_client_method == NULL)) {
  4859. mg_snprintf(NULL,
  4860. NULL, /* No truncation check for ebuf */
  4861. ebuf,
  4862. ebuf_len,
  4863. "%s",
  4864. "SSL is not initialized");
  4865. return 0;
  4866. }
  4867. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4868. sa->sin.sin_port = htons((uint16_t)port);
  4869. ip_ver = 4;
  4870. #ifdef USE_IPV6
  4871. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4872. sa->sin6.sin6_port = htons((uint16_t)port);
  4873. ip_ver = 6;
  4874. } else if (host[0] == '[') {
  4875. /* While getaddrinfo on Windows will work with [::1],
  4876. * getaddrinfo on Linux only works with ::1 (without []). */
  4877. size_t l = strlen(host + 1);
  4878. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4879. if (h) {
  4880. h[l - 1] = 0;
  4881. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4882. sa->sin6.sin6_port = htons((uint16_t)port);
  4883. ip_ver = 6;
  4884. }
  4885. mg_free(h);
  4886. }
  4887. #endif
  4888. }
  4889. if (ip_ver == 0) {
  4890. mg_snprintf(NULL,
  4891. NULL, /* No truncation check for ebuf */
  4892. ebuf,
  4893. ebuf_len,
  4894. "%s",
  4895. "host not found");
  4896. return 0;
  4897. }
  4898. if (ip_ver == 4) {
  4899. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4900. }
  4901. #ifdef USE_IPV6
  4902. else if (ip_ver == 6) {
  4903. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4904. }
  4905. #endif
  4906. if (*sock == INVALID_SOCKET) {
  4907. mg_snprintf(NULL,
  4908. NULL, /* No truncation check for ebuf */
  4909. ebuf,
  4910. ebuf_len,
  4911. "socket(): %s",
  4912. strerror(ERRNO));
  4913. return 0;
  4914. }
  4915. set_close_on_exec(*sock, fc(ctx));
  4916. if ((ip_ver == 4)
  4917. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4918. == 0)) {
  4919. /* connected with IPv4 */
  4920. return 1;
  4921. }
  4922. #ifdef USE_IPV6
  4923. if ((ip_ver == 6)
  4924. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4925. == 0)) {
  4926. /* connected with IPv6 */
  4927. return 1;
  4928. }
  4929. #endif
  4930. /* Not connected */
  4931. mg_snprintf(NULL,
  4932. NULL, /* No truncation check for ebuf */
  4933. ebuf,
  4934. ebuf_len,
  4935. "connect(%s:%d): %s",
  4936. host,
  4937. port,
  4938. strerror(ERRNO));
  4939. closesocket(*sock);
  4940. *sock = INVALID_SOCKET;
  4941. return 0;
  4942. }
  4943. int
  4944. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4945. {
  4946. static const char *dont_escape = "._-$,;~()";
  4947. static const char *hex = "0123456789abcdef";
  4948. char *pos = dst;
  4949. const char *end = dst + dst_len - 1;
  4950. for (; *src != '\0' && pos < end; src++, pos++) {
  4951. if (isalnum(*(const unsigned char *)src)
  4952. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4953. *pos = *src;
  4954. } else if (pos + 2 < end) {
  4955. pos[0] = '%';
  4956. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4957. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4958. pos += 2;
  4959. } else {
  4960. break;
  4961. }
  4962. }
  4963. *pos = '\0';
  4964. return (*src == '\0') ? (int)(pos - dst) : -1;
  4965. }
  4966. static void
  4967. print_dir_entry(struct de *de)
  4968. {
  4969. char size[64], mod[64], href[PATH_MAX];
  4970. struct tm *tm;
  4971. if (de->file.is_directory) {
  4972. mg_snprintf(de->conn,
  4973. NULL, /* Buffer is big enough */
  4974. size,
  4975. sizeof(size),
  4976. "%s",
  4977. "[DIRECTORY]");
  4978. } else {
  4979. /* We use (signed) cast below because MSVC 6 compiler cannot
  4980. * convert unsigned __int64 to double. Sigh. */
  4981. if (de->file.size < 1024) {
  4982. mg_snprintf(de->conn,
  4983. NULL, /* Buffer is big enough */
  4984. size,
  4985. sizeof(size),
  4986. "%d",
  4987. (int)de->file.size);
  4988. } else if (de->file.size < 0x100000) {
  4989. mg_snprintf(de->conn,
  4990. NULL, /* Buffer is big enough */
  4991. size,
  4992. sizeof(size),
  4993. "%.1fk",
  4994. (double)de->file.size / 1024.0);
  4995. } else if (de->file.size < 0x40000000) {
  4996. mg_snprintf(de->conn,
  4997. NULL, /* Buffer is big enough */
  4998. size,
  4999. sizeof(size),
  5000. "%.1fM",
  5001. (double)de->file.size / 1048576);
  5002. } else {
  5003. mg_snprintf(de->conn,
  5004. NULL, /* Buffer is big enough */
  5005. size,
  5006. sizeof(size),
  5007. "%.1fG",
  5008. (double)de->file.size / 1073741824);
  5009. }
  5010. }
  5011. /* Note: mg_snprintf will not cause a buffer overflow above.
  5012. * So, string truncation checks are not required here. */
  5013. tm = localtime(&de->file.last_modified);
  5014. if (tm != NULL) {
  5015. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5016. } else {
  5017. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5018. mod[sizeof(mod) - 1] = '\0';
  5019. }
  5020. mg_url_encode(de->file_name, href, sizeof(href));
  5021. de->conn->num_bytes_sent +=
  5022. mg_printf(de->conn,
  5023. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5024. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5025. de->conn->request_info.local_uri,
  5026. href,
  5027. de->file.is_directory ? "/" : "",
  5028. de->file_name,
  5029. de->file.is_directory ? "/" : "",
  5030. mod,
  5031. size);
  5032. }
  5033. /* This function is called from send_directory() and used for
  5034. * sorting directory entries by size, or name, or modification time.
  5035. * On windows, __cdecl specification is needed in case if project is built
  5036. * with __stdcall convention. qsort always requires __cdels callback. */
  5037. static int WINCDECL
  5038. compare_dir_entries(const void *p1, const void *p2)
  5039. {
  5040. if (p1 && p2) {
  5041. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5042. const char *query_string = a->conn->request_info.query_string;
  5043. int cmp_result = 0;
  5044. if (query_string == NULL) {
  5045. query_string = "na";
  5046. }
  5047. if (a->file.is_directory && !b->file.is_directory) {
  5048. return -1; /* Always put directories on top */
  5049. } else if (!a->file.is_directory && b->file.is_directory) {
  5050. return 1; /* Always put directories on top */
  5051. } else if (*query_string == 'n') {
  5052. cmp_result = strcmp(a->file_name, b->file_name);
  5053. } else if (*query_string == 's') {
  5054. cmp_result = a->file.size == b->file.size
  5055. ? 0
  5056. : a->file.size > b->file.size ? 1 : -1;
  5057. } else if (*query_string == 'd') {
  5058. cmp_result =
  5059. (a->file.last_modified == b->file.last_modified)
  5060. ? 0
  5061. : ((a->file.last_modified > b->file.last_modified) ? 1
  5062. : -1);
  5063. }
  5064. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5065. }
  5066. return 0;
  5067. }
  5068. static int
  5069. must_hide_file(struct mg_connection *conn, const char *path)
  5070. {
  5071. if (conn && conn->ctx) {
  5072. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5073. const char *pattern = conn->ctx->config[HIDE_FILES];
  5074. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5075. || (pattern != NULL
  5076. && match_prefix(pattern, strlen(pattern), path) > 0);
  5077. }
  5078. return 0;
  5079. }
  5080. static int
  5081. scan_directory(struct mg_connection *conn,
  5082. const char *dir,
  5083. void *data,
  5084. void (*cb)(struct de *, void *))
  5085. {
  5086. char path[PATH_MAX];
  5087. struct dirent *dp;
  5088. DIR *dirp;
  5089. struct de de;
  5090. int truncated;
  5091. if ((dirp = opendir(dir)) == NULL) {
  5092. return 0;
  5093. } else {
  5094. de.conn = conn;
  5095. while ((dp = readdir(dirp)) != NULL) {
  5096. /* Do not show current dir and hidden files */
  5097. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5098. || must_hide_file(conn, dp->d_name)) {
  5099. continue;
  5100. }
  5101. mg_snprintf(
  5102. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5103. /* If we don't memset stat structure to zero, mtime will have
  5104. * garbage and strftime() will segfault later on in
  5105. * print_dir_entry(). memset is required only if mg_stat()
  5106. * fails. For more details, see
  5107. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5108. memset(&de.file, 0, sizeof(de.file));
  5109. if (truncated) {
  5110. /* If the path is not complete, skip processing. */
  5111. continue;
  5112. }
  5113. if (!mg_stat(conn, path, &de.file)) {
  5114. mg_cry(conn,
  5115. "%s: mg_stat(%s) failed: %s",
  5116. __func__,
  5117. path,
  5118. strerror(ERRNO));
  5119. }
  5120. de.file_name = dp->d_name;
  5121. cb(&de, data);
  5122. }
  5123. (void)closedir(dirp);
  5124. }
  5125. return 1;
  5126. }
  5127. #if !defined(NO_FILES)
  5128. static int
  5129. remove_directory(struct mg_connection *conn, const char *dir)
  5130. {
  5131. char path[PATH_MAX];
  5132. struct dirent *dp;
  5133. DIR *dirp;
  5134. struct de de;
  5135. int truncated;
  5136. int ok = 1;
  5137. if ((dirp = opendir(dir)) == NULL) {
  5138. return 0;
  5139. } else {
  5140. de.conn = conn;
  5141. while ((dp = readdir(dirp)) != NULL) {
  5142. /* Do not show current dir (but show hidden files as they will
  5143. * also be removed) */
  5144. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5145. continue;
  5146. }
  5147. mg_snprintf(
  5148. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5149. /* If we don't memset stat structure to zero, mtime will have
  5150. * garbage and strftime() will segfault later on in
  5151. * print_dir_entry(). memset is required only if mg_stat()
  5152. * fails. For more details, see
  5153. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5154. memset(&de.file, 0, sizeof(de.file));
  5155. if (truncated) {
  5156. /* Do not delete anything shorter */
  5157. ok = 0;
  5158. continue;
  5159. }
  5160. if (!mg_stat(conn, path, &de.file)) {
  5161. mg_cry(conn,
  5162. "%s: mg_stat(%s) failed: %s",
  5163. __func__,
  5164. path,
  5165. strerror(ERRNO));
  5166. ok = 0;
  5167. }
  5168. if (de.file.membuf == NULL) {
  5169. /* file is not in memory */
  5170. if (de.file.is_directory) {
  5171. if (remove_directory(conn, path) == 0) {
  5172. ok = 0;
  5173. }
  5174. } else {
  5175. if (mg_remove(path) == 0) {
  5176. ok = 0;
  5177. }
  5178. }
  5179. } else {
  5180. /* file is in memory. It can not be deleted. */
  5181. ok = 0;
  5182. }
  5183. }
  5184. (void)closedir(dirp);
  5185. IGNORE_UNUSED_RESULT(rmdir(dir));
  5186. }
  5187. return ok;
  5188. }
  5189. #endif
  5190. struct dir_scan_data {
  5191. struct de *entries;
  5192. unsigned int num_entries;
  5193. unsigned int arr_size;
  5194. };
  5195. /* Behaves like realloc(), but frees original pointer on failure */
  5196. static void *
  5197. realloc2(void *ptr, size_t size)
  5198. {
  5199. void *new_ptr = mg_realloc(ptr, size);
  5200. if (new_ptr == NULL) {
  5201. mg_free(ptr);
  5202. }
  5203. return new_ptr;
  5204. }
  5205. static void
  5206. dir_scan_callback(struct de *de, void *data)
  5207. {
  5208. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5209. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5210. dsd->arr_size *= 2;
  5211. dsd->entries =
  5212. (struct de *)realloc2(dsd->entries,
  5213. dsd->arr_size * sizeof(dsd->entries[0]));
  5214. }
  5215. if (dsd->entries == NULL) {
  5216. /* TODO(lsm, low): propagate an error to the caller */
  5217. dsd->num_entries = 0;
  5218. } else {
  5219. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5220. dsd->entries[dsd->num_entries].file = de->file;
  5221. dsd->entries[dsd->num_entries].conn = de->conn;
  5222. dsd->num_entries++;
  5223. }
  5224. }
  5225. static void
  5226. handle_directory_request(struct mg_connection *conn, const char *dir)
  5227. {
  5228. unsigned int i;
  5229. int sort_direction;
  5230. struct dir_scan_data data = {NULL, 0, 128};
  5231. char date[64];
  5232. time_t curtime = time(NULL);
  5233. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5234. send_http_error(conn,
  5235. 500,
  5236. "Error: Cannot open directory\nopendir(%s): %s",
  5237. dir,
  5238. strerror(ERRNO));
  5239. return;
  5240. }
  5241. gmt_time_string(date, sizeof(date), &curtime);
  5242. if (!conn) {
  5243. return;
  5244. }
  5245. sort_direction = conn->request_info.query_string != NULL
  5246. && conn->request_info.query_string[1] == 'd'
  5247. ? 'a'
  5248. : 'd';
  5249. conn->must_close = 1;
  5250. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5251. send_static_cache_header(conn);
  5252. mg_printf(conn,
  5253. "Date: %s\r\n"
  5254. "Connection: close\r\n"
  5255. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5256. date);
  5257. conn->num_bytes_sent +=
  5258. mg_printf(conn,
  5259. "<html><head><title>Index of %s</title>"
  5260. "<style>th {text-align: left;}</style></head>"
  5261. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5262. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5263. "<th><a href=\"?d%c\">Modified</a></th>"
  5264. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5265. "<tr><td colspan=\"3\"><hr></td></tr>",
  5266. conn->request_info.local_uri,
  5267. conn->request_info.local_uri,
  5268. sort_direction,
  5269. sort_direction,
  5270. sort_direction);
  5271. /* Print first entry - link to a parent directory */
  5272. conn->num_bytes_sent +=
  5273. mg_printf(conn,
  5274. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5275. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5276. conn->request_info.local_uri,
  5277. "..",
  5278. "Parent directory",
  5279. "-",
  5280. "-");
  5281. /* Sort and print directory entries */
  5282. if (data.entries != NULL) {
  5283. qsort(data.entries,
  5284. (size_t)data.num_entries,
  5285. sizeof(data.entries[0]),
  5286. compare_dir_entries);
  5287. for (i = 0; i < data.num_entries; i++) {
  5288. print_dir_entry(&data.entries[i]);
  5289. mg_free(data.entries[i].file_name);
  5290. }
  5291. mg_free(data.entries);
  5292. }
  5293. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5294. conn->status_code = 200;
  5295. }
  5296. /* Send len bytes from the opened file to the client. */
  5297. static void
  5298. send_file_data(struct mg_connection *conn,
  5299. struct file *filep,
  5300. int64_t offset,
  5301. int64_t len)
  5302. {
  5303. char buf[MG_BUF_LEN];
  5304. int to_read, num_read, num_written;
  5305. int64_t size;
  5306. if (!filep || !conn) {
  5307. return;
  5308. }
  5309. /* Sanity check the offset */
  5310. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5311. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5312. if (len > 0 && filep->membuf != NULL && size > 0) {
  5313. /* file stored in memory */
  5314. if (len > size - offset) {
  5315. len = size - offset;
  5316. }
  5317. mg_write(conn, filep->membuf + offset, (size_t)len);
  5318. } else if (len > 0 && filep->fp != NULL) {
  5319. /* file stored on disk */
  5320. #if defined(__linux__)
  5321. /* sendfile is only available for Linux */
  5322. if (conn->throttle == 0 && conn->ssl == 0) {
  5323. off_t sf_offs = (off_t)offset;
  5324. ssize_t sf_sent;
  5325. int sf_file = fileno(filep->fp);
  5326. int loop_cnt = 0;
  5327. do {
  5328. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5329. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5330. size_t sf_tosend =
  5331. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5332. sf_sent =
  5333. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5334. if (sf_sent > 0) {
  5335. conn->num_bytes_sent += sf_sent;
  5336. len -= sf_sent;
  5337. offset += sf_sent;
  5338. } else if (loop_cnt == 0) {
  5339. /* This file can not be sent using sendfile.
  5340. * This might be the case for pseudo-files in the
  5341. * /sys/ and /proc/ file system.
  5342. * Use the regular user mode copy code instead. */
  5343. break;
  5344. } else if (sf_sent == 0) {
  5345. /* No error, but 0 bytes sent. May be EOF? */
  5346. return;
  5347. }
  5348. loop_cnt++;
  5349. } while ((len > 0) && (sf_sent >= 0));
  5350. if (sf_sent > 0) {
  5351. return; /* OK */
  5352. }
  5353. /* sf_sent<0 means error, thus fall back to the classic way */
  5354. /* This is always the case, if sf_file is not a "normal" file,
  5355. * e.g., for sending data from the output of a CGI process. */
  5356. offset = (int64_t)sf_offs;
  5357. }
  5358. #endif
  5359. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5360. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5361. send_http_error(
  5362. conn,
  5363. 500,
  5364. "%s",
  5365. "Error: Unable to access file at requested position.");
  5366. } else {
  5367. while (len > 0) {
  5368. /* Calculate how much to read from the file in the buffer */
  5369. to_read = sizeof(buf);
  5370. if ((int64_t)to_read > len) {
  5371. to_read = (int)len;
  5372. }
  5373. /* Read from file, exit the loop on error */
  5374. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5375. <= 0) {
  5376. break;
  5377. }
  5378. /* Send read bytes to the client, exit the loop on error */
  5379. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5380. != num_read) {
  5381. break;
  5382. }
  5383. /* Both read and were successful, adjust counters */
  5384. conn->num_bytes_sent += num_written;
  5385. len -= num_written;
  5386. }
  5387. }
  5388. }
  5389. }
  5390. static int
  5391. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5392. {
  5393. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5394. }
  5395. static void
  5396. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5397. {
  5398. if (filep != NULL && buf != NULL) {
  5399. mg_snprintf(NULL,
  5400. NULL, /* All calls to construct_etag use 64 byte buffer */
  5401. buf,
  5402. buf_len,
  5403. "\"%lx.%" INT64_FMT "\"",
  5404. (unsigned long)filep->last_modified,
  5405. filep->size);
  5406. }
  5407. }
  5408. static void
  5409. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5410. {
  5411. if (filep != NULL && filep->fp != NULL) {
  5412. #ifdef _WIN32
  5413. (void)conn; /* Unused. */
  5414. #else
  5415. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5416. mg_cry(conn,
  5417. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5418. __func__,
  5419. strerror(ERRNO));
  5420. }
  5421. #endif
  5422. }
  5423. }
  5424. static void
  5425. handle_static_file_request(struct mg_connection *conn,
  5426. const char *path,
  5427. struct file *filep)
  5428. {
  5429. char date[64], lm[64], etag[64];
  5430. char range[128]; /* large enough, so there will be no overflow */
  5431. const char *msg = "OK", *hdr;
  5432. time_t curtime = time(NULL);
  5433. int64_t cl, r1, r2;
  5434. struct vec mime_vec;
  5435. int n, truncated;
  5436. char gz_path[PATH_MAX];
  5437. const char *encoding = "";
  5438. const char *cors1, *cors2, *cors3;
  5439. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5440. return;
  5441. }
  5442. get_mime_type(conn->ctx, path, &mime_vec);
  5443. if (filep->size > INT64_MAX) {
  5444. send_http_error(conn,
  5445. 500,
  5446. "Error: File size is too large to send\n%" INT64_FMT,
  5447. filep->size);
  5448. }
  5449. cl = (int64_t)filep->size;
  5450. conn->status_code = 200;
  5451. range[0] = '\0';
  5452. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5453. * it's important to rewrite the filename after resolving
  5454. * the mime type from it, to preserve the actual file's type */
  5455. if (filep->gzipped) {
  5456. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5457. if (truncated) {
  5458. send_http_error(conn,
  5459. 500,
  5460. "Error: Path of zipped file too long (%s)",
  5461. path);
  5462. return;
  5463. }
  5464. path = gz_path;
  5465. encoding = "Content-Encoding: gzip\r\n";
  5466. }
  5467. if (!mg_fopen(conn, path, "rb", filep)) {
  5468. send_http_error(conn,
  5469. 500,
  5470. "Error: Cannot open file\nfopen(%s): %s",
  5471. path,
  5472. strerror(ERRNO));
  5473. return;
  5474. }
  5475. fclose_on_exec(filep, conn);
  5476. /* If Range: header specified, act accordingly */
  5477. r1 = r2 = 0;
  5478. hdr = mg_get_header(conn, "Range");
  5479. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5480. && r2 >= 0) {
  5481. /* actually, range requests don't play well with a pre-gzipped
  5482. * file (since the range is specified in the uncompressed space) */
  5483. if (filep->gzipped) {
  5484. send_http_error(
  5485. conn,
  5486. 501,
  5487. "%s",
  5488. "Error: Range requests in gzipped files are not supported");
  5489. mg_fclose(filep);
  5490. return;
  5491. }
  5492. conn->status_code = 206;
  5493. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5494. mg_snprintf(conn,
  5495. NULL, /* range buffer is big enough */
  5496. range,
  5497. sizeof(range),
  5498. "Content-Range: bytes "
  5499. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5500. r1,
  5501. r1 + cl - 1,
  5502. filep->size);
  5503. msg = "Partial Content";
  5504. }
  5505. hdr = mg_get_header(conn, "Origin");
  5506. if (hdr) {
  5507. /* Cross-origin resource sharing (CORS), see
  5508. * http://www.html5rocks.com/en/tutorials/cors/,
  5509. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5510. * preflight is not supported for files. */
  5511. cors1 = "Access-Control-Allow-Origin: ";
  5512. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5513. cors3 = "\r\n";
  5514. } else {
  5515. cors1 = cors2 = cors3 = "";
  5516. }
  5517. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5518. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5519. gmt_time_string(date, sizeof(date), &curtime);
  5520. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5521. construct_etag(etag, sizeof(etag), filep);
  5522. (void)mg_printf(conn,
  5523. "HTTP/1.1 %d %s\r\n"
  5524. "%s%s%s"
  5525. "Date: %s\r\n",
  5526. conn->status_code,
  5527. msg,
  5528. cors1,
  5529. cors2,
  5530. cors3,
  5531. date);
  5532. send_static_cache_header(conn);
  5533. (void)mg_printf(conn,
  5534. "Last-Modified: %s\r\n"
  5535. "Etag: %s\r\n"
  5536. "Content-Type: %.*s\r\n"
  5537. "Content-Length: %" INT64_FMT "\r\n"
  5538. "Connection: %s\r\n"
  5539. "Accept-Ranges: bytes\r\n"
  5540. "%s%s\r\n",
  5541. lm,
  5542. etag,
  5543. (int)mime_vec.len,
  5544. mime_vec.ptr,
  5545. cl,
  5546. suggest_connection_header(conn),
  5547. range,
  5548. encoding);
  5549. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5550. send_file_data(conn, filep, r1, cl);
  5551. }
  5552. mg_fclose(filep);
  5553. }
  5554. void
  5555. mg_send_file(struct mg_connection *conn, const char *path)
  5556. {
  5557. struct file file = STRUCT_FILE_INITIALIZER;
  5558. if (mg_stat(conn, path, &file)) {
  5559. if (file.is_directory) {
  5560. if (!conn) {
  5561. return;
  5562. }
  5563. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5564. "yes")) {
  5565. handle_directory_request(conn, path);
  5566. } else {
  5567. send_http_error(conn,
  5568. 403,
  5569. "%s",
  5570. "Error: Directory listing denied");
  5571. }
  5572. } else {
  5573. handle_static_file_request(conn, path, &file);
  5574. }
  5575. } else {
  5576. send_http_error(conn, 404, "%s", "Error: File not found");
  5577. }
  5578. }
  5579. /* For a given PUT path, create all intermediate subdirectories.
  5580. * Return 0 if the path itself is a directory.
  5581. * Return 1 if the path leads to a file.
  5582. * Return -1 for if the path is too long.
  5583. * Return -2 if path can not be created.
  5584. */
  5585. static int
  5586. put_dir(struct mg_connection *conn, const char *path)
  5587. {
  5588. char buf[PATH_MAX];
  5589. const char *s, *p;
  5590. struct file file = STRUCT_FILE_INITIALIZER;
  5591. size_t len;
  5592. int res = 1;
  5593. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5594. len = (size_t)(p - path);
  5595. if (len >= sizeof(buf)) {
  5596. /* path too long */
  5597. res = -1;
  5598. break;
  5599. }
  5600. memcpy(buf, path, len);
  5601. buf[len] = '\0';
  5602. /* Try to create intermediate directory */
  5603. DEBUG_TRACE("mkdir(%s)", buf);
  5604. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5605. /* path does not exixt and can not be created */
  5606. res = -2;
  5607. break;
  5608. }
  5609. /* Is path itself a directory? */
  5610. if (p[1] == '\0') {
  5611. res = 0;
  5612. }
  5613. }
  5614. return res;
  5615. }
  5616. static void
  5617. remove_bad_file(const struct mg_connection *conn, const char *path)
  5618. {
  5619. int r = mg_remove(path);
  5620. if (r != 0) {
  5621. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5622. }
  5623. }
  5624. long long
  5625. mg_store_body(struct mg_connection *conn, const char *path)
  5626. {
  5627. char buf[MG_BUF_LEN];
  5628. long long len = 0;
  5629. int ret, n;
  5630. struct file fi;
  5631. if (conn->consumed_content != 0) {
  5632. mg_cry(conn, "%s: Contents already consumed", __func__);
  5633. return -11;
  5634. }
  5635. ret = put_dir(conn, path);
  5636. if (ret < 0) {
  5637. /* -1 for path too long,
  5638. * -2 for path can not be created. */
  5639. return ret;
  5640. }
  5641. if (ret != 1) {
  5642. /* Return 0 means, path itself is a directory. */
  5643. return 0;
  5644. }
  5645. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5646. return -12;
  5647. }
  5648. ret = mg_read(conn, buf, sizeof(buf));
  5649. while (ret > 0) {
  5650. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5651. if (n != ret) {
  5652. fclose(fi.fp);
  5653. remove_bad_file(conn, path);
  5654. return -13;
  5655. }
  5656. ret = mg_read(conn, buf, sizeof(buf));
  5657. }
  5658. /* TODO: mg_fclose should return an error,
  5659. * and every caller should check and handle it. */
  5660. if (fclose(fi.fp) != 0) {
  5661. remove_bad_file(conn, path);
  5662. return -14;
  5663. }
  5664. return len;
  5665. }
  5666. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5667. * where parsing stopped. */
  5668. static void
  5669. parse_http_headers(char **buf, struct mg_request_info *ri)
  5670. {
  5671. int i;
  5672. if (!ri) {
  5673. return;
  5674. }
  5675. ri->num_headers = 0;
  5676. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5677. char *dp = *buf;
  5678. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5679. dp++;
  5680. }
  5681. if (!*dp) {
  5682. /* neither : nor \r\n. This is not a valid field. */
  5683. break;
  5684. }
  5685. if (*dp == '\r') {
  5686. if (dp[1] == '\n') {
  5687. /* \r\n */
  5688. ri->http_headers[i].name = *buf;
  5689. ri->http_headers[i].value = 0;
  5690. *buf = dp;
  5691. } else {
  5692. /* stray \r. This is not valid. */
  5693. break;
  5694. }
  5695. } else {
  5696. /* (*dp == ':') */
  5697. *dp = 0;
  5698. ri->http_headers[i].name = *buf;
  5699. do {
  5700. dp++;
  5701. } while (*dp == ' ');
  5702. ri->http_headers[i].value = dp;
  5703. *buf = strstr(dp, "\r\n");
  5704. }
  5705. ri->num_headers = i + 1;
  5706. if (*buf) {
  5707. (*buf)[0] = 0;
  5708. (*buf)[1] = 0;
  5709. *buf += 2;
  5710. } else {
  5711. *buf = dp;
  5712. break;
  5713. }
  5714. if (*buf[0] == '\r') {
  5715. /* This is the end of the header */
  5716. break;
  5717. }
  5718. }
  5719. }
  5720. static int
  5721. is_valid_http_method(const char *method)
  5722. {
  5723. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5724. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5725. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5726. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5727. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5728. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5729. /* TRACE method (RFC 2616) is not supported for security reasons */
  5730. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5731. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5732. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5733. /* Unsupported WEBDAV Methods: */
  5734. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5735. /* + 11 methods from RFC 3253 */
  5736. /* ORDERPATCH (RFC 3648) */
  5737. /* ACL (RFC 3744) */
  5738. /* SEARCH (RFC 5323) */
  5739. /* + MicroSoft extensions
  5740. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5741. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5742. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5743. }
  5744. /* Parse HTTP request, fill in mg_request_info structure.
  5745. * This function modifies the buffer by NUL-terminating
  5746. * HTTP request components, header names and header values. */
  5747. static int
  5748. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5749. {
  5750. int is_request, request_length;
  5751. if (!ri) {
  5752. return 0;
  5753. }
  5754. request_length = get_request_len(buf, len);
  5755. if (request_length > 0) {
  5756. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5757. * remote_port */
  5758. ri->remote_user = ri->request_method = ri->request_uri =
  5759. ri->http_version = NULL;
  5760. ri->num_headers = 0;
  5761. buf[request_length - 1] = '\0';
  5762. /* RFC says that all initial whitespaces should be ingored */
  5763. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5764. buf++;
  5765. }
  5766. ri->request_method = skip(&buf, " ");
  5767. ri->request_uri = skip(&buf, " ");
  5768. ri->http_version = skip(&buf, "\r\n");
  5769. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5770. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5771. is_request = is_valid_http_method(ri->request_method);
  5772. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5773. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5774. request_length = -1;
  5775. } else {
  5776. if (is_request) {
  5777. ri->http_version += 5;
  5778. }
  5779. parse_http_headers(&buf, ri);
  5780. }
  5781. }
  5782. return request_length;
  5783. }
  5784. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5785. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5786. * buffer (which marks the end of HTTP request). Buffer buf may already
  5787. * have some data. The length of the data is stored in nread.
  5788. * Upon every read operation, increase nread by the number of bytes read. */
  5789. static int
  5790. read_request(FILE *fp,
  5791. struct mg_connection *conn,
  5792. char *buf,
  5793. int bufsiz,
  5794. int *nread)
  5795. {
  5796. int request_len, n = 0;
  5797. struct timespec last_action_time;
  5798. double request_timeout;
  5799. if (!conn) {
  5800. return 0;
  5801. }
  5802. memset(&last_action_time, 0, sizeof(last_action_time));
  5803. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5804. /* value of request_timeout is in seconds, config in milliseconds */
  5805. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5806. } else {
  5807. request_timeout = -1.0;
  5808. }
  5809. request_len = get_request_len(buf, *nread);
  5810. /* first time reading from this connection */
  5811. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5812. while (
  5813. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5814. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5815. <= request_timeout) || (request_timeout < 0))
  5816. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5817. > 0)) {
  5818. *nread += n;
  5819. /* assert(*nread <= bufsiz); */
  5820. if (*nread > bufsiz) {
  5821. return -2;
  5822. }
  5823. request_len = get_request_len(buf, *nread);
  5824. if (request_timeout > 0.0) {
  5825. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5826. }
  5827. }
  5828. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5829. }
  5830. #if !defined(NO_FILES)
  5831. /* For given directory path, substitute it to valid index file.
  5832. * Return 1 if index file has been found, 0 if not found.
  5833. * If the file is found, it's stats is returned in stp. */
  5834. static int
  5835. substitute_index_file(struct mg_connection *conn,
  5836. char *path,
  5837. size_t path_len,
  5838. struct file *filep)
  5839. {
  5840. if (conn && conn->ctx) {
  5841. const char *list = conn->ctx->config[INDEX_FILES];
  5842. struct file file = STRUCT_FILE_INITIALIZER;
  5843. struct vec filename_vec;
  5844. size_t n = strlen(path);
  5845. int found = 0;
  5846. /* The 'path' given to us points to the directory. Remove all trailing
  5847. * directory separator characters from the end of the path, and
  5848. * then append single directory separator character. */
  5849. while (n > 0 && path[n - 1] == '/') {
  5850. n--;
  5851. }
  5852. path[n] = '/';
  5853. /* Traverse index files list. For each entry, append it to the given
  5854. * path and see if the file exists. If it exists, break the loop */
  5855. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5856. /* Ignore too long entries that may overflow path buffer */
  5857. if (filename_vec.len > path_len - (n + 2)) {
  5858. continue;
  5859. }
  5860. /* Prepare full path to the index file */
  5861. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5862. /* Does it exist? */
  5863. if (mg_stat(conn, path, &file)) {
  5864. /* Yes it does, break the loop */
  5865. *filep = file;
  5866. found = 1;
  5867. break;
  5868. }
  5869. }
  5870. /* If no index file exists, restore directory path */
  5871. if (!found) {
  5872. path[n] = '\0';
  5873. }
  5874. return found;
  5875. }
  5876. return 0;
  5877. }
  5878. #endif
  5879. /* Return True if we should reply 304 Not Modified. */
  5880. static int
  5881. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5882. {
  5883. char etag[64];
  5884. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5885. const char *inm = mg_get_header(conn, "If-None-Match");
  5886. construct_etag(etag, sizeof(etag), filep);
  5887. if (!filep) {
  5888. return 0;
  5889. }
  5890. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5891. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5892. }
  5893. #if !defined(NO_CGI) || !defined(NO_FILES)
  5894. static int
  5895. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5896. {
  5897. const char *expect, *body;
  5898. char buf[MG_BUF_LEN];
  5899. int to_read, nread, success = 0;
  5900. int64_t buffered_len;
  5901. double timeout = -1.0;
  5902. if (!conn) {
  5903. return 0;
  5904. }
  5905. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5906. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5907. }
  5908. expect = mg_get_header(conn, "Expect");
  5909. /* assert(fp != NULL); */
  5910. if (!fp) {
  5911. send_http_error(conn, 500, "%s", "Error: NULL File");
  5912. return 0;
  5913. }
  5914. if (conn->content_len == -1 && !conn->is_chunked) {
  5915. /* Content length is not specified by the client. */
  5916. send_http_error(conn,
  5917. 411,
  5918. "%s",
  5919. "Error: Client did not specify content length");
  5920. } else if ((expect != NULL)
  5921. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5922. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5923. send_http_error(conn,
  5924. 417,
  5925. "Error: Can not fulfill expectation %s",
  5926. expect);
  5927. } else {
  5928. if (expect != NULL) {
  5929. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5930. conn->status_code = 100;
  5931. } else {
  5932. conn->status_code = 200;
  5933. }
  5934. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5935. - conn->consumed_content;
  5936. /* assert(buffered_len >= 0); */
  5937. /* assert(conn->consumed_content == 0); */
  5938. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5939. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5940. return 0;
  5941. }
  5942. if (buffered_len > 0) {
  5943. if ((int64_t)buffered_len > conn->content_len) {
  5944. buffered_len = (int)conn->content_len;
  5945. }
  5946. body = conn->buf + conn->request_len + conn->consumed_content;
  5947. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5948. conn->consumed_content += buffered_len;
  5949. }
  5950. nread = 0;
  5951. while (conn->consumed_content < conn->content_len) {
  5952. to_read = sizeof(buf);
  5953. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5954. to_read = (int)(conn->content_len - conn->consumed_content);
  5955. }
  5956. nread = pull(NULL, conn, buf, to_read, timeout);
  5957. if (nread <= 0
  5958. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5959. break;
  5960. }
  5961. conn->consumed_content += nread;
  5962. }
  5963. if (conn->consumed_content == conn->content_len) {
  5964. success = (nread >= 0);
  5965. }
  5966. /* Each error code path in this function must send an error */
  5967. if (!success) {
  5968. /* NOTE: Maybe some data has already been sent. */
  5969. /* TODO (low): If some data has been sent, a correct error
  5970. * reply can no longer be sent, so just close the connection */
  5971. send_http_error(conn, 500, "%s", "");
  5972. }
  5973. }
  5974. return success;
  5975. }
  5976. #endif
  5977. #if !defined(NO_CGI)
  5978. /* This structure helps to create an environment for the spawned CGI program.
  5979. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5980. * last element must be NULL.
  5981. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5982. * strings must reside in a contiguous buffer. The end of the buffer is
  5983. * marked by two '\0' characters.
  5984. * We satisfy both worlds: we create an envp array (which is vars), all
  5985. * entries are actually pointers inside buf. */
  5986. struct cgi_environment {
  5987. struct mg_connection *conn;
  5988. /* Data block */
  5989. char *buf; /* Environment buffer */
  5990. size_t buflen; /* Space available in buf */
  5991. size_t bufused; /* Space taken in buf */
  5992. /* Index block */
  5993. char **var; /* char **envp */
  5994. size_t varlen; /* Number of variables available in var */
  5995. size_t varused; /* Number of variables stored in var */
  5996. };
  5997. static void addenv(struct cgi_environment *env,
  5998. PRINTF_FORMAT_STRING(const char *fmt),
  5999. ...) PRINTF_ARGS(2, 3);
  6000. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6001. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6002. static void
  6003. addenv(struct cgi_environment *env, const char *fmt, ...)
  6004. {
  6005. size_t n, space;
  6006. int truncated;
  6007. char *added;
  6008. va_list ap;
  6009. /* Calculate how much space is left in the buffer */
  6010. space = (env->buflen - env->bufused);
  6011. /* Calculate an estimate for the required space */
  6012. n = strlen(fmt) + 2 + 128;
  6013. do {
  6014. if (space <= n) {
  6015. /* Allocate new buffer */
  6016. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6017. added = (char *)mg_realloc(env->buf, n);
  6018. if (!added) {
  6019. /* Out of memory */
  6020. mg_cry(env->conn,
  6021. "%s: Cannot allocate memory for CGI variable [%s]",
  6022. __func__,
  6023. fmt);
  6024. return;
  6025. }
  6026. env->buf = added;
  6027. env->buflen = n;
  6028. space = (env->buflen - env->bufused);
  6029. }
  6030. /* Make a pointer to the free space int the buffer */
  6031. added = env->buf + env->bufused;
  6032. /* Copy VARIABLE=VALUE\0 string into the free space */
  6033. va_start(ap, fmt);
  6034. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6035. va_end(ap);
  6036. /* Do not add truncated strings to the environment */
  6037. if (truncated) {
  6038. /* Reallocate the buffer */
  6039. space = 0;
  6040. n = 1;
  6041. }
  6042. } while (truncated);
  6043. /* Calculate number of bytes added to the environment */
  6044. n = strlen(added) + 1;
  6045. env->bufused += n;
  6046. /* Now update the variable index */
  6047. space = (env->varlen - env->varused);
  6048. if (space < 2) {
  6049. mg_cry(env->conn,
  6050. "%s: Cannot register CGI variable [%s]",
  6051. __func__,
  6052. fmt);
  6053. return;
  6054. }
  6055. /* Append a pointer to the added string into the envp array */
  6056. env->var[env->varused] = added;
  6057. env->varused++;
  6058. }
  6059. static void
  6060. prepare_cgi_environment(struct mg_connection *conn,
  6061. const char *prog,
  6062. struct cgi_environment *env)
  6063. {
  6064. const char *s;
  6065. struct vec var_vec;
  6066. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6067. int i, truncated;
  6068. if (conn == NULL || prog == NULL || env == NULL) {
  6069. return;
  6070. }
  6071. env->conn = conn;
  6072. env->buflen = CGI_ENVIRONMENT_SIZE;
  6073. env->bufused = 0;
  6074. env->buf = (char *)mg_malloc(env->buflen);
  6075. env->varlen = MAX_CGI_ENVIR_VARS;
  6076. env->varused = 0;
  6077. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6078. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6079. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6080. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6081. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6082. /* Prepare the environment block */
  6083. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6084. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6085. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6086. #if defined(USE_IPV6)
  6087. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6088. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6089. } else
  6090. #endif
  6091. {
  6092. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6093. }
  6094. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6095. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6096. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6097. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6098. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6099. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6100. /* SCRIPT_NAME */
  6101. addenv(env,
  6102. "SCRIPT_NAME=%.*s",
  6103. (int)strlen(conn->request_info.local_uri)
  6104. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6105. conn->request_info.local_uri);
  6106. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6107. if (conn->path_info == NULL) {
  6108. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6109. } else {
  6110. addenv(env,
  6111. "PATH_TRANSLATED=%s%s",
  6112. conn->ctx->config[DOCUMENT_ROOT],
  6113. conn->path_info);
  6114. }
  6115. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6116. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6117. addenv(env, "CONTENT_TYPE=%s", s);
  6118. }
  6119. if (conn->request_info.query_string != NULL) {
  6120. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6121. }
  6122. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6123. addenv(env, "CONTENT_LENGTH=%s", s);
  6124. }
  6125. if ((s = getenv("PATH")) != NULL) {
  6126. addenv(env, "PATH=%s", s);
  6127. }
  6128. if (conn->path_info != NULL) {
  6129. addenv(env, "PATH_INFO=%s", conn->path_info);
  6130. }
  6131. if (conn->status_code > 0) {
  6132. /* CGI error handler should show the status code */
  6133. addenv(env, "STATUS=%d", conn->status_code);
  6134. }
  6135. #if defined(_WIN32)
  6136. if ((s = getenv("COMSPEC")) != NULL) {
  6137. addenv(env, "COMSPEC=%s", s);
  6138. }
  6139. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6140. addenv(env, "SYSTEMROOT=%s", s);
  6141. }
  6142. if ((s = getenv("SystemDrive")) != NULL) {
  6143. addenv(env, "SystemDrive=%s", s);
  6144. }
  6145. if ((s = getenv("ProgramFiles")) != NULL) {
  6146. addenv(env, "ProgramFiles=%s", s);
  6147. }
  6148. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6149. addenv(env, "ProgramFiles(x86)=%s", s);
  6150. }
  6151. #else
  6152. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6153. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6154. }
  6155. #endif /* _WIN32 */
  6156. if ((s = getenv("PERLLIB")) != NULL) {
  6157. addenv(env, "PERLLIB=%s", s);
  6158. }
  6159. if (conn->request_info.remote_user != NULL) {
  6160. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6161. addenv(env, "%s", "AUTH_TYPE=Digest");
  6162. }
  6163. /* Add all headers as HTTP_* variables */
  6164. for (i = 0; i < conn->request_info.num_headers; i++) {
  6165. (void)mg_snprintf(conn,
  6166. &truncated,
  6167. http_var_name,
  6168. sizeof(http_var_name),
  6169. "HTTP_%s",
  6170. conn->request_info.http_headers[i].name);
  6171. if (truncated) {
  6172. mg_cry(conn,
  6173. "%s: HTTP header variable too long [%s]",
  6174. __func__,
  6175. conn->request_info.http_headers[i].name);
  6176. continue;
  6177. }
  6178. /* Convert variable name into uppercase, and change - to _ */
  6179. for (p = http_var_name; *p != '\0'; p++) {
  6180. if (*p == '-') {
  6181. *p = '_';
  6182. }
  6183. *p = (char)toupper(*(unsigned char *)p);
  6184. }
  6185. addenv(env,
  6186. "%s=%s",
  6187. http_var_name,
  6188. conn->request_info.http_headers[i].value);
  6189. }
  6190. /* Add user-specified variables */
  6191. s = conn->ctx->config[CGI_ENVIRONMENT];
  6192. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6193. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6194. }
  6195. env->var[env->varused] = NULL;
  6196. env->buf[env->bufused] = '\0';
  6197. }
  6198. static void
  6199. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6200. {
  6201. char *buf;
  6202. size_t buflen;
  6203. int headers_len, data_len, i, truncated;
  6204. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6205. const char *status, *status_text, *connection_state;
  6206. char *pbuf, dir[PATH_MAX], *p;
  6207. struct mg_request_info ri;
  6208. struct cgi_environment blk;
  6209. FILE *in = NULL, *out = NULL, *err = NULL;
  6210. struct file fout = STRUCT_FILE_INITIALIZER;
  6211. pid_t pid = (pid_t)-1;
  6212. if (conn == NULL) {
  6213. return;
  6214. }
  6215. buf = NULL;
  6216. buflen = 16384;
  6217. prepare_cgi_environment(conn, prog, &blk);
  6218. /* CGI must be executed in its own directory. 'dir' must point to the
  6219. * directory containing executable program, 'p' must point to the
  6220. * executable program name relative to 'dir'. */
  6221. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6222. if (truncated) {
  6223. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6224. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6225. goto done;
  6226. }
  6227. if ((p = strrchr(dir, '/')) != NULL) {
  6228. *p++ = '\0';
  6229. } else {
  6230. dir[0] = '.', dir[1] = '\0';
  6231. p = (char *)prog;
  6232. }
  6233. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6234. status = strerror(ERRNO);
  6235. mg_cry(conn,
  6236. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6237. prog,
  6238. status);
  6239. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6240. goto done;
  6241. }
  6242. pid = spawn_process(
  6243. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  6244. if (pid == (pid_t)-1) {
  6245. status = strerror(ERRNO);
  6246. mg_cry(conn,
  6247. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6248. prog,
  6249. status);
  6250. send_http_error(conn,
  6251. 500,
  6252. "Error: Cannot spawn CGI process [%s]: %s",
  6253. prog,
  6254. status);
  6255. goto done;
  6256. }
  6257. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6258. set_close_on_exec((SOCKET)fdin[0], conn);
  6259. set_close_on_exec((SOCKET)fdin[1], conn);
  6260. set_close_on_exec((SOCKET)fdout[0], conn);
  6261. set_close_on_exec((SOCKET)fdout[1], conn);
  6262. set_close_on_exec((SOCKET)fderr[0], conn);
  6263. set_close_on_exec((SOCKET)fderr[1], conn);
  6264. /* Parent closes only one side of the pipes.
  6265. * If we don't mark them as closed, close() attempt before
  6266. * return from this function throws an exception on Windows.
  6267. * Windows does not like when closed descriptor is closed again. */
  6268. (void)close(fdin[0]);
  6269. (void)close(fdout[1]);
  6270. (void)close(fderr[1]);
  6271. fdin[0] = fdout[1] = fderr[1] = -1;
  6272. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6273. status = strerror(ERRNO);
  6274. mg_cry(conn,
  6275. "Error: CGI program \"%s\": Can not open stdin: %s",
  6276. prog,
  6277. status);
  6278. send_http_error(conn,
  6279. 500,
  6280. "Error: CGI can not open fdin\nfopen: %s",
  6281. status);
  6282. goto done;
  6283. }
  6284. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6285. status = strerror(ERRNO);
  6286. mg_cry(conn,
  6287. "Error: CGI program \"%s\": Can not open stdout: %s",
  6288. prog,
  6289. status);
  6290. send_http_error(conn,
  6291. 500,
  6292. "Error: CGI can not open fdout\nfopen: %s",
  6293. status);
  6294. goto done;
  6295. }
  6296. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6297. status = strerror(ERRNO);
  6298. mg_cry(conn,
  6299. "Error: CGI program \"%s\": Can not open stderr: %s",
  6300. prog,
  6301. status);
  6302. send_http_error(conn,
  6303. 500,
  6304. "Error: CGI can not open fdout\nfopen: %s",
  6305. status);
  6306. goto done;
  6307. }
  6308. setbuf(in, NULL);
  6309. setbuf(out, NULL);
  6310. setbuf(err, NULL);
  6311. fout.fp = out;
  6312. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6313. /* This is a POST/PUT request, or another request with body data. */
  6314. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6315. /* Error sending the body data */
  6316. mg_cry(conn,
  6317. "Error: CGI program \"%s\": Forward body data failed",
  6318. prog);
  6319. goto done;
  6320. }
  6321. }
  6322. /* Close so child gets an EOF. */
  6323. fclose(in);
  6324. in = NULL;
  6325. fdin[1] = -1;
  6326. /* Now read CGI reply into a buffer. We need to set correct
  6327. * status code, thus we need to see all HTTP headers first.
  6328. * Do not send anything back to client, until we buffer in all
  6329. * HTTP headers. */
  6330. data_len = 0;
  6331. buf = (char *)mg_malloc(buflen);
  6332. if (buf == NULL) {
  6333. send_http_error(conn,
  6334. 500,
  6335. "Error: Not enough memory for CGI buffer (%u bytes)",
  6336. (unsigned int)buflen);
  6337. mg_cry(conn,
  6338. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6339. "bytes)",
  6340. prog,
  6341. (unsigned int)buflen);
  6342. goto done;
  6343. }
  6344. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6345. if (headers_len <= 0) {
  6346. /* Could not parse the CGI response. Check if some error message on
  6347. * stderr. */
  6348. i = pull_all(err, conn, buf, (int)buflen);
  6349. if (i > 0) {
  6350. mg_cry(conn,
  6351. "Error: CGI program \"%s\" sent error "
  6352. "message: [%.*s]",
  6353. prog,
  6354. i,
  6355. buf);
  6356. send_http_error(conn,
  6357. 500,
  6358. "Error: CGI program \"%s\" sent error "
  6359. "message: [%.*s]",
  6360. prog,
  6361. i,
  6362. buf);
  6363. } else {
  6364. mg_cry(conn,
  6365. "Error: CGI program sent malformed or too big "
  6366. "(>%u bytes) HTTP headers: [%.*s]",
  6367. (unsigned)buflen,
  6368. data_len,
  6369. buf);
  6370. send_http_error(conn,
  6371. 500,
  6372. "Error: CGI program sent malformed or too big "
  6373. "(>%u bytes) HTTP headers: [%.*s]",
  6374. (unsigned)buflen,
  6375. data_len,
  6376. buf);
  6377. }
  6378. goto done;
  6379. }
  6380. pbuf = buf;
  6381. buf[headers_len - 1] = '\0';
  6382. parse_http_headers(&pbuf, &ri);
  6383. /* Make up and send the status line */
  6384. status_text = "OK";
  6385. if ((status = get_header(&ri, "Status")) != NULL) {
  6386. conn->status_code = atoi(status);
  6387. status_text = status;
  6388. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6389. status_text++;
  6390. }
  6391. } else if (get_header(&ri, "Location") != NULL) {
  6392. conn->status_code = 302;
  6393. } else {
  6394. conn->status_code = 200;
  6395. }
  6396. connection_state = get_header(&ri, "Connection");
  6397. if (connection_state == NULL
  6398. || mg_strcasecmp(connection_state, "keep-alive")) {
  6399. conn->must_close = 1;
  6400. }
  6401. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6402. /* Send headers */
  6403. for (i = 0; i < ri.num_headers; i++) {
  6404. mg_printf(conn,
  6405. "%s: %s\r\n",
  6406. ri.http_headers[i].name,
  6407. ri.http_headers[i].value);
  6408. }
  6409. mg_write(conn, "\r\n", 2);
  6410. /* Send chunk of data that may have been read after the headers */
  6411. conn->num_bytes_sent +=
  6412. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6413. /* Read the rest of CGI output and send to the client */
  6414. send_file_data(conn, &fout, 0, INT64_MAX);
  6415. done:
  6416. mg_free(blk.var);
  6417. mg_free(blk.buf);
  6418. if (pid != (pid_t)-1) {
  6419. kill(pid, SIGKILL);
  6420. #if !defined(_WIN32)
  6421. {
  6422. int st;
  6423. while (waitpid(pid, &st, 0) != -1)
  6424. ; /* clean zombies */
  6425. }
  6426. #endif
  6427. }
  6428. if (fdin[0] != -1) {
  6429. close(fdin[0]);
  6430. }
  6431. if (fdout[1] != -1) {
  6432. close(fdout[1]);
  6433. }
  6434. if (in != NULL) {
  6435. fclose(in);
  6436. } else if (fdin[1] != -1) {
  6437. close(fdin[1]);
  6438. }
  6439. if (out != NULL) {
  6440. fclose(out);
  6441. } else if (fdout[0] != -1) {
  6442. close(fdout[0]);
  6443. }
  6444. if (err != NULL) {
  6445. fclose(err);
  6446. } else if (fderr[0] != -1) {
  6447. close(fderr[0]);
  6448. }
  6449. if (buf != NULL) {
  6450. mg_free(buf);
  6451. }
  6452. }
  6453. #endif /* !NO_CGI */
  6454. #if !defined(NO_FILES)
  6455. static void
  6456. mkcol(struct mg_connection *conn, const char *path)
  6457. {
  6458. int rc, body_len;
  6459. struct de de;
  6460. char date[64];
  6461. time_t curtime = time(NULL);
  6462. if (conn == NULL) {
  6463. return;
  6464. }
  6465. /* TODO (mid): Check the send_http_error situations in this function */
  6466. memset(&de.file, 0, sizeof(de.file));
  6467. if (!mg_stat(conn, path, &de.file)) {
  6468. mg_cry(conn,
  6469. "%s: mg_stat(%s) failed: %s",
  6470. __func__,
  6471. path,
  6472. strerror(ERRNO));
  6473. }
  6474. if (de.file.last_modified) {
  6475. /* TODO (high): This check does not seem to make any sense ! */
  6476. send_http_error(
  6477. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6478. return;
  6479. }
  6480. body_len = conn->data_len - conn->request_len;
  6481. if (body_len > 0) {
  6482. send_http_error(
  6483. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6484. return;
  6485. }
  6486. rc = mg_mkdir(path, 0755);
  6487. if (rc == 0) {
  6488. conn->status_code = 201;
  6489. gmt_time_string(date, sizeof(date), &curtime);
  6490. mg_printf(conn,
  6491. "HTTP/1.1 %d Created\r\n"
  6492. "Date: %s\r\n",
  6493. conn->status_code,
  6494. date);
  6495. send_static_cache_header(conn);
  6496. mg_printf(conn,
  6497. "Content-Length: 0\r\n"
  6498. "Connection: %s\r\n\r\n",
  6499. suggest_connection_header(conn));
  6500. } else if (rc == -1) {
  6501. if (errno == EEXIST) {
  6502. send_http_error(
  6503. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6504. } else if (errno == EACCES) {
  6505. send_http_error(
  6506. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6507. } else if (errno == ENOENT) {
  6508. send_http_error(
  6509. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6510. } else {
  6511. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6512. }
  6513. }
  6514. }
  6515. static void
  6516. put_file(struct mg_connection *conn, const char *path)
  6517. {
  6518. struct file file = STRUCT_FILE_INITIALIZER;
  6519. const char *range;
  6520. int64_t r1, r2;
  6521. int rc;
  6522. char date[64];
  6523. time_t curtime = time(NULL);
  6524. if (conn == NULL) {
  6525. return;
  6526. }
  6527. if (mg_stat(conn, path, &file)) {
  6528. /* File already exists */
  6529. conn->status_code = 200;
  6530. if (file.is_directory) {
  6531. /* This is an already existing directory,
  6532. * so there is nothing to do for the server. */
  6533. rc = 0;
  6534. } else {
  6535. /* File exists and is not a directory. */
  6536. /* Can it be replaced? */
  6537. if (file.membuf != NULL) {
  6538. /* This is an "in-memory" file, that can not be replaced */
  6539. send_http_error(
  6540. conn,
  6541. 405,
  6542. "Error: Put not possible\nReplacing %s is not supported",
  6543. path);
  6544. return;
  6545. }
  6546. /* Check if the server may write this file */
  6547. if (access(path, W_OK) == 0) {
  6548. /* Access granted */
  6549. conn->status_code = 200;
  6550. rc = 1;
  6551. } else {
  6552. send_http_error(
  6553. conn,
  6554. 403,
  6555. "Error: Put not possible\nReplacing %s is not allowed",
  6556. path);
  6557. return;
  6558. }
  6559. }
  6560. } else {
  6561. /* File should be created */
  6562. conn->status_code = 201;
  6563. rc = put_dir(conn, path);
  6564. }
  6565. if (rc == 0) {
  6566. /* put_dir returns 0 if path is a directory */
  6567. gmt_time_string(date, sizeof(date), &curtime);
  6568. mg_printf(conn,
  6569. "HTTP/1.1 %d %s\r\n",
  6570. conn->status_code,
  6571. mg_get_response_code_text(conn->status_code, NULL));
  6572. send_no_cache_header(conn);
  6573. mg_printf(conn,
  6574. "Date: %s\r\n"
  6575. "Content-Length: 0\r\n"
  6576. "Connection: %s\r\n\r\n",
  6577. date,
  6578. suggest_connection_header(conn));
  6579. /* Request to create a directory has been fulfilled successfully.
  6580. * No need to put a file. */
  6581. return;
  6582. }
  6583. if (rc == -1) {
  6584. /* put_dir returns -1 if the path is too long */
  6585. send_http_error(conn,
  6586. 414,
  6587. "Error: Path too long\nput_dir(%s): %s",
  6588. path,
  6589. strerror(ERRNO));
  6590. return;
  6591. }
  6592. if (rc == -2) {
  6593. /* put_dir returns -2 if the directory can not be created */
  6594. send_http_error(conn,
  6595. 500,
  6596. "Error: Can not create directory\nput_dir(%s): %s",
  6597. path,
  6598. strerror(ERRNO));
  6599. return;
  6600. }
  6601. /* A file should be created or overwritten. */
  6602. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6603. mg_fclose(&file);
  6604. send_http_error(conn,
  6605. 500,
  6606. "Error: Can not create file\nfopen(%s): %s",
  6607. path,
  6608. strerror(ERRNO));
  6609. return;
  6610. }
  6611. fclose_on_exec(&file, conn);
  6612. range = mg_get_header(conn, "Content-Range");
  6613. r1 = r2 = 0;
  6614. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6615. conn->status_code = 206; /* Partial content */
  6616. fseeko(file.fp, r1, SEEK_SET);
  6617. }
  6618. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6619. /* forward_body_data failed.
  6620. * The error code has already been sent to the client,
  6621. * and conn->status_code is already set. */
  6622. mg_fclose(&file);
  6623. return;
  6624. }
  6625. gmt_time_string(date, sizeof(date), &curtime);
  6626. mg_printf(conn,
  6627. "HTTP/1.1 %d %s\r\n",
  6628. conn->status_code,
  6629. mg_get_response_code_text(conn->status_code, NULL));
  6630. send_no_cache_header(conn);
  6631. mg_printf(conn,
  6632. "Date: %s\r\n"
  6633. "Content-Length: 0\r\n"
  6634. "Connection: %s\r\n\r\n",
  6635. date,
  6636. suggest_connection_header(conn));
  6637. mg_fclose(&file);
  6638. }
  6639. static void
  6640. delete_file(struct mg_connection *conn, const char *path)
  6641. {
  6642. struct de de;
  6643. memset(&de.file, 0, sizeof(de.file));
  6644. if (!mg_stat(conn, path, &de.file)) {
  6645. /* mg_stat returns 0 if the file does not exist */
  6646. send_http_error(conn,
  6647. 404,
  6648. "Error: Cannot delete file\nFile %s not found",
  6649. path);
  6650. return;
  6651. }
  6652. if (de.file.membuf != NULL) {
  6653. /* the file is cached in memory */
  6654. send_http_error(
  6655. conn,
  6656. 405,
  6657. "Error: Delete not possible\nDeleting %s is not supported",
  6658. path);
  6659. return;
  6660. }
  6661. if (de.file.is_directory) {
  6662. if (remove_directory(conn, path)) {
  6663. /* Delete is successful: Return 204 without content. */
  6664. send_http_error(conn, 204, "%s", "");
  6665. } else {
  6666. /* Delete is not successful: Return 500 (Server error). */
  6667. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6668. }
  6669. return;
  6670. }
  6671. /* This is an existing file (not a directory).
  6672. * Check if write permission is granted. */
  6673. if (access(path, W_OK) != 0) {
  6674. /* File is read only */
  6675. send_http_error(
  6676. conn,
  6677. 403,
  6678. "Error: Delete not possible\nDeleting %s is not allowed",
  6679. path);
  6680. return;
  6681. }
  6682. /* Try to delete it. */
  6683. if (mg_remove(path) == 0) {
  6684. /* Delete was successful: Return 204 without content. */
  6685. send_http_error(conn, 204, "%s", "");
  6686. } else {
  6687. /* Delete not successful (file locked). */
  6688. send_http_error(conn,
  6689. 423,
  6690. "Error: Cannot delete file\nremove(%s): %s",
  6691. path,
  6692. strerror(ERRNO));
  6693. }
  6694. }
  6695. #endif /* !NO_FILES */
  6696. static void
  6697. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6698. static void
  6699. do_ssi_include(struct mg_connection *conn,
  6700. const char *ssi,
  6701. char *tag,
  6702. int include_level)
  6703. {
  6704. char file_name[MG_BUF_LEN], path[512], *p;
  6705. struct file file = STRUCT_FILE_INITIALIZER;
  6706. size_t len;
  6707. int truncated = 0;
  6708. if (conn == NULL) {
  6709. return;
  6710. }
  6711. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6712. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6713. * always < MG_BUF_LEN. */
  6714. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6715. /* File name is relative to the webserver root */
  6716. file_name[511] = 0;
  6717. (void)mg_snprintf(conn,
  6718. &truncated,
  6719. path,
  6720. sizeof(path),
  6721. "%s/%s",
  6722. conn->ctx->config[DOCUMENT_ROOT],
  6723. file_name);
  6724. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6725. /* File name is relative to the webserver working directory
  6726. * or it is absolute system path */
  6727. file_name[511] = 0;
  6728. (void)
  6729. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6730. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6731. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6732. /* File name is relative to the currect document */
  6733. file_name[511] = 0;
  6734. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6735. if (!truncated) {
  6736. if ((p = strrchr(path, '/')) != NULL) {
  6737. p[1] = '\0';
  6738. }
  6739. len = strlen(path);
  6740. (void)mg_snprintf(conn,
  6741. &truncated,
  6742. path + len,
  6743. sizeof(path) - len,
  6744. "%s",
  6745. file_name);
  6746. }
  6747. } else {
  6748. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6749. return;
  6750. }
  6751. if (truncated) {
  6752. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6753. return;
  6754. }
  6755. if (!mg_fopen(conn, path, "rb", &file)) {
  6756. mg_cry(conn,
  6757. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6758. tag,
  6759. path,
  6760. strerror(ERRNO));
  6761. } else {
  6762. fclose_on_exec(&file, conn);
  6763. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6764. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6765. path) > 0) {
  6766. send_ssi_file(conn, path, &file, include_level + 1);
  6767. } else {
  6768. send_file_data(conn, &file, 0, INT64_MAX);
  6769. }
  6770. mg_fclose(&file);
  6771. }
  6772. }
  6773. #if !defined(NO_POPEN)
  6774. static void
  6775. do_ssi_exec(struct mg_connection *conn, char *tag)
  6776. {
  6777. char cmd[1024] = "";
  6778. struct file file = STRUCT_FILE_INITIALIZER;
  6779. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6780. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6781. } else {
  6782. cmd[1023] = 0;
  6783. if ((file.fp = popen(cmd, "r")) == NULL) {
  6784. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6785. } else {
  6786. send_file_data(conn, &file, 0, INT64_MAX);
  6787. pclose(file.fp);
  6788. }
  6789. }
  6790. }
  6791. #endif /* !NO_POPEN */
  6792. static int
  6793. mg_fgetc(struct file *filep, int offset)
  6794. {
  6795. if (filep == NULL) {
  6796. return EOF;
  6797. }
  6798. if (filep->membuf != NULL && offset >= 0
  6799. && ((unsigned int)(offset)) < filep->size) {
  6800. return ((unsigned char *)filep->membuf)[offset];
  6801. } else if (filep->fp != NULL) {
  6802. return fgetc(filep->fp);
  6803. } else {
  6804. return EOF;
  6805. }
  6806. }
  6807. static void
  6808. send_ssi_file(struct mg_connection *conn,
  6809. const char *path,
  6810. struct file *filep,
  6811. int include_level)
  6812. {
  6813. char buf[MG_BUF_LEN];
  6814. int ch, offset, len, in_ssi_tag;
  6815. if (include_level > 10) {
  6816. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6817. return;
  6818. }
  6819. in_ssi_tag = len = offset = 0;
  6820. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6821. if (in_ssi_tag && ch == '>') {
  6822. in_ssi_tag = 0;
  6823. buf[len++] = (char)ch;
  6824. buf[len] = '\0';
  6825. /* assert(len <= (int) sizeof(buf)); */
  6826. if (len > (int)sizeof(buf)) {
  6827. break;
  6828. }
  6829. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6830. /* Not an SSI tag, pass it */
  6831. (void)mg_write(conn, buf, (size_t)len);
  6832. } else {
  6833. if (!memcmp(buf + 5, "include", 7)) {
  6834. do_ssi_include(conn, path, buf + 12, include_level);
  6835. #if !defined(NO_POPEN)
  6836. } else if (!memcmp(buf + 5, "exec", 4)) {
  6837. do_ssi_exec(conn, buf + 9);
  6838. #endif /* !NO_POPEN */
  6839. } else {
  6840. mg_cry(conn,
  6841. "%s: unknown SSI "
  6842. "command: \"%s\"",
  6843. path,
  6844. buf);
  6845. }
  6846. }
  6847. len = 0;
  6848. } else if (in_ssi_tag) {
  6849. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6850. /* Not an SSI tag */
  6851. in_ssi_tag = 0;
  6852. } else if (len == (int)sizeof(buf) - 2) {
  6853. mg_cry(conn, "%s: SSI tag is too large", path);
  6854. len = 0;
  6855. }
  6856. buf[len++] = (char)(ch & 0xff);
  6857. } else if (ch == '<') {
  6858. in_ssi_tag = 1;
  6859. if (len > 0) {
  6860. mg_write(conn, buf, (size_t)len);
  6861. }
  6862. len = 0;
  6863. buf[len++] = (char)(ch & 0xff);
  6864. } else {
  6865. buf[len++] = (char)(ch & 0xff);
  6866. if (len == (int)sizeof(buf)) {
  6867. mg_write(conn, buf, (size_t)len);
  6868. len = 0;
  6869. }
  6870. }
  6871. }
  6872. /* Send the rest of buffered data */
  6873. if (len > 0) {
  6874. mg_write(conn, buf, (size_t)len);
  6875. }
  6876. }
  6877. static void
  6878. handle_ssi_file_request(struct mg_connection *conn,
  6879. const char *path,
  6880. struct file *filep)
  6881. {
  6882. char date[64];
  6883. time_t curtime = time(NULL);
  6884. const char *cors1, *cors2, *cors3;
  6885. if (conn == NULL || path == NULL || filep == NULL) {
  6886. return;
  6887. }
  6888. if (mg_get_header(conn, "Origin")) {
  6889. /* Cross-origin resource sharing (CORS). */
  6890. cors1 = "Access-Control-Allow-Origin: ";
  6891. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6892. cors3 = "\r\n";
  6893. } else {
  6894. cors1 = cors2 = cors3 = "";
  6895. }
  6896. if (!mg_fopen(conn, path, "rb", filep)) {
  6897. /* File exists (precondition for calling this function),
  6898. * but can not be opened by the server. */
  6899. send_http_error(conn,
  6900. 500,
  6901. "Error: Cannot read file\nfopen(%s): %s",
  6902. path,
  6903. strerror(ERRNO));
  6904. } else {
  6905. conn->must_close = 1;
  6906. gmt_time_string(date, sizeof(date), &curtime);
  6907. fclose_on_exec(filep, conn);
  6908. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6909. send_no_cache_header(conn);
  6910. mg_printf(conn,
  6911. "%s%s%s"
  6912. "Date: %s\r\n"
  6913. "Content-Type: text/html\r\n"
  6914. "Connection: %s\r\n\r\n",
  6915. cors1,
  6916. cors2,
  6917. cors3,
  6918. date,
  6919. suggest_connection_header(conn));
  6920. send_ssi_file(conn, path, filep, 0);
  6921. mg_fclose(filep);
  6922. }
  6923. }
  6924. #if !defined(NO_FILES)
  6925. static void
  6926. send_options(struct mg_connection *conn)
  6927. {
  6928. char date[64];
  6929. time_t curtime = time(NULL);
  6930. if (!conn) {
  6931. return;
  6932. }
  6933. conn->status_code = 200;
  6934. conn->must_close = 1;
  6935. gmt_time_string(date, sizeof(date), &curtime);
  6936. mg_printf(conn,
  6937. "HTTP/1.1 200 OK\r\n"
  6938. "Date: %s\r\n"
  6939. /* TODO: "Cache-Control" (?) */
  6940. "Connection: %s\r\n"
  6941. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6942. "PROPFIND, MKCOL\r\n"
  6943. "DAV: 1\r\n\r\n",
  6944. date,
  6945. suggest_connection_header(conn));
  6946. }
  6947. /* Writes PROPFIND properties for a collection element */
  6948. static void
  6949. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6950. {
  6951. char mtime[64];
  6952. if (conn == NULL || uri == NULL || filep == NULL) {
  6953. return;
  6954. }
  6955. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6956. conn->num_bytes_sent +=
  6957. mg_printf(conn,
  6958. "<d:response>"
  6959. "<d:href>%s</d:href>"
  6960. "<d:propstat>"
  6961. "<d:prop>"
  6962. "<d:resourcetype>%s</d:resourcetype>"
  6963. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6964. "<d:getlastmodified>%s</d:getlastmodified>"
  6965. "</d:prop>"
  6966. "<d:status>HTTP/1.1 200 OK</d:status>"
  6967. "</d:propstat>"
  6968. "</d:response>\n",
  6969. uri,
  6970. filep->is_directory ? "<d:collection/>" : "",
  6971. filep->size,
  6972. mtime);
  6973. }
  6974. static void
  6975. print_dav_dir_entry(struct de *de, void *data)
  6976. {
  6977. char href[PATH_MAX];
  6978. char href_encoded[PATH_MAX];
  6979. int truncated;
  6980. struct mg_connection *conn = (struct mg_connection *)data;
  6981. if (!de || !conn) {
  6982. return;
  6983. }
  6984. mg_snprintf(conn,
  6985. &truncated,
  6986. href,
  6987. sizeof(href),
  6988. "%s%s",
  6989. conn->request_info.local_uri,
  6990. de->file_name);
  6991. if (!truncated) {
  6992. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6993. print_props(conn, href_encoded, &de->file);
  6994. }
  6995. }
  6996. static void
  6997. handle_propfind(struct mg_connection *conn,
  6998. const char *path,
  6999. struct file *filep)
  7000. {
  7001. const char *depth = mg_get_header(conn, "Depth");
  7002. char date[64];
  7003. time_t curtime = time(NULL);
  7004. gmt_time_string(date, sizeof(date), &curtime);
  7005. if (!conn || !path || !filep || !conn->ctx) {
  7006. return;
  7007. }
  7008. conn->must_close = 1;
  7009. conn->status_code = 207;
  7010. mg_printf(conn,
  7011. "HTTP/1.1 207 Multi-Status\r\n"
  7012. "Date: %s\r\n",
  7013. date);
  7014. send_static_cache_header(conn);
  7015. mg_printf(conn,
  7016. "Connection: %s\r\n"
  7017. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7018. suggest_connection_header(conn));
  7019. conn->num_bytes_sent +=
  7020. mg_printf(conn,
  7021. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7022. "<d:multistatus xmlns:d='DAV:'>\n");
  7023. /* Print properties for the requested resource itself */
  7024. print_props(conn, conn->request_info.local_uri, filep);
  7025. /* If it is a directory, print directory entries too if Depth is not 0 */
  7026. if (filep && filep->is_directory
  7027. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7028. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7029. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7030. }
  7031. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7032. }
  7033. #endif
  7034. void
  7035. mg_lock_connection(struct mg_connection *conn)
  7036. {
  7037. if (conn) {
  7038. (void)pthread_mutex_lock(&conn->mutex);
  7039. }
  7040. }
  7041. void
  7042. mg_unlock_connection(struct mg_connection *conn)
  7043. {
  7044. if (conn) {
  7045. (void)pthread_mutex_unlock(&conn->mutex);
  7046. }
  7047. }
  7048. void
  7049. mg_lock_context(struct mg_context *ctx)
  7050. {
  7051. if (ctx) {
  7052. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7053. }
  7054. }
  7055. void
  7056. mg_unlock_context(struct mg_context *ctx)
  7057. {
  7058. if (ctx) {
  7059. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7060. }
  7061. }
  7062. #if defined(USE_TIMERS)
  7063. #include "timer.inl"
  7064. #endif /* USE_TIMERS */
  7065. #ifdef USE_LUA
  7066. #include "mod_lua.inl"
  7067. #endif /* USE_LUA */
  7068. #ifdef USE_DUKTAPE
  7069. #include "mod_duktape.inl"
  7070. #endif /* USE_DUKTAPE */
  7071. #if defined(USE_WEBSOCKET)
  7072. /* START OF SHA-1 code
  7073. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7074. #define SHA1HANDSOFF
  7075. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7076. *
  7077. * #if defined(__sun)
  7078. * #include "solarisfixes.h"
  7079. * #endif
  7080. */
  7081. static int
  7082. is_big_endian(void)
  7083. {
  7084. static const int n = 1;
  7085. return ((char *)&n)[0] == 0;
  7086. }
  7087. union char64long16 {
  7088. unsigned char c[64];
  7089. uint32_t l[16];
  7090. };
  7091. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7092. static uint32_t
  7093. blk0(union char64long16 *block, int i)
  7094. {
  7095. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7096. if (!is_big_endian()) {
  7097. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7098. | (rol(block->l[i], 8) & 0x00FF00FF);
  7099. }
  7100. return block->l[i];
  7101. }
  7102. #define blk(i) \
  7103. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7104. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7105. 1))
  7106. #define R0(v, w, x, y, z, i) \
  7107. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7108. w = rol(w, 30);
  7109. #define R1(v, w, x, y, z, i) \
  7110. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7111. w = rol(w, 30);
  7112. #define R2(v, w, x, y, z, i) \
  7113. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7114. w = rol(w, 30);
  7115. #define R3(v, w, x, y, z, i) \
  7116. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7117. w = rol(w, 30);
  7118. #define R4(v, w, x, y, z, i) \
  7119. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7120. w = rol(w, 30);
  7121. typedef struct {
  7122. uint32_t state[5];
  7123. uint32_t count[2];
  7124. unsigned char buffer[64];
  7125. } SHA1_CTX;
  7126. static void
  7127. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7128. {
  7129. uint32_t a, b, c, d, e;
  7130. union char64long16 block[1];
  7131. memcpy(block, buffer, 64);
  7132. a = state[0];
  7133. b = state[1];
  7134. c = state[2];
  7135. d = state[3];
  7136. e = state[4];
  7137. R0(a, b, c, d, e, 0);
  7138. R0(e, a, b, c, d, 1);
  7139. R0(d, e, a, b, c, 2);
  7140. R0(c, d, e, a, b, 3);
  7141. R0(b, c, d, e, a, 4);
  7142. R0(a, b, c, d, e, 5);
  7143. R0(e, a, b, c, d, 6);
  7144. R0(d, e, a, b, c, 7);
  7145. R0(c, d, e, a, b, 8);
  7146. R0(b, c, d, e, a, 9);
  7147. R0(a, b, c, d, e, 10);
  7148. R0(e, a, b, c, d, 11);
  7149. R0(d, e, a, b, c, 12);
  7150. R0(c, d, e, a, b, 13);
  7151. R0(b, c, d, e, a, 14);
  7152. R0(a, b, c, d, e, 15);
  7153. R1(e, a, b, c, d, 16);
  7154. R1(d, e, a, b, c, 17);
  7155. R1(c, d, e, a, b, 18);
  7156. R1(b, c, d, e, a, 19);
  7157. R2(a, b, c, d, e, 20);
  7158. R2(e, a, b, c, d, 21);
  7159. R2(d, e, a, b, c, 22);
  7160. R2(c, d, e, a, b, 23);
  7161. R2(b, c, d, e, a, 24);
  7162. R2(a, b, c, d, e, 25);
  7163. R2(e, a, b, c, d, 26);
  7164. R2(d, e, a, b, c, 27);
  7165. R2(c, d, e, a, b, 28);
  7166. R2(b, c, d, e, a, 29);
  7167. R2(a, b, c, d, e, 30);
  7168. R2(e, a, b, c, d, 31);
  7169. R2(d, e, a, b, c, 32);
  7170. R2(c, d, e, a, b, 33);
  7171. R2(b, c, d, e, a, 34);
  7172. R2(a, b, c, d, e, 35);
  7173. R2(e, a, b, c, d, 36);
  7174. R2(d, e, a, b, c, 37);
  7175. R2(c, d, e, a, b, 38);
  7176. R2(b, c, d, e, a, 39);
  7177. R3(a, b, c, d, e, 40);
  7178. R3(e, a, b, c, d, 41);
  7179. R3(d, e, a, b, c, 42);
  7180. R3(c, d, e, a, b, 43);
  7181. R3(b, c, d, e, a, 44);
  7182. R3(a, b, c, d, e, 45);
  7183. R3(e, a, b, c, d, 46);
  7184. R3(d, e, a, b, c, 47);
  7185. R3(c, d, e, a, b, 48);
  7186. R3(b, c, d, e, a, 49);
  7187. R3(a, b, c, d, e, 50);
  7188. R3(e, a, b, c, d, 51);
  7189. R3(d, e, a, b, c, 52);
  7190. R3(c, d, e, a, b, 53);
  7191. R3(b, c, d, e, a, 54);
  7192. R3(a, b, c, d, e, 55);
  7193. R3(e, a, b, c, d, 56);
  7194. R3(d, e, a, b, c, 57);
  7195. R3(c, d, e, a, b, 58);
  7196. R3(b, c, d, e, a, 59);
  7197. R4(a, b, c, d, e, 60);
  7198. R4(e, a, b, c, d, 61);
  7199. R4(d, e, a, b, c, 62);
  7200. R4(c, d, e, a, b, 63);
  7201. R4(b, c, d, e, a, 64);
  7202. R4(a, b, c, d, e, 65);
  7203. R4(e, a, b, c, d, 66);
  7204. R4(d, e, a, b, c, 67);
  7205. R4(c, d, e, a, b, 68);
  7206. R4(b, c, d, e, a, 69);
  7207. R4(a, b, c, d, e, 70);
  7208. R4(e, a, b, c, d, 71);
  7209. R4(d, e, a, b, c, 72);
  7210. R4(c, d, e, a, b, 73);
  7211. R4(b, c, d, e, a, 74);
  7212. R4(a, b, c, d, e, 75);
  7213. R4(e, a, b, c, d, 76);
  7214. R4(d, e, a, b, c, 77);
  7215. R4(c, d, e, a, b, 78);
  7216. R4(b, c, d, e, a, 79);
  7217. state[0] += a;
  7218. state[1] += b;
  7219. state[2] += c;
  7220. state[3] += d;
  7221. state[4] += e;
  7222. a = b = c = d = e = 0;
  7223. memset(block, '\0', sizeof(block));
  7224. }
  7225. static void
  7226. SHA1Init(SHA1_CTX *context)
  7227. {
  7228. context->state[0] = 0x67452301;
  7229. context->state[1] = 0xEFCDAB89;
  7230. context->state[2] = 0x98BADCFE;
  7231. context->state[3] = 0x10325476;
  7232. context->state[4] = 0xC3D2E1F0;
  7233. context->count[0] = context->count[1] = 0;
  7234. }
  7235. static void
  7236. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7237. {
  7238. uint32_t i, j;
  7239. j = context->count[0];
  7240. if ((context->count[0] += len << 3) < j) {
  7241. context->count[1]++;
  7242. }
  7243. context->count[1] += (len >> 29);
  7244. j = (j >> 3) & 63;
  7245. if ((j + len) > 63) {
  7246. memcpy(&context->buffer[j], data, (i = 64 - j));
  7247. SHA1Transform(context->state, context->buffer);
  7248. for (; i + 63 < len; i += 64) {
  7249. SHA1Transform(context->state, &data[i]);
  7250. }
  7251. j = 0;
  7252. } else
  7253. i = 0;
  7254. memcpy(&context->buffer[j], &data[i], len - i);
  7255. }
  7256. static void
  7257. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7258. {
  7259. unsigned i;
  7260. unsigned char finalcount[8], c;
  7261. for (i = 0; i < 8; i++) {
  7262. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7263. >> ((3 - (i & 3)) * 8)) & 255);
  7264. }
  7265. c = 0200;
  7266. SHA1Update(context, &c, 1);
  7267. while ((context->count[0] & 504) != 448) {
  7268. c = 0000;
  7269. SHA1Update(context, &c, 1);
  7270. }
  7271. SHA1Update(context, finalcount, 8);
  7272. for (i = 0; i < 20; i++) {
  7273. digest[i] = (unsigned char)((context->state[i >> 2]
  7274. >> ((3 - (i & 3)) * 8)) & 255);
  7275. }
  7276. memset(context, '\0', sizeof(*context));
  7277. memset(&finalcount, '\0', sizeof(finalcount));
  7278. }
  7279. /* END OF SHA1 CODE */
  7280. static int
  7281. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7282. {
  7283. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7284. const char *protocol = NULL;
  7285. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7286. SHA1_CTX sha_ctx;
  7287. int truncated;
  7288. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7289. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7290. if (truncated) {
  7291. conn->must_close = 1;
  7292. return 0;
  7293. }
  7294. SHA1Init(&sha_ctx);
  7295. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7296. SHA1Final((unsigned char *)sha, &sha_ctx);
  7297. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7298. mg_printf(conn,
  7299. "HTTP/1.1 101 Switching Protocols\r\n"
  7300. "Upgrade: websocket\r\n"
  7301. "Connection: Upgrade\r\n"
  7302. "Sec-WebSocket-Accept: %s\r\n",
  7303. b64_sha);
  7304. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7305. if (protocol) {
  7306. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7307. } else {
  7308. mg_printf(conn, "%s", "\r\n");
  7309. }
  7310. return 1;
  7311. }
  7312. static void
  7313. read_websocket(struct mg_connection *conn,
  7314. mg_websocket_data_handler ws_data_handler,
  7315. void *callback_data)
  7316. {
  7317. /* Pointer to the beginning of the portion of the incoming websocket
  7318. * message queue.
  7319. * The original websocket upgrade request is never removed, so the queue
  7320. * begins after it. */
  7321. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7322. int n, error, exit_by_callback;
  7323. /* body_len is the length of the entire queue in bytes
  7324. * len is the length of the current message
  7325. * data_len is the length of the current message's data payload
  7326. * header_len is the length of the current message's header */
  7327. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7328. /* "The masking key is a 32-bit value chosen at random by the client."
  7329. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7330. */
  7331. unsigned char mask[4];
  7332. /* data points to the place where the message is stored when passed to the
  7333. * websocket_data callback. This is either mem on the stack, or a
  7334. * dynamically allocated buffer if it is too large. */
  7335. char mem[4096];
  7336. char *data = mem;
  7337. unsigned char mop; /* mask flag and opcode */
  7338. double timeout = -1.0;
  7339. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7340. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7341. }
  7342. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7343. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7344. }
  7345. mg_set_thread_name("wsock");
  7346. /* Loop continuously, reading messages from the socket, invoking the
  7347. * callback, and waiting repeatedly until an error occurs. */
  7348. while (!conn->ctx->stop_flag) {
  7349. header_len = 0;
  7350. assert(conn->data_len >= conn->request_len);
  7351. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7352. len = buf[1] & 127;
  7353. mask_len = buf[1] & 128 ? 4 : 0;
  7354. if (len < 126 && body_len >= mask_len) {
  7355. data_len = len;
  7356. header_len = 2 + mask_len;
  7357. } else if (len == 126 && body_len >= 4 + mask_len) {
  7358. header_len = 4 + mask_len;
  7359. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7360. } else if (body_len >= 10 + mask_len) {
  7361. header_len = 10 + mask_len;
  7362. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7363. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7364. }
  7365. }
  7366. if (header_len > 0 && body_len >= header_len) {
  7367. /* Allocate space to hold websocket payload */
  7368. data = mem;
  7369. if (data_len > sizeof(mem)) {
  7370. data = (char *)mg_malloc(data_len);
  7371. if (data == NULL) {
  7372. /* Allocation failed, exit the loop and then close the
  7373. * connection */
  7374. mg_cry(conn, "websocket out of memory; closing connection");
  7375. break;
  7376. }
  7377. }
  7378. /* Copy the mask before we shift the queue and destroy it */
  7379. if (mask_len > 0) {
  7380. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7381. } else {
  7382. memset(mask, 0, sizeof(mask));
  7383. }
  7384. /* Read frame payload from the first message in the queue into
  7385. * data and advance the queue by moving the memory in place. */
  7386. assert(body_len >= header_len);
  7387. if (data_len + header_len > body_len) {
  7388. mop = buf[0]; /* current mask and opcode */
  7389. /* Overflow case */
  7390. len = body_len - header_len;
  7391. memcpy(data, buf + header_len, len);
  7392. error = 0;
  7393. while (len < data_len) {
  7394. n = pull(
  7395. NULL, conn, data + len, (int)(data_len - len), timeout);
  7396. if (n <= 0) {
  7397. error = 1;
  7398. break;
  7399. }
  7400. len += (size_t)n;
  7401. }
  7402. if (error) {
  7403. mg_cry(conn, "Websocket pull failed; closing connection");
  7404. break;
  7405. }
  7406. conn->data_len = conn->request_len;
  7407. } else {
  7408. mop = buf[0]; /* current mask and opcode, overwritten by
  7409. * memmove() */
  7410. /* Length of the message being read at the front of the
  7411. * queue */
  7412. len = data_len + header_len;
  7413. /* Copy the data payload into the data pointer for the
  7414. * callback */
  7415. memcpy(data, buf + header_len, data_len);
  7416. /* Move the queue forward len bytes */
  7417. memmove(buf, buf + len, body_len - len);
  7418. /* Mark the queue as advanced */
  7419. conn->data_len -= (int)len;
  7420. }
  7421. /* Apply mask if necessary */
  7422. if (mask_len > 0) {
  7423. for (i = 0; i < data_len; ++i) {
  7424. data[i] ^= mask[i & 3];
  7425. }
  7426. }
  7427. /* Exit the loop if callback signals to exit (server side),
  7428. * or "connection close" opcode received (client side). */
  7429. exit_by_callback = 0;
  7430. if ((ws_data_handler != NULL)
  7431. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7432. exit_by_callback = 1;
  7433. }
  7434. if (data != mem) {
  7435. mg_free(data);
  7436. }
  7437. if (exit_by_callback
  7438. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7439. /* Opcode == 8, connection close */
  7440. break;
  7441. }
  7442. /* Not breaking the loop, process next websocket frame. */
  7443. } else {
  7444. /* Read from the socket into the next available location in the
  7445. * message queue. */
  7446. if ((n = pull(NULL,
  7447. conn,
  7448. conn->buf + conn->data_len,
  7449. conn->buf_size - conn->data_len,
  7450. timeout)) <= 0) {
  7451. /* Error, no bytes read */
  7452. break;
  7453. }
  7454. conn->data_len += n;
  7455. }
  7456. }
  7457. mg_set_thread_name("worker");
  7458. }
  7459. static int
  7460. mg_websocket_write_exec(struct mg_connection *conn,
  7461. int opcode,
  7462. const char *data,
  7463. size_t dataLen,
  7464. uint32_t masking_key)
  7465. {
  7466. unsigned char header[14];
  7467. size_t headerLen = 1;
  7468. int retval = -1;
  7469. header[0] = 0x80 + (opcode & 0xF);
  7470. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7471. if (dataLen < 126) {
  7472. /* inline 7-bit length field */
  7473. header[1] = (unsigned char)dataLen;
  7474. headerLen = 2;
  7475. } else if (dataLen <= 0xFFFF) {
  7476. /* 16-bit length field */
  7477. header[1] = 126;
  7478. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7479. headerLen = 4;
  7480. } else {
  7481. /* 64-bit length field */
  7482. header[1] = 127;
  7483. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7484. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7485. headerLen = 10;
  7486. }
  7487. if (masking_key) {
  7488. /* add mask */
  7489. header[1] |= 0x80;
  7490. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7491. headerLen += 4;
  7492. }
  7493. /* Note that POSIX/Winsock's send() is threadsafe
  7494. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7495. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7496. * push(), although that is only a problem if the packet is large or
  7497. * outgoing buffer is full). */
  7498. (void)mg_lock_connection(conn);
  7499. retval = mg_write(conn, header, headerLen);
  7500. if (dataLen > 0) {
  7501. retval = mg_write(conn, data, dataLen);
  7502. }
  7503. mg_unlock_connection(conn);
  7504. return retval;
  7505. }
  7506. int
  7507. mg_websocket_write(struct mg_connection *conn,
  7508. int opcode,
  7509. const char *data,
  7510. size_t dataLen)
  7511. {
  7512. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7513. }
  7514. static void
  7515. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7516. {
  7517. size_t i = 0;
  7518. i = 0;
  7519. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7520. /* Convert in 32 bit words, if data is 4 byte aligned */
  7521. while (i < (in_len - 3)) {
  7522. *(uint32_t *)(void *)(out + i) =
  7523. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7524. i += 4;
  7525. }
  7526. }
  7527. if (i != in_len) {
  7528. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7529. while (i < in_len) {
  7530. *(uint8_t *)(void *)(out + i) =
  7531. *(uint8_t *)(void *)(in + i)
  7532. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7533. i++;
  7534. }
  7535. }
  7536. }
  7537. int
  7538. mg_websocket_client_write(struct mg_connection *conn,
  7539. int opcode,
  7540. const char *data,
  7541. size_t dataLen)
  7542. {
  7543. int retval = -1;
  7544. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7545. uint32_t masking_key = (uint32_t)get_random();
  7546. if (masked_data == NULL) {
  7547. /* Return -1 in an error case */
  7548. mg_cry(conn,
  7549. "Cannot allocate buffer for masked websocket response: "
  7550. "Out of memory");
  7551. return -1;
  7552. }
  7553. mask_data(data, dataLen, masking_key, masked_data);
  7554. retval = mg_websocket_write_exec(
  7555. conn, opcode, masked_data, dataLen, masking_key);
  7556. mg_free(masked_data);
  7557. return retval;
  7558. }
  7559. static void
  7560. handle_websocket_request(struct mg_connection *conn,
  7561. const char *path,
  7562. int is_callback_resource,
  7563. mg_websocket_connect_handler ws_connect_handler,
  7564. mg_websocket_ready_handler ws_ready_handler,
  7565. mg_websocket_data_handler ws_data_handler,
  7566. mg_websocket_close_handler ws_close_handler,
  7567. void *cbData)
  7568. {
  7569. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7570. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7571. int lua_websock = 0;
  7572. #if !defined(USE_LUA)
  7573. (void)path;
  7574. #endif
  7575. /* Step 1: Check websocket protocol version. */
  7576. /* Step 1.1: Check Sec-WebSocket-Key. */
  7577. if (!websock_key) {
  7578. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7579. * requires a Sec-WebSocket-Key header.
  7580. */
  7581. /* It could be the hixie draft version
  7582. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7583. */
  7584. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7585. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7586. char key3[8];
  7587. if ((key1 != NULL) && (key2 != NULL)) {
  7588. /* This version uses 8 byte body data in a GET request */
  7589. conn->content_len = 8;
  7590. if (8 == mg_read(conn, key3, 8)) {
  7591. /* This is the hixie version */
  7592. send_http_error(conn,
  7593. 426,
  7594. "%s",
  7595. "Protocol upgrade to RFC 6455 required");
  7596. return;
  7597. }
  7598. }
  7599. /* This is an unknown version */
  7600. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7601. return;
  7602. }
  7603. /* Step 1.2: Check websocket protocol version. */
  7604. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7605. if (version == NULL || strcmp(version, "13") != 0) {
  7606. /* Reject wrong versions */
  7607. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7608. return;
  7609. }
  7610. /* Step 1.3: Could check for "Host", but we do not really nead this
  7611. * value for anything, so just ignore it. */
  7612. /* Step 2: If a callback is responsible, call it. */
  7613. if (is_callback_resource) {
  7614. if (ws_connect_handler != NULL
  7615. && ws_connect_handler(conn, cbData) != 0) {
  7616. /* C callback has returned non-zero, do not proceed with
  7617. * handshake.
  7618. */
  7619. /* Note that C callbacks are no longer called when Lua is
  7620. * responsible, so C can no longer filter callbacks for Lua. */
  7621. return;
  7622. }
  7623. }
  7624. #if defined(USE_LUA)
  7625. /* Step 3: No callback. Check if Lua is responsible. */
  7626. else {
  7627. /* Step 3.1: Check if Lua is responsible. */
  7628. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7629. lua_websock =
  7630. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7631. strlen(
  7632. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7633. path);
  7634. }
  7635. if (lua_websock) {
  7636. /* Step 3.2: Lua is responsible: call it. */
  7637. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7638. if (!conn->lua_websocket_state) {
  7639. /* Lua rejected the new client */
  7640. return;
  7641. }
  7642. }
  7643. }
  7644. #endif
  7645. /* Step 4: Check if there is a responsible websocket handler. */
  7646. if (!is_callback_resource && !lua_websock) {
  7647. /* There is no callback, an Lua is not responsible either. */
  7648. /* Reply with a 404 Not Found or with nothing at all?
  7649. * TODO (mid): check the websocket standards, how to reply to
  7650. * requests to invalid websocket addresses. */
  7651. send_http_error(conn, 404, "%s", "Not found");
  7652. return;
  7653. }
  7654. /* Step 5: The websocket connection has been accepted */
  7655. if (!send_websocket_handshake(conn, websock_key)) {
  7656. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7657. return;
  7658. }
  7659. /* Step 6: Call the ready handler */
  7660. if (is_callback_resource) {
  7661. if (ws_ready_handler != NULL) {
  7662. ws_ready_handler(conn, cbData);
  7663. }
  7664. #if defined(USE_LUA)
  7665. } else if (lua_websock) {
  7666. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7667. /* the ready handler returned false */
  7668. return;
  7669. }
  7670. #endif
  7671. }
  7672. /* Step 7: Enter the read loop */
  7673. if (is_callback_resource) {
  7674. read_websocket(conn, ws_data_handler, cbData);
  7675. #if defined(USE_LUA)
  7676. } else if (lua_websock) {
  7677. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7678. #endif
  7679. }
  7680. /* Step 8: Call the close handler */
  7681. if (ws_close_handler) {
  7682. ws_close_handler(conn, cbData);
  7683. }
  7684. }
  7685. static int
  7686. is_websocket_protocol(const struct mg_connection *conn)
  7687. {
  7688. const char *upgrade, *connection;
  7689. /* A websocket protocoll has the following HTTP headers:
  7690. *
  7691. * Connection: Upgrade
  7692. * Upgrade: Websocket
  7693. */
  7694. upgrade = mg_get_header(conn, "Upgrade");
  7695. if (upgrade == NULL) {
  7696. return 0; /* fail early, don't waste time checking other header
  7697. * fields
  7698. */
  7699. }
  7700. if (!mg_strcasestr(upgrade, "websocket")) {
  7701. return 0;
  7702. }
  7703. connection = mg_get_header(conn, "Connection");
  7704. if (connection == NULL) {
  7705. return 0;
  7706. }
  7707. if (!mg_strcasestr(connection, "upgrade")) {
  7708. return 0;
  7709. }
  7710. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7711. * "Sec-WebSocket-Version" are also required.
  7712. * Don't check them here, since even an unsupported websocket protocol
  7713. * request still IS a websocket request (in contrast to a standard HTTP
  7714. * request). It will fail later in handle_websocket_request.
  7715. */
  7716. return 1;
  7717. }
  7718. #endif /* !USE_WEBSOCKET */
  7719. static int
  7720. isbyte(int n)
  7721. {
  7722. return n >= 0 && n <= 255;
  7723. }
  7724. static int
  7725. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7726. {
  7727. int n, a, b, c, d, slash = 32, len = 0;
  7728. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7729. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7730. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7731. && slash < 33) {
  7732. len = n;
  7733. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7734. | (uint32_t)d;
  7735. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7736. }
  7737. return len;
  7738. }
  7739. static int
  7740. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7741. {
  7742. int throttle = 0;
  7743. struct vec vec, val;
  7744. uint32_t net, mask;
  7745. char mult;
  7746. double v;
  7747. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7748. mult = ',';
  7749. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7750. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7751. && mult != ',')) {
  7752. continue;
  7753. }
  7754. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7755. : 1;
  7756. if (vec.len == 1 && vec.ptr[0] == '*') {
  7757. throttle = (int)v;
  7758. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7759. if ((remote_ip & mask) == net) {
  7760. throttle = (int)v;
  7761. }
  7762. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7763. throttle = (int)v;
  7764. }
  7765. }
  7766. return throttle;
  7767. }
  7768. static uint32_t
  7769. get_remote_ip(const struct mg_connection *conn)
  7770. {
  7771. if (!conn) {
  7772. return 0;
  7773. }
  7774. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7775. }
  7776. /* Experimental replacement for mg_upload. */
  7777. #include "handle_form.inl"
  7778. /* Replacement for mg_upload (Note: mg_upload is deprecated) */
  7779. struct mg_upload_user_data {
  7780. struct mg_connection *conn;
  7781. const char *destination_dir;
  7782. int num_uploaded_files;
  7783. };
  7784. /* Helper function for deprecated mg_upload. */
  7785. static int
  7786. mg_upload_field_found(const char *key,
  7787. const char *filename,
  7788. char *path,
  7789. size_t pathlen,
  7790. void *user_data)
  7791. {
  7792. int truncated = 0;
  7793. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7794. (void)key;
  7795. if (!filename) {
  7796. mg_cry(fud->conn, "%s: No filename set", __func__);
  7797. return FORM_FIELD_STORAGE_ABORT;
  7798. }
  7799. mg_snprintf(fud->conn,
  7800. &truncated,
  7801. path,
  7802. pathlen - 1,
  7803. "%s/%s",
  7804. fud->destination_dir,
  7805. filename);
  7806. if (!truncated) {
  7807. mg_cry(fud->conn, "%s: File path too long", __func__);
  7808. return FORM_FIELD_STORAGE_ABORT;
  7809. }
  7810. return FORM_FIELD_STORAGE_STORE;
  7811. }
  7812. /* Helper function for deprecated mg_upload. */
  7813. static int
  7814. mg_upload_field_get(const char *key,
  7815. const char *value,
  7816. size_t value_size,
  7817. void *user_data)
  7818. {
  7819. /* Function should never be called */
  7820. (void)key;
  7821. (void)value;
  7822. (void)value_size;
  7823. (void)user_data;
  7824. return 0;
  7825. }
  7826. /* Helper function for deprecated mg_upload. */
  7827. static int
  7828. mg_upload_field_stored(const char *path, size_t file_size, void *user_data)
  7829. {
  7830. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7831. (void)file_size;
  7832. fud->num_uploaded_files++;
  7833. fud->conn->ctx->callbacks.upload(fud->conn, path);
  7834. return 0;
  7835. }
  7836. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  7837. int
  7838. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7839. {
  7840. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  7841. struct mg_form_data_handler fdh = {mg_upload_field_found,
  7842. mg_upload_field_get,
  7843. mg_upload_field_stored,
  7844. 0};
  7845. int ret;
  7846. fdh.user_data = (void *)&fud;
  7847. ret = mg_handle_form_request(conn, &fdh);
  7848. if (ret < 0) {
  7849. mg_cry(conn, "%s: Error while parsing the request", __func__);
  7850. }
  7851. return fud.num_uploaded_files;
  7852. }
  7853. static int
  7854. get_first_ssl_listener_index(const struct mg_context *ctx)
  7855. {
  7856. unsigned int i;
  7857. int idx = -1;
  7858. if (ctx) {
  7859. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7860. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7861. }
  7862. }
  7863. return idx;
  7864. }
  7865. static void
  7866. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7867. {
  7868. char host[1025];
  7869. const char *host_header;
  7870. size_t hostlen;
  7871. host_header = mg_get_header(conn, "Host");
  7872. hostlen = sizeof(host);
  7873. if (host_header != NULL) {
  7874. char *pos;
  7875. mg_strlcpy(host, host_header, hostlen);
  7876. host[hostlen - 1] = '\0';
  7877. pos = strchr(host, ':');
  7878. if (pos != NULL) {
  7879. *pos = '\0';
  7880. }
  7881. } else {
  7882. /* Cannot get host from the Host: header.
  7883. * Fallback to our IP address. */
  7884. if (conn) {
  7885. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7886. }
  7887. }
  7888. /* Send host, port, uri and (if it exists) ?query_string */
  7889. if (conn) {
  7890. mg_printf(conn,
  7891. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7892. host,
  7893. (int)ntohs(
  7894. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7895. conn->request_info.local_uri,
  7896. (conn->request_info.query_string == NULL) ? "" : "?",
  7897. (conn->request_info.query_string == NULL)
  7898. ? ""
  7899. : conn->request_info.query_string);
  7900. }
  7901. }
  7902. static void
  7903. mg_set_handler_type(struct mg_context *ctx,
  7904. const char *uri,
  7905. int handler_type,
  7906. int is_delete_request,
  7907. mg_request_handler handler,
  7908. mg_websocket_connect_handler connect_handler,
  7909. mg_websocket_ready_handler ready_handler,
  7910. mg_websocket_data_handler data_handler,
  7911. mg_websocket_close_handler close_handler,
  7912. mg_authorization_handler auth_handler,
  7913. void *cbdata)
  7914. {
  7915. struct mg_handler_info *tmp_rh, **lastref;
  7916. size_t urilen = strlen(uri);
  7917. if (handler_type == WEBSOCKET_HANDLER) {
  7918. /* assert(handler == NULL); */
  7919. /* assert(is_delete_request || connect_handler!=NULL ||
  7920. * ready_handler!=NULL || data_handler!=NULL ||
  7921. * close_handler!=NULL);
  7922. */
  7923. /* assert(auth_handler == NULL); */
  7924. if (handler != NULL) {
  7925. return;
  7926. }
  7927. if (!is_delete_request && connect_handler == NULL
  7928. && ready_handler == NULL
  7929. && data_handler == NULL
  7930. && close_handler == NULL) {
  7931. return;
  7932. }
  7933. if (auth_handler != NULL) {
  7934. return;
  7935. }
  7936. } else if (handler_type == REQUEST_HANDLER) {
  7937. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7938. * data_handler==NULL && close_handler==NULL); */
  7939. /* assert(is_delete_request || (handler!=NULL));
  7940. */
  7941. /* assert(auth_handler == NULL); */
  7942. if (connect_handler != NULL || ready_handler != NULL
  7943. || data_handler != NULL
  7944. || close_handler != NULL) {
  7945. return;
  7946. }
  7947. if (!is_delete_request && (handler == NULL)) {
  7948. return;
  7949. }
  7950. if (auth_handler != NULL) {
  7951. return;
  7952. }
  7953. } else { /* AUTH_HANDLER */
  7954. /* assert(handler == NULL); */
  7955. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7956. * data_handler==NULL && close_handler==NULL); */
  7957. /* assert(auth_handler != NULL); */
  7958. if (handler != NULL) {
  7959. return;
  7960. }
  7961. if (connect_handler != NULL || ready_handler != NULL
  7962. || data_handler != NULL
  7963. || close_handler != NULL) {
  7964. return;
  7965. }
  7966. if (!is_delete_request && (auth_handler == NULL)) {
  7967. return;
  7968. }
  7969. }
  7970. if (!ctx) {
  7971. return;
  7972. }
  7973. mg_lock_context(ctx);
  7974. /* first try to find an existing handler */
  7975. lastref = &(ctx->handlers);
  7976. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  7977. if (tmp_rh->handler_type == handler_type) {
  7978. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7979. if (!is_delete_request) {
  7980. /* update existing handler */
  7981. if (handler_type == REQUEST_HANDLER) {
  7982. tmp_rh->handler = handler;
  7983. } else if (handler_type == WEBSOCKET_HANDLER) {
  7984. tmp_rh->connect_handler = connect_handler;
  7985. tmp_rh->ready_handler = ready_handler;
  7986. tmp_rh->data_handler = data_handler;
  7987. tmp_rh->close_handler = close_handler;
  7988. } else { /* AUTH_HANDLER */
  7989. tmp_rh->auth_handler = auth_handler;
  7990. }
  7991. tmp_rh->cbdata = cbdata;
  7992. } else {
  7993. /* remove existing handler */
  7994. *lastref = tmp_rh->next;
  7995. mg_free(tmp_rh->uri);
  7996. mg_free(tmp_rh);
  7997. }
  7998. mg_unlock_context(ctx);
  7999. return;
  8000. }
  8001. }
  8002. lastref = &(tmp_rh->next);
  8003. }
  8004. if (is_delete_request) {
  8005. /* no handler to set, this was a remove request to a non-existing
  8006. * handler */
  8007. mg_unlock_context(ctx);
  8008. return;
  8009. }
  8010. tmp_rh =
  8011. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8012. if (tmp_rh == NULL) {
  8013. mg_unlock_context(ctx);
  8014. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8015. return;
  8016. }
  8017. tmp_rh->uri = mg_strdup(uri);
  8018. if (!tmp_rh->uri) {
  8019. mg_unlock_context(ctx);
  8020. mg_free(tmp_rh);
  8021. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8022. return;
  8023. }
  8024. tmp_rh->uri_len = urilen;
  8025. if (handler_type == REQUEST_HANDLER) {
  8026. tmp_rh->handler = handler;
  8027. } else if (handler_type == WEBSOCKET_HANDLER) {
  8028. tmp_rh->connect_handler = connect_handler;
  8029. tmp_rh->ready_handler = ready_handler;
  8030. tmp_rh->data_handler = data_handler;
  8031. tmp_rh->close_handler = close_handler;
  8032. } else { /* AUTH_HANDLER */
  8033. tmp_rh->auth_handler = auth_handler;
  8034. }
  8035. tmp_rh->cbdata = cbdata;
  8036. tmp_rh->handler_type = handler_type;
  8037. tmp_rh->next = NULL;
  8038. *lastref = tmp_rh;
  8039. mg_unlock_context(ctx);
  8040. }
  8041. void
  8042. mg_set_request_handler(struct mg_context *ctx,
  8043. const char *uri,
  8044. mg_request_handler handler,
  8045. void *cbdata)
  8046. {
  8047. mg_set_handler_type(ctx,
  8048. uri,
  8049. REQUEST_HANDLER,
  8050. handler == NULL,
  8051. handler,
  8052. NULL,
  8053. NULL,
  8054. NULL,
  8055. NULL,
  8056. NULL,
  8057. cbdata);
  8058. }
  8059. void
  8060. mg_set_websocket_handler(struct mg_context *ctx,
  8061. const char *uri,
  8062. mg_websocket_connect_handler connect_handler,
  8063. mg_websocket_ready_handler ready_handler,
  8064. mg_websocket_data_handler data_handler,
  8065. mg_websocket_close_handler close_handler,
  8066. void *cbdata)
  8067. {
  8068. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8069. && (data_handler == NULL)
  8070. && (close_handler == NULL);
  8071. mg_set_handler_type(ctx,
  8072. uri,
  8073. WEBSOCKET_HANDLER,
  8074. is_delete_request,
  8075. NULL,
  8076. connect_handler,
  8077. ready_handler,
  8078. data_handler,
  8079. close_handler,
  8080. NULL,
  8081. cbdata);
  8082. }
  8083. void
  8084. mg_set_auth_handler(struct mg_context *ctx,
  8085. const char *uri,
  8086. mg_request_handler handler,
  8087. void *cbdata)
  8088. {
  8089. mg_set_handler_type(ctx,
  8090. uri,
  8091. AUTH_HANDLER,
  8092. handler == NULL,
  8093. NULL,
  8094. NULL,
  8095. NULL,
  8096. NULL,
  8097. NULL,
  8098. handler,
  8099. cbdata);
  8100. }
  8101. static int
  8102. get_request_handler(struct mg_connection *conn,
  8103. int handler_type,
  8104. mg_request_handler *handler,
  8105. mg_websocket_connect_handler *connect_handler,
  8106. mg_websocket_ready_handler *ready_handler,
  8107. mg_websocket_data_handler *data_handler,
  8108. mg_websocket_close_handler *close_handler,
  8109. mg_authorization_handler *auth_handler,
  8110. void **cbdata)
  8111. {
  8112. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8113. if (request_info) {
  8114. const char *uri = request_info->local_uri;
  8115. size_t urilen = strlen(uri);
  8116. struct mg_handler_info *tmp_rh;
  8117. if (!conn || !conn->ctx) {
  8118. return 0;
  8119. }
  8120. mg_lock_context(conn->ctx);
  8121. /* first try for an exact match */
  8122. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8123. tmp_rh = tmp_rh->next) {
  8124. if (tmp_rh->handler_type == handler_type) {
  8125. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8126. if (handler_type == WEBSOCKET_HANDLER) {
  8127. *connect_handler = tmp_rh->connect_handler;
  8128. *ready_handler = tmp_rh->ready_handler;
  8129. *data_handler = tmp_rh->data_handler;
  8130. *close_handler = tmp_rh->close_handler;
  8131. } else if (handler_type == REQUEST_HANDLER) {
  8132. *handler = tmp_rh->handler;
  8133. } else { /* AUTH_HANDLER */
  8134. *auth_handler = tmp_rh->auth_handler;
  8135. }
  8136. *cbdata = tmp_rh->cbdata;
  8137. mg_unlock_context(conn->ctx);
  8138. return 1;
  8139. }
  8140. }
  8141. }
  8142. /* next try for a partial match, we will accept uri/something */
  8143. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8144. tmp_rh = tmp_rh->next) {
  8145. if (tmp_rh->handler_type == handler_type) {
  8146. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8147. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8148. if (handler_type == WEBSOCKET_HANDLER) {
  8149. *connect_handler = tmp_rh->connect_handler;
  8150. *ready_handler = tmp_rh->ready_handler;
  8151. *data_handler = tmp_rh->data_handler;
  8152. *close_handler = tmp_rh->close_handler;
  8153. } else if (handler_type == REQUEST_HANDLER) {
  8154. *handler = tmp_rh->handler;
  8155. } else { /* AUTH_HANDLER */
  8156. *auth_handler = tmp_rh->auth_handler;
  8157. }
  8158. *cbdata = tmp_rh->cbdata;
  8159. mg_unlock_context(conn->ctx);
  8160. return 1;
  8161. }
  8162. }
  8163. }
  8164. /* finally try for pattern match */
  8165. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8166. tmp_rh = tmp_rh->next) {
  8167. if (tmp_rh->handler_type == handler_type) {
  8168. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8169. if (handler_type == WEBSOCKET_HANDLER) {
  8170. *connect_handler = tmp_rh->connect_handler;
  8171. *ready_handler = tmp_rh->ready_handler;
  8172. *data_handler = tmp_rh->data_handler;
  8173. *close_handler = tmp_rh->close_handler;
  8174. } else if (handler_type == REQUEST_HANDLER) {
  8175. *handler = tmp_rh->handler;
  8176. } else { /* AUTH_HANDLER */
  8177. *auth_handler = tmp_rh->auth_handler;
  8178. }
  8179. *cbdata = tmp_rh->cbdata;
  8180. mg_unlock_context(conn->ctx);
  8181. return 1;
  8182. }
  8183. }
  8184. }
  8185. mg_unlock_context(conn->ctx);
  8186. }
  8187. return 0; /* none found */
  8188. }
  8189. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8190. static int
  8191. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8192. void *cbdata)
  8193. {
  8194. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8195. if (pcallbacks->websocket_connect) {
  8196. return pcallbacks->websocket_connect(conn);
  8197. }
  8198. /* No handler set - assume "OK" */
  8199. return 0;
  8200. }
  8201. static void
  8202. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8203. {
  8204. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8205. if (pcallbacks->websocket_ready) {
  8206. pcallbacks->websocket_ready(conn);
  8207. }
  8208. }
  8209. static int
  8210. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8211. int bits,
  8212. char *data,
  8213. size_t len,
  8214. void *cbdata)
  8215. {
  8216. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8217. if (pcallbacks->websocket_data) {
  8218. return pcallbacks->websocket_data(conn, bits, data, len);
  8219. }
  8220. /* No handler set - assume "OK" */
  8221. return 1;
  8222. }
  8223. #endif
  8224. /* This is the heart of the Civetweb's logic.
  8225. * This function is called when the request is read, parsed and validated,
  8226. * and Civetweb must decide what action to take: serve a file, or
  8227. * a directory, or call embedded function, etcetera. */
  8228. static void
  8229. handle_request(struct mg_connection *conn)
  8230. {
  8231. if (conn) {
  8232. struct mg_request_info *ri = &conn->request_info;
  8233. char path[PATH_MAX];
  8234. int uri_len, ssl_index;
  8235. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8236. is_put_or_delete_request = 0, is_callback_resource = 0;
  8237. int i;
  8238. struct file file = STRUCT_FILE_INITIALIZER;
  8239. mg_request_handler callback_handler = NULL;
  8240. mg_websocket_connect_handler ws_connect_handler = NULL;
  8241. mg_websocket_ready_handler ws_ready_handler = NULL;
  8242. mg_websocket_data_handler ws_data_handler = NULL;
  8243. mg_websocket_close_handler ws_close_handler = NULL;
  8244. void *callback_data = NULL;
  8245. mg_authorization_handler auth_handler = NULL;
  8246. void *auth_callback_data = NULL;
  8247. #if !defined(NO_FILES)
  8248. time_t curtime = time(NULL);
  8249. char date[64];
  8250. #endif
  8251. path[0] = 0;
  8252. if (!ri) {
  8253. return;
  8254. }
  8255. /* 1. get the request url */
  8256. /* 1.1. split into url and query string */
  8257. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8258. != NULL) {
  8259. *((char *)conn->request_info.query_string++) = '\0';
  8260. }
  8261. uri_len = (int)strlen(ri->local_uri);
  8262. /* 1.2. decode url (if config says so) */
  8263. if (should_decode_url(conn)) {
  8264. mg_url_decode(
  8265. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8266. }
  8267. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8268. * not
  8269. * possible */
  8270. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8271. /* step 1. completed, the url is known now */
  8272. DEBUG_TRACE("URL: %s", ri->local_uri);
  8273. /* 2. do a https redirect, if required */
  8274. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8275. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8276. if (ssl_index >= 0) {
  8277. redirect_to_https_port(conn, ssl_index);
  8278. } else {
  8279. /* A http to https forward port has been specified,
  8280. * but no https port to forward to. */
  8281. send_http_error(conn,
  8282. 503,
  8283. "%s",
  8284. "Error: SSL forward not configured properly");
  8285. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8286. }
  8287. return;
  8288. }
  8289. /* 3. if this ip has limited speed, set it for this connection */
  8290. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8291. get_remote_ip(conn),
  8292. ri->local_uri);
  8293. /* 4. call a "handle everything" callback, if registered */
  8294. if (conn->ctx->callbacks.begin_request != NULL) {
  8295. /* Note that since V1.7 the "begin_request" function is called
  8296. * before an authorization check. If an authorization check is
  8297. * required, use a request_handler instead. */
  8298. i = conn->ctx->callbacks.begin_request(conn);
  8299. if (i > 0) {
  8300. /* callback already processed the request. Store the
  8301. return value as a status code for the access log. */
  8302. conn->status_code = i;
  8303. return;
  8304. } else if (i == 0) {
  8305. /* civetweb should process the request */
  8306. } else {
  8307. /* unspecified - may change with the next version */
  8308. return;
  8309. }
  8310. }
  8311. /* request not yet handled by a handler or redirect, so the request
  8312. * is processed here */
  8313. /* 5. interpret the url to find out how the request must be handled
  8314. */
  8315. /* 5.1. first test, if the request targets the regular http(s)://
  8316. * protocol namespace or the websocket ws(s):// protocol namespace.
  8317. */
  8318. is_websocket_request = is_websocket_protocol(conn);
  8319. /* 5.2. check if the request will be handled by a callback */
  8320. if (get_request_handler(conn,
  8321. is_websocket_request ? WEBSOCKET_HANDLER
  8322. : REQUEST_HANDLER,
  8323. &callback_handler,
  8324. &ws_connect_handler,
  8325. &ws_ready_handler,
  8326. &ws_data_handler,
  8327. &ws_close_handler,
  8328. NULL,
  8329. &callback_data)) {
  8330. /* 5.2.1. A callback will handle this request. All requests
  8331. * handled
  8332. * by a callback have to be considered as requests to a script
  8333. * resource. */
  8334. is_callback_resource = 1;
  8335. is_script_resource = 1;
  8336. is_put_or_delete_request = is_put_or_delete_method(conn);
  8337. } else {
  8338. no_callback_resource:
  8339. /* 5.2.2. No callback is responsible for this request. The URI
  8340. * addresses a file based resource (static content or Lua/cgi
  8341. * scripts in the file system). */
  8342. is_callback_resource = 0;
  8343. interpret_uri(conn,
  8344. path,
  8345. sizeof(path),
  8346. &file,
  8347. &is_found,
  8348. &is_script_resource,
  8349. &is_websocket_request,
  8350. &is_put_or_delete_request);
  8351. }
  8352. /* 6. authorization check */
  8353. /* 6.1. a custom authorization handler is installed */
  8354. if (get_request_handler(conn,
  8355. AUTH_HANDLER,
  8356. NULL,
  8357. NULL,
  8358. NULL,
  8359. NULL,
  8360. NULL,
  8361. &auth_handler,
  8362. &auth_callback_data)) {
  8363. if (!auth_handler(conn, auth_callback_data)) {
  8364. return;
  8365. }
  8366. } else if (is_put_or_delete_request && !is_script_resource
  8367. && !is_callback_resource) {
  8368. /* 6.2. this request is a PUT/DELETE to a real file */
  8369. /* 6.2.1. thus, the server must have real files */
  8370. #if defined(NO_FILES)
  8371. if (1) {
  8372. #else
  8373. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8374. #endif
  8375. /* This server does not have any real files, thus the
  8376. * PUT/DELETE methods are not valid. */
  8377. send_http_error(conn,
  8378. 405,
  8379. "%s method not allowed",
  8380. conn->request_info.request_method);
  8381. return;
  8382. }
  8383. #if !defined(NO_FILES)
  8384. /* 6.2.2. Check if put authorization for static files is available.
  8385. */
  8386. if (!is_authorized_for_put(conn)) {
  8387. send_authorization_request(conn);
  8388. return;
  8389. }
  8390. #endif
  8391. } else {
  8392. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8393. * or it is a PUT or DELETE request to a resource that does not
  8394. * correspond to a file. Check authorization. */
  8395. if (!check_authorization(conn, path)) {
  8396. send_authorization_request(conn);
  8397. return;
  8398. }
  8399. }
  8400. /* request is authorized or does not need authorization */
  8401. /* 7. check if there are request handlers for this uri */
  8402. if (is_callback_resource) {
  8403. if (!is_websocket_request) {
  8404. i = callback_handler(conn, callback_data);
  8405. if (i > 0) {
  8406. /* Do nothing, callback has served the request. Store
  8407. * the
  8408. * return value as status code for the log and discard
  8409. * all
  8410. * data from the client not used by the callback. */
  8411. conn->status_code = i;
  8412. discard_unread_request_data(conn);
  8413. } else {
  8414. /* TODO (high): what if the handler did NOT handle the
  8415. * request */
  8416. /* The last version did handle this as a file request,
  8417. * but
  8418. * since a file request is not always a script resource,
  8419. * the authorization check might be different */
  8420. interpret_uri(conn,
  8421. path,
  8422. sizeof(path),
  8423. &file,
  8424. &is_found,
  8425. &is_script_resource,
  8426. &is_websocket_request,
  8427. &is_put_or_delete_request);
  8428. callback_handler = NULL;
  8429. /* TODO (very low): goto is deprecated but for the
  8430. * moment,
  8431. * a goto is simpler than some curious loop. */
  8432. /* The situation "callback does not handle the request"
  8433. * needs to be reconsidered anyway. */
  8434. goto no_callback_resource;
  8435. }
  8436. } else {
  8437. #if defined(USE_WEBSOCKET)
  8438. handle_websocket_request(conn,
  8439. path,
  8440. is_callback_resource,
  8441. ws_connect_handler,
  8442. ws_ready_handler,
  8443. ws_data_handler,
  8444. ws_close_handler,
  8445. callback_data);
  8446. #endif
  8447. }
  8448. return;
  8449. }
  8450. /* 8. handle websocket requests */
  8451. #if defined(USE_WEBSOCKET)
  8452. if (is_websocket_request) {
  8453. if (is_script_resource) {
  8454. /* Websocket Lua script */
  8455. handle_websocket_request(conn,
  8456. path,
  8457. 0 /* Lua Script */,
  8458. NULL,
  8459. NULL,
  8460. NULL,
  8461. NULL,
  8462. &conn->ctx->callbacks);
  8463. } else {
  8464. #if defined(MG_LEGACY_INTERFACE)
  8465. handle_websocket_request(
  8466. conn,
  8467. path,
  8468. !is_script_resource /* could be deprecated global callback */,
  8469. deprecated_websocket_connect_wrapper,
  8470. deprecated_websocket_ready_wrapper,
  8471. deprecated_websocket_data_wrapper,
  8472. NULL,
  8473. &conn->ctx->callbacks);
  8474. #else
  8475. send_http_error(conn, 404, "%s", "Not found");
  8476. #endif
  8477. }
  8478. return;
  8479. } else
  8480. #endif
  8481. #if defined(NO_FILES)
  8482. /* 9a. In case the server uses only callbacks, this uri is
  8483. * unknown.
  8484. * Then, all request handling ends here. */
  8485. send_http_error(conn, 404, "%s", "Not Found");
  8486. #else
  8487. /* 9b. This request is either for a static file or resource handled
  8488. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8489. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8490. send_http_error(conn, 404, "%s", "Not Found");
  8491. return;
  8492. }
  8493. /* 10. File is handled by a script. */
  8494. if (is_script_resource) {
  8495. handle_file_based_request(conn, path, &file);
  8496. return;
  8497. }
  8498. /* 11. Handle put/delete/mkcol requests */
  8499. if (is_put_or_delete_request) {
  8500. /* 11.1. PUT method */
  8501. if (!strcmp(ri->request_method, "PUT")) {
  8502. put_file(conn, path);
  8503. return;
  8504. }
  8505. /* 11.2. DELETE method */
  8506. if (!strcmp(ri->request_method, "DELETE")) {
  8507. delete_file(conn, path);
  8508. return;
  8509. }
  8510. /* 11.3. MKCOL method */
  8511. if (!strcmp(ri->request_method, "MKCOL")) {
  8512. mkcol(conn, path);
  8513. return;
  8514. }
  8515. /* 11.4. PATCH method
  8516. * This method is not supported for static resources,
  8517. * only for scripts (Lua, CGI) and callbacks. */
  8518. send_http_error(conn,
  8519. 405,
  8520. "%s method not allowed",
  8521. conn->request_info.request_method);
  8522. return;
  8523. }
  8524. /* 11. File does not exist, or it was configured that it should be
  8525. * hidden */
  8526. if (!is_found || (must_hide_file(conn, path))) {
  8527. send_http_error(conn, 404, "%s", "Not found");
  8528. return;
  8529. }
  8530. /* 12. Directory uris should end with a slash */
  8531. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8532. gmt_time_string(date, sizeof(date), &curtime);
  8533. mg_printf(conn,
  8534. "HTTP/1.1 301 Moved Permanently\r\n"
  8535. "Location: %s/\r\n"
  8536. "Date: %s\r\n"
  8537. /* "Cache-Control: private\r\n" (= default) */
  8538. "Content-Length: 0\r\n"
  8539. "Connection: %s\r\n\r\n",
  8540. ri->request_uri,
  8541. date,
  8542. suggest_connection_header(conn));
  8543. return;
  8544. }
  8545. /* 13. Handle other methods than GET/HEAD */
  8546. /* 13.1. Handle PROPFIND */
  8547. if (!strcmp(ri->request_method, "PROPFIND")) {
  8548. handle_propfind(conn, path, &file);
  8549. return;
  8550. }
  8551. /* 13.2. Handle OPTIONS for files */
  8552. if (!strcmp(ri->request_method, "OPTIONS")) {
  8553. /* This standard handler is only used for real files.
  8554. * Scripts should support the OPTIONS method themselves, to allow a
  8555. * maximum flexibility.
  8556. * Lua and CGI scripts may fully support CORS this way (including
  8557. * preflights). */
  8558. send_options(conn);
  8559. return;
  8560. }
  8561. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8562. if (0 != strcmp(ri->request_method, "GET")
  8563. && 0 != strcmp(ri->request_method, "HEAD")) {
  8564. send_http_error(conn,
  8565. 405,
  8566. "%s method not allowed",
  8567. conn->request_info.request_method);
  8568. return;
  8569. }
  8570. /* 14. directories */
  8571. if (file.is_directory) {
  8572. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8573. /* 14.1. use a substitute file */
  8574. /* TODO (high): substitute index may be a script resource.
  8575. * define what should be possible in this case. */
  8576. } else {
  8577. /* 14.2. no substitute file */
  8578. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8579. "yes")) {
  8580. handle_directory_request(conn, path);
  8581. } else {
  8582. send_http_error(conn,
  8583. 403,
  8584. "%s",
  8585. "Error: Directory listing denied");
  8586. }
  8587. return;
  8588. }
  8589. }
  8590. handle_file_based_request(conn, path, &file);
  8591. #endif /* !defined(NO_FILES) */
  8592. #if 0
  8593. /* Perform redirect and auth checks before calling begin_request()
  8594. * handler.
  8595. * Otherwise, begin_request() would need to perform auth checks and
  8596. * redirects. */
  8597. #endif
  8598. }
  8599. return;
  8600. }
  8601. static void
  8602. handle_file_based_request(struct mg_connection *conn,
  8603. const char *path,
  8604. struct file *file)
  8605. {
  8606. if (!conn || !conn->ctx) {
  8607. return;
  8608. }
  8609. if (0) {
  8610. #ifdef USE_LUA
  8611. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8612. strlen(
  8613. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8614. path) > 0) {
  8615. /* Lua server page: an SSI like page containing mostly plain html
  8616. * code
  8617. * plus some tags with server generated contents. */
  8618. handle_lsp_request(conn, path, file, NULL);
  8619. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8620. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8621. path) > 0) {
  8622. /* Lua in-server module script: a CGI like script used to generate
  8623. * the
  8624. * entire reply. */
  8625. mg_exec_lua_script(conn, path, NULL);
  8626. #endif
  8627. #if defined(USE_DUKTAPE)
  8628. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8629. strlen(
  8630. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8631. path) > 0) {
  8632. /* Call duktape to generate the page */
  8633. mg_exec_duktape_script(conn, path);
  8634. #endif
  8635. #if !defined(NO_CGI)
  8636. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8637. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8638. path) > 0) {
  8639. /* CGI scripts may support all HTTP methods */
  8640. handle_cgi_request(conn, path);
  8641. #endif /* !NO_CGI */
  8642. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8643. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8644. path) > 0) {
  8645. handle_ssi_file_request(conn, path, file);
  8646. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8647. /* Send 304 "Not Modified" - this must not send any body data */
  8648. send_http_error(conn, 304, "%s", "");
  8649. } else {
  8650. handle_static_file_request(conn, path, file);
  8651. }
  8652. }
  8653. static void
  8654. close_all_listening_sockets(struct mg_context *ctx)
  8655. {
  8656. unsigned int i;
  8657. if (!ctx) {
  8658. return;
  8659. }
  8660. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8661. closesocket(ctx->listening_sockets[i].sock);
  8662. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8663. }
  8664. mg_free(ctx->listening_sockets);
  8665. ctx->listening_sockets = NULL;
  8666. mg_free(ctx->listening_ports);
  8667. ctx->listening_ports = NULL;
  8668. }
  8669. /* Valid listening port specification is: [ip_address:]port[s]
  8670. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8671. * Examples for IPv6: [::]:80, [::1]:80,
  8672. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8673. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8674. static int
  8675. parse_port_string(const struct vec *vec, struct socket *so)
  8676. {
  8677. unsigned int a, b, c, d, port;
  8678. int ch, len;
  8679. #if defined(USE_IPV6)
  8680. char buf[100] = {0};
  8681. #endif
  8682. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8683. * Also, all-zeroes in the socket address means binding to all addresses
  8684. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8685. memset(so, 0, sizeof(*so));
  8686. so->lsa.sin.sin_family = AF_INET;
  8687. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8688. == 5) {
  8689. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8690. so->lsa.sin.sin_addr.s_addr =
  8691. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8692. so->lsa.sin.sin_port = htons((uint16_t)port);
  8693. #if defined(USE_IPV6)
  8694. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8695. && mg_inet_pton(
  8696. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8697. /* IPv6 address, examples: see above */
  8698. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8699. */
  8700. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8701. #endif
  8702. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8703. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8704. so->lsa.sin.sin_port = htons((uint16_t)port);
  8705. } else {
  8706. /* Parsing failure. Make port invalid. */
  8707. port = 0;
  8708. len = 0;
  8709. }
  8710. /* sscanf and the option splitting code ensure the following condition
  8711. */
  8712. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8713. return 0;
  8714. }
  8715. ch = vec->ptr[len]; /* Next character after the port number */
  8716. so->is_ssl = (ch == 's');
  8717. so->ssl_redir = (ch == 'r');
  8718. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8719. return is_valid_port(port)
  8720. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8721. }
  8722. static int
  8723. set_ports_option(struct mg_context *ctx)
  8724. {
  8725. const char *list;
  8726. int on = 1;
  8727. #if defined(USE_IPV6)
  8728. int off = 0;
  8729. #endif
  8730. struct vec vec;
  8731. struct socket so, *ptr;
  8732. in_port_t *portPtr;
  8733. union usa usa;
  8734. socklen_t len;
  8735. int portsTotal = 0;
  8736. int portsOk = 0;
  8737. if (!ctx) {
  8738. return 0;
  8739. }
  8740. memset(&so, 0, sizeof(so));
  8741. memset(&usa, 0, sizeof(usa));
  8742. len = sizeof(usa);
  8743. list = ctx->config[LISTENING_PORTS];
  8744. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8745. portsTotal++;
  8746. if (!parse_port_string(&vec, &so)) {
  8747. mg_cry(fc(ctx),
  8748. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8749. (int)vec.len,
  8750. vec.ptr,
  8751. portsTotal,
  8752. "[IP_ADDRESS:]PORT[s|r]");
  8753. continue;
  8754. }
  8755. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8756. mg_cry(fc(ctx),
  8757. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8758. "option set?",
  8759. portsTotal);
  8760. continue;
  8761. }
  8762. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8763. == INVALID_SOCKET) {
  8764. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8765. continue;
  8766. }
  8767. #ifdef _WIN32
  8768. /* Windows SO_REUSEADDR lets many procs binds to a
  8769. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8770. * if someone already has the socket -- DTL */
  8771. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8772. * Windows might need a few seconds before
  8773. * the same port can be used again in the
  8774. * same process, so a short Sleep may be
  8775. * required between mg_stop and mg_start.
  8776. */
  8777. if (setsockopt(so.sock,
  8778. SOL_SOCKET,
  8779. SO_EXCLUSIVEADDRUSE,
  8780. (SOCK_OPT_TYPE)&on,
  8781. sizeof(on)) != 0) {
  8782. mg_cry(fc(ctx),
  8783. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8784. portsTotal);
  8785. }
  8786. #else
  8787. if (setsockopt(so.sock,
  8788. SOL_SOCKET,
  8789. SO_REUSEADDR,
  8790. (SOCK_OPT_TYPE)&on,
  8791. sizeof(on)) != 0) {
  8792. mg_cry(fc(ctx),
  8793. "cannot set socket option SO_REUSEADDR (entry %i)",
  8794. portsTotal);
  8795. }
  8796. #endif
  8797. #if defined(USE_IPV6)
  8798. if (so.lsa.sa.sa_family == AF_INET6
  8799. && setsockopt(so.sock,
  8800. IPPROTO_IPV6,
  8801. IPV6_V6ONLY,
  8802. (void *)&off,
  8803. sizeof(off)) != 0) {
  8804. mg_cry(fc(ctx),
  8805. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8806. portsTotal);
  8807. }
  8808. #endif
  8809. if (so.lsa.sa.sa_family == AF_INET) {
  8810. len = sizeof(so.lsa.sin);
  8811. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8812. mg_cry(fc(ctx),
  8813. "cannot bind to %.*s: %d (%s)",
  8814. (int)vec.len,
  8815. vec.ptr,
  8816. (int)ERRNO,
  8817. strerror(errno));
  8818. closesocket(so.sock);
  8819. so.sock = INVALID_SOCKET;
  8820. continue;
  8821. }
  8822. }
  8823. #if defined(USE_IPV6)
  8824. else if (so.lsa.sa.sa_family == AF_INET6) {
  8825. len = sizeof(so.lsa.sin6);
  8826. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8827. mg_cry(fc(ctx),
  8828. "cannot bind to IPv6 %.*s: %d (%s)",
  8829. (int)vec.len,
  8830. vec.ptr,
  8831. (int)ERRNO,
  8832. strerror(errno));
  8833. closesocket(so.sock);
  8834. so.sock = INVALID_SOCKET;
  8835. continue;
  8836. }
  8837. }
  8838. #endif
  8839. else {
  8840. mg_cry(fc(ctx),
  8841. "cannot bind: address family not supported (entry %i)",
  8842. portsTotal);
  8843. continue;
  8844. }
  8845. if (listen(so.sock, SOMAXCONN) != 0) {
  8846. mg_cry(fc(ctx),
  8847. "cannot listen to %.*s: %d (%s)",
  8848. (int)vec.len,
  8849. vec.ptr,
  8850. (int)ERRNO,
  8851. strerror(errno));
  8852. closesocket(so.sock);
  8853. so.sock = INVALID_SOCKET;
  8854. continue;
  8855. }
  8856. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8857. int err = (int)ERRNO;
  8858. mg_cry(fc(ctx),
  8859. "call to getsockname failed %.*s: %d (%s)",
  8860. (int)vec.len,
  8861. vec.ptr,
  8862. err,
  8863. strerror(errno));
  8864. closesocket(so.sock);
  8865. so.sock = INVALID_SOCKET;
  8866. continue;
  8867. }
  8868. if ((ptr = (struct socket *)
  8869. mg_realloc(ctx->listening_sockets,
  8870. (ctx->num_listening_sockets + 1)
  8871. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8872. mg_cry(fc(ctx), "%s", "Out of memory");
  8873. closesocket(so.sock);
  8874. so.sock = INVALID_SOCKET;
  8875. continue;
  8876. }
  8877. if ((portPtr =
  8878. (in_port_t *)mg_realloc(ctx->listening_ports,
  8879. (ctx->num_listening_sockets + 1)
  8880. * sizeof(ctx->listening_ports[0])))
  8881. == NULL) {
  8882. mg_cry(fc(ctx), "%s", "Out of memory");
  8883. closesocket(so.sock);
  8884. so.sock = INVALID_SOCKET;
  8885. mg_free(ptr);
  8886. continue;
  8887. }
  8888. set_close_on_exec(so.sock, fc(ctx));
  8889. ctx->listening_sockets = ptr;
  8890. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8891. ctx->listening_ports = portPtr;
  8892. ctx->listening_ports[ctx->num_listening_sockets] =
  8893. ntohs(usa.sin.sin_port);
  8894. ctx->num_listening_sockets++;
  8895. portsOk++;
  8896. }
  8897. if (portsOk != portsTotal) {
  8898. close_all_listening_sockets(ctx);
  8899. portsOk = 0;
  8900. }
  8901. return portsOk;
  8902. }
  8903. static const char *
  8904. header_val(const struct mg_connection *conn, const char *header)
  8905. {
  8906. const char *header_value;
  8907. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8908. return "-";
  8909. } else {
  8910. return header_value;
  8911. }
  8912. }
  8913. static void
  8914. log_access(const struct mg_connection *conn)
  8915. {
  8916. const struct mg_request_info *ri;
  8917. struct file fi;
  8918. char date[64], src_addr[IP_ADDR_STR_LEN];
  8919. struct tm *tm;
  8920. const char *referer;
  8921. const char *user_agent;
  8922. char buf[4096];
  8923. if (!conn || !conn->ctx) {
  8924. return;
  8925. }
  8926. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  8927. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  8928. == 0) {
  8929. fi.fp = NULL;
  8930. }
  8931. } else {
  8932. fi.fp = NULL;
  8933. }
  8934. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8935. return;
  8936. }
  8937. tm = localtime(&conn->conn_birth_time);
  8938. if (tm != NULL) {
  8939. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8940. } else {
  8941. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8942. date[sizeof(date) - 1] = '\0';
  8943. }
  8944. ri = &conn->request_info;
  8945. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8946. referer = header_val(conn, "Referer");
  8947. user_agent = header_val(conn, "User-Agent");
  8948. mg_snprintf(conn,
  8949. NULL, /* Ignore truncation in access log */
  8950. buf,
  8951. sizeof(buf),
  8952. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8953. src_addr,
  8954. ri->remote_user == NULL ? "-" : ri->remote_user,
  8955. date,
  8956. ri->request_method ? ri->request_method : "-",
  8957. ri->request_uri ? ri->request_uri : "-",
  8958. ri->query_string ? "?" : "",
  8959. ri->query_string ? ri->query_string : "",
  8960. ri->http_version,
  8961. conn->status_code,
  8962. conn->num_bytes_sent,
  8963. referer,
  8964. user_agent);
  8965. if (conn->ctx->callbacks.log_access) {
  8966. conn->ctx->callbacks.log_access(conn, buf);
  8967. }
  8968. if (fi.fp) {
  8969. flockfile(fi.fp);
  8970. fprintf(fi.fp, "%s\n", buf);
  8971. fflush(fi.fp);
  8972. funlockfile(fi.fp);
  8973. mg_fclose(&fi);
  8974. }
  8975. }
  8976. /* Verify given socket address against the ACL.
  8977. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  8978. */
  8979. static int
  8980. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8981. {
  8982. int allowed, flag;
  8983. uint32_t net, mask;
  8984. struct vec vec;
  8985. if (ctx) {
  8986. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8987. /* If any ACL is set, deny by default */
  8988. allowed = list == NULL ? '+' : '-';
  8989. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8990. flag = vec.ptr[0];
  8991. if ((flag != '+' && flag != '-')
  8992. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8993. mg_cry(fc(ctx),
  8994. "%s: subnet must be [+|-]x.x.x.x[/x]",
  8995. __func__);
  8996. return -1;
  8997. }
  8998. if (net == (remote_ip & mask)) {
  8999. allowed = flag;
  9000. }
  9001. }
  9002. return allowed == '+';
  9003. }
  9004. return -1;
  9005. }
  9006. #if !defined(_WIN32)
  9007. static int
  9008. set_uid_option(struct mg_context *ctx)
  9009. {
  9010. struct passwd *pw;
  9011. if (ctx) {
  9012. const char *uid = ctx->config[RUN_AS_USER];
  9013. int success = 0;
  9014. if (uid == NULL) {
  9015. success = 1;
  9016. } else {
  9017. if ((pw = getpwnam(uid)) == NULL) {
  9018. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9019. } else if (setgid(pw->pw_gid) == -1) {
  9020. mg_cry(fc(ctx),
  9021. "%s: setgid(%s): %s",
  9022. __func__,
  9023. uid,
  9024. strerror(errno));
  9025. } else if (setgroups(0, NULL)) {
  9026. mg_cry(fc(ctx),
  9027. "%s: setgroups(): %s",
  9028. __func__,
  9029. strerror(errno));
  9030. } else if (setuid(pw->pw_uid) == -1) {
  9031. mg_cry(fc(ctx),
  9032. "%s: setuid(%s): %s",
  9033. __func__,
  9034. uid,
  9035. strerror(errno));
  9036. } else {
  9037. success = 1;
  9038. }
  9039. }
  9040. return success;
  9041. }
  9042. return 0;
  9043. }
  9044. #endif /* !_WIN32 */
  9045. static void
  9046. tls_dtor(void *key)
  9047. {
  9048. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9049. /* key == pthread_getspecific(sTlsKey); */
  9050. if (tls) {
  9051. if (tls->is_master == 2) {
  9052. tls->is_master = -3; /* Mark memory as dead */
  9053. mg_free(tls);
  9054. }
  9055. }
  9056. pthread_setspecific(sTlsKey, NULL);
  9057. }
  9058. #if !defined(NO_SSL)
  9059. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9060. static unsigned long
  9061. ssl_id_callback(void)
  9062. {
  9063. #ifdef _WIN32
  9064. return GetCurrentThreadId();
  9065. #else
  9066. #ifdef __clang__
  9067. #pragma clang diagnostic push
  9068. #pragma clang diagnostic ignored "-Wunreachable-code"
  9069. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9070. * or not, so one of the two conditions will be unreachable by construction.
  9071. * Unfortunately the C standard does not define a way to check this at
  9072. * compile time, since the #if preprocessor conditions can not use the sizeof
  9073. * operator as an argument. */
  9074. #endif
  9075. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9076. /* This is the problematic case for CRYPTO_set_id_callback:
  9077. * The OS pthread_t can not be cast to unsigned long. */
  9078. struct mg_workerTLS *tls =
  9079. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9080. if (tls == NULL) {
  9081. /* SSL called from an unknown thread: Create some thread index.
  9082. */
  9083. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9084. tls->is_master = -2; /* -2 means "3rd party thread" */
  9085. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9086. pthread_setspecific(sTlsKey, tls);
  9087. }
  9088. return tls->thread_idx;
  9089. } else {
  9090. return (unsigned long)pthread_self();
  9091. }
  9092. #ifdef __clang__
  9093. #pragma clang diagnostic pop
  9094. #endif
  9095. #endif
  9096. }
  9097. static pthread_mutex_t *ssl_mutexes;
  9098. static int
  9099. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9100. {
  9101. int ret, err;
  9102. if (!conn) {
  9103. return 0;
  9104. }
  9105. conn->ssl = SSL_new(s);
  9106. if (conn->ssl == NULL) {
  9107. return 0;
  9108. }
  9109. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9110. if (ret != 1) {
  9111. err = SSL_get_error(conn->ssl, ret);
  9112. (void)err; /* TODO: set some error message */
  9113. SSL_free(conn->ssl);
  9114. conn->ssl = NULL;
  9115. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9116. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9117. ERR_remove_state(0);
  9118. return 0;
  9119. }
  9120. ret = func(conn->ssl);
  9121. if (ret != 1) {
  9122. err = SSL_get_error(conn->ssl, ret);
  9123. (void)err; /* TODO: set some error message */
  9124. SSL_free(conn->ssl);
  9125. conn->ssl = NULL;
  9126. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9127. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9128. ERR_remove_state(0);
  9129. return 0;
  9130. }
  9131. return 1;
  9132. }
  9133. /* Return OpenSSL error message (from CRYPTO lib) */
  9134. static const char *
  9135. ssl_error(void)
  9136. {
  9137. unsigned long err;
  9138. err = ERR_get_error();
  9139. return err == 0 ? "" : ERR_error_string(err, NULL);
  9140. }
  9141. static void
  9142. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9143. {
  9144. (void)line;
  9145. (void)file;
  9146. if (mode & 1) {
  9147. /* 1 is CRYPTO_LOCK */
  9148. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9149. } else {
  9150. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9151. }
  9152. }
  9153. #if !defined(NO_SSL_DL)
  9154. static void *
  9155. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9156. {
  9157. union {
  9158. void *p;
  9159. void (*fp)(void);
  9160. } u;
  9161. void *dll_handle;
  9162. struct ssl_func *fp;
  9163. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9164. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9165. return NULL;
  9166. }
  9167. for (fp = sw; fp->name != NULL; fp++) {
  9168. #ifdef _WIN32
  9169. /* GetProcAddress() returns pointer to function */
  9170. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9171. #else
  9172. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9173. * pointers to function pointers. We need to use a union to make a
  9174. * cast. */
  9175. u.p = dlsym(dll_handle, fp->name);
  9176. #endif /* _WIN32 */
  9177. if (u.fp == NULL) {
  9178. mg_cry(fc(ctx),
  9179. "%s: %s: cannot find %s",
  9180. __func__,
  9181. dll_name,
  9182. fp->name);
  9183. dlclose(dll_handle);
  9184. return NULL;
  9185. } else {
  9186. fp->ptr = u.fp;
  9187. }
  9188. }
  9189. return dll_handle;
  9190. }
  9191. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9192. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9193. #endif /* NO_SSL_DL */
  9194. #if defined(SSL_ALREADY_INITIALIZED)
  9195. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9196. #else
  9197. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9198. #endif
  9199. static int
  9200. initialize_ssl(struct mg_context *ctx)
  9201. {
  9202. int i;
  9203. size_t size;
  9204. #if !defined(NO_SSL_DL)
  9205. if (!cryptolib_dll_handle) {
  9206. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9207. if (!cryptolib_dll_handle) {
  9208. return 0;
  9209. }
  9210. }
  9211. #endif /* NO_SSL_DL */
  9212. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9213. return 1;
  9214. }
  9215. /* Initialize locking callbacks, needed for thread safety.
  9216. * http://www.openssl.org/support/faq.html#PROG1
  9217. */
  9218. i = CRYPTO_num_locks();
  9219. if (i < 0) {
  9220. i = 0;
  9221. }
  9222. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9223. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9224. mg_cry(fc(ctx),
  9225. "%s: cannot allocate mutexes: %s",
  9226. __func__,
  9227. ssl_error());
  9228. return 0;
  9229. }
  9230. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9231. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9232. }
  9233. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9234. CRYPTO_set_id_callback(&ssl_id_callback);
  9235. return 1;
  9236. }
  9237. static int
  9238. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9239. {
  9240. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9241. mg_cry(fc(ctx),
  9242. "%s: cannot open certificate file %s: %s",
  9243. __func__,
  9244. pem,
  9245. ssl_error());
  9246. return 0;
  9247. }
  9248. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9249. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9250. mg_cry(fc(ctx),
  9251. "%s: cannot open private key file %s: %s",
  9252. __func__,
  9253. pem,
  9254. ssl_error());
  9255. return 0;
  9256. }
  9257. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9258. mg_cry(fc(ctx),
  9259. "%s: certificate and private key do not match: %s",
  9260. __func__,
  9261. pem);
  9262. return 0;
  9263. }
  9264. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9265. mg_cry(fc(ctx),
  9266. "%s: cannot use certificate chain file %s: %s",
  9267. __func__,
  9268. pem,
  9269. ssl_error());
  9270. return 0;
  9271. }
  9272. return 1;
  9273. }
  9274. static long
  9275. ssl_get_protocol(int version_id)
  9276. {
  9277. long ret = SSL_OP_ALL;
  9278. if (version_id > 0)
  9279. ret |= SSL_OP_NO_SSLv2;
  9280. if (version_id > 1)
  9281. ret |= SSL_OP_NO_SSLv3;
  9282. if (version_id > 2)
  9283. ret |= SSL_OP_NO_TLSv1;
  9284. if (version_id > 3)
  9285. ret |= SSL_OP_NO_TLSv1_1;
  9286. return ret;
  9287. }
  9288. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9289. static int
  9290. set_ssl_option(struct mg_context *ctx)
  9291. {
  9292. const char *pem;
  9293. int callback_ret;
  9294. int should_verify_peer;
  9295. const char *ca_path;
  9296. const char *ca_file;
  9297. int use_default_verify_paths;
  9298. int verify_depth;
  9299. time_t now_rt = time(NULL);
  9300. struct timespec now_mt;
  9301. md5_byte_t ssl_context_id[16];
  9302. md5_state_t md5state;
  9303. int protocol_ver;
  9304. /* If PEM file is not specified and the init_ssl callback
  9305. * is not specified, skip SSL initialization. */
  9306. if (!ctx) {
  9307. return 0;
  9308. }
  9309. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9310. && ctx->callbacks.init_ssl == NULL) {
  9311. return 1;
  9312. }
  9313. if (!initialize_ssl(ctx)) {
  9314. return 0;
  9315. }
  9316. #if !defined(NO_SSL_DL)
  9317. if (!ssllib_dll_handle) {
  9318. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9319. if (!ssllib_dll_handle) {
  9320. return 0;
  9321. }
  9322. }
  9323. #endif /* NO_SSL_DL */
  9324. /* Initialize SSL library */
  9325. SSL_library_init();
  9326. SSL_load_error_strings();
  9327. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9328. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9329. return 0;
  9330. }
  9331. SSL_CTX_clear_options(ctx->ssl_ctx,
  9332. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9333. | SSL_OP_NO_TLSv1_1);
  9334. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9335. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9336. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9337. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9338. /* If a callback has been specified, call it. */
  9339. callback_ret =
  9340. (ctx->callbacks.init_ssl == NULL)
  9341. ? 0
  9342. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9343. /* If callback returns 0, civetweb sets up the SSL certificate.
  9344. * If it returns 1, civetweb assumes the calback already did this.
  9345. * If it returns -1, initializing ssl fails. */
  9346. if (callback_ret < 0) {
  9347. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9348. return 0;
  9349. }
  9350. if (callback_ret > 0) {
  9351. if (pem != NULL) {
  9352. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9353. }
  9354. return 1;
  9355. }
  9356. /* Use some UID as session context ID. */
  9357. md5_init(&md5state);
  9358. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9359. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9360. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9361. md5_append(&md5state,
  9362. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9363. strlen(ctx->config[LISTENING_PORTS]));
  9364. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9365. md5_finish(&md5state, ssl_context_id);
  9366. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9367. (const unsigned char *)&ssl_context_id,
  9368. sizeof(ssl_context_id));
  9369. if (pem != NULL) {
  9370. if (!ssl_use_pem_file(ctx, pem)) {
  9371. return 0;
  9372. }
  9373. }
  9374. should_verify_peer =
  9375. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9376. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9377. use_default_verify_paths =
  9378. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9379. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9380. if (should_verify_peer) {
  9381. ca_path = ctx->config[SSL_CA_PATH];
  9382. ca_file = ctx->config[SSL_CA_FILE];
  9383. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9384. != 1) {
  9385. mg_cry(fc(ctx),
  9386. "SSL_CTX_load_verify_locations error: %s "
  9387. "ssl_verify_peer requires setting "
  9388. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9389. "present in "
  9390. "the .conf file?",
  9391. ssl_error());
  9392. return 0;
  9393. }
  9394. SSL_CTX_set_verify(ctx->ssl_ctx,
  9395. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9396. NULL);
  9397. if (use_default_verify_paths
  9398. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9399. mg_cry(fc(ctx),
  9400. "SSL_CTX_set_default_verify_paths error: %s",
  9401. ssl_error());
  9402. return 0;
  9403. }
  9404. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9405. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9406. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9407. }
  9408. }
  9409. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9410. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9411. != 1) {
  9412. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9413. }
  9414. }
  9415. return 1;
  9416. }
  9417. static void
  9418. uninitialize_ssl(struct mg_context *ctx)
  9419. {
  9420. int i;
  9421. (void)ctx;
  9422. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9423. /* Shutdown according to
  9424. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9425. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9426. */
  9427. CRYPTO_set_locking_callback(NULL);
  9428. CRYPTO_set_id_callback(NULL);
  9429. ENGINE_cleanup();
  9430. CONF_modules_unload(1);
  9431. ERR_free_strings();
  9432. EVP_cleanup();
  9433. CRYPTO_cleanup_all_ex_data();
  9434. ERR_remove_state(0);
  9435. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9436. pthread_mutex_destroy(&ssl_mutexes[i]);
  9437. }
  9438. }
  9439. }
  9440. #endif /* !NO_SSL */
  9441. static int
  9442. set_gpass_option(struct mg_context *ctx)
  9443. {
  9444. if (ctx) {
  9445. struct file file = STRUCT_FILE_INITIALIZER;
  9446. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9447. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9448. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9449. return 0;
  9450. }
  9451. return 1;
  9452. }
  9453. return 0;
  9454. }
  9455. static int
  9456. set_acl_option(struct mg_context *ctx)
  9457. {
  9458. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9459. }
  9460. static void
  9461. reset_per_request_attributes(struct mg_connection *conn)
  9462. {
  9463. if (!conn) {
  9464. return;
  9465. }
  9466. conn->path_info = NULL;
  9467. conn->num_bytes_sent = conn->consumed_content = 0;
  9468. conn->status_code = -1;
  9469. conn->is_chunked = 0;
  9470. conn->must_close = conn->request_len = conn->throttle = 0;
  9471. conn->request_info.content_length = -1;
  9472. conn->request_info.remote_user = NULL;
  9473. conn->request_info.request_method = NULL;
  9474. conn->request_info.request_uri = NULL;
  9475. conn->request_info.local_uri = NULL;
  9476. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9477. * local_uri and request_uri */
  9478. conn->request_info.http_version = NULL;
  9479. conn->request_info.num_headers = 0;
  9480. conn->data_len = 0;
  9481. conn->chunk_remainder = 0;
  9482. conn->internal_error = 0;
  9483. }
  9484. static int
  9485. set_sock_timeout(SOCKET sock, int milliseconds)
  9486. {
  9487. int r0 = 0, r1, r2;
  9488. #ifdef _WIN32
  9489. /* Windows specific */
  9490. DWORD tv = (DWORD)milliseconds;
  9491. #else
  9492. /* Linux, ... (not Windows) */
  9493. struct timeval tv;
  9494. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9495. * max. time waiting for the acknowledged of TCP data before the connection
  9496. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9497. * If this option is not set, the default timeout of 20-30 minutes is used.
  9498. */
  9499. /* #define TCP_USER_TIMEOUT (18) */
  9500. #if defined(TCP_USER_TIMEOUT)
  9501. unsigned int uto = (unsigned int)milliseconds;
  9502. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9503. #endif
  9504. memset(&tv, 0, sizeof(tv));
  9505. tv.tv_sec = milliseconds / 1000;
  9506. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9507. #endif /* _WIN32 */
  9508. r1 = setsockopt(
  9509. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9510. r2 = setsockopt(
  9511. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9512. return r0 || r1 || r2;
  9513. }
  9514. static int
  9515. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9516. {
  9517. if (setsockopt(sock,
  9518. IPPROTO_TCP,
  9519. TCP_NODELAY,
  9520. (SOCK_OPT_TYPE)&nodelay_on,
  9521. sizeof(nodelay_on)) != 0) {
  9522. /* Error */
  9523. return 1;
  9524. }
  9525. /* OK */
  9526. return 0;
  9527. }
  9528. static void
  9529. close_socket_gracefully(struct mg_connection *conn)
  9530. {
  9531. #if defined(_WIN32)
  9532. char buf[MG_BUF_LEN];
  9533. int n;
  9534. #endif
  9535. struct linger linger;
  9536. if (!conn) {
  9537. return;
  9538. }
  9539. /* Set linger option to avoid socket hanging out after close. This
  9540. * prevent
  9541. * ephemeral port exhaust problem under high QPS. */
  9542. linger.l_onoff = 1;
  9543. linger.l_linger = 1;
  9544. if (setsockopt(conn->client.sock,
  9545. SOL_SOCKET,
  9546. SO_LINGER,
  9547. (char *)&linger,
  9548. sizeof(linger)) != 0) {
  9549. mg_cry(conn,
  9550. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9551. __func__,
  9552. strerror(ERRNO));
  9553. }
  9554. /* Send FIN to the client */
  9555. shutdown(conn->client.sock, SHUT_WR);
  9556. set_non_blocking_mode(conn->client.sock);
  9557. #if defined(_WIN32)
  9558. /* Read and discard pending incoming data. If we do not do that and
  9559. * close
  9560. * the socket, the data in the send buffer may be discarded. This
  9561. * behaviour is seen on Windows, when client keeps sending data
  9562. * when server decides to close the connection; then when client
  9563. * does recv() it gets no data back. */
  9564. do {
  9565. n = pull(
  9566. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9567. } while (n > 0);
  9568. #endif
  9569. /* Now we know that our FIN is ACK-ed, safe to close */
  9570. closesocket(conn->client.sock);
  9571. conn->client.sock = INVALID_SOCKET;
  9572. }
  9573. static void
  9574. close_connection(struct mg_connection *conn)
  9575. {
  9576. if (!conn || !conn->ctx) {
  9577. return;
  9578. }
  9579. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9580. if (conn->lua_websocket_state) {
  9581. lua_websocket_close(conn, conn->lua_websocket_state);
  9582. conn->lua_websocket_state = NULL;
  9583. }
  9584. #endif
  9585. /* call the connection_close callback if assigned */
  9586. if ((conn->ctx->callbacks.connection_close != NULL)
  9587. && (conn->ctx->context_type == 1)) {
  9588. conn->ctx->callbacks.connection_close(conn);
  9589. }
  9590. mg_lock_connection(conn);
  9591. conn->must_close = 1;
  9592. #ifndef NO_SSL
  9593. if (conn->ssl != NULL) {
  9594. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9595. */
  9596. SSL_shutdown(conn->ssl);
  9597. SSL_free(conn->ssl);
  9598. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9599. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9600. ERR_remove_state(0);
  9601. conn->ssl = NULL;
  9602. }
  9603. #endif
  9604. if (conn->client.sock != INVALID_SOCKET) {
  9605. close_socket_gracefully(conn);
  9606. conn->client.sock = INVALID_SOCKET;
  9607. }
  9608. mg_unlock_connection(conn);
  9609. }
  9610. void
  9611. mg_close_connection(struct mg_connection *conn)
  9612. {
  9613. struct mg_context *client_ctx = NULL;
  9614. unsigned int i;
  9615. if (conn == NULL) {
  9616. return;
  9617. }
  9618. if (conn->ctx->context_type == 2) {
  9619. client_ctx = conn->ctx;
  9620. /* client context: loops must end */
  9621. conn->ctx->stop_flag = 1;
  9622. }
  9623. #ifndef NO_SSL
  9624. if (conn->client_ssl_ctx != NULL) {
  9625. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9626. }
  9627. #endif
  9628. close_connection(conn);
  9629. if (client_ctx != NULL) {
  9630. /* join worker thread and free context */
  9631. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9632. if (client_ctx->workerthreadids[i] != 0) {
  9633. mg_join_thread(client_ctx->workerthreadids[i]);
  9634. }
  9635. }
  9636. mg_free(client_ctx->workerthreadids);
  9637. mg_free(client_ctx);
  9638. (void)pthread_mutex_destroy(&conn->mutex);
  9639. mg_free(conn);
  9640. }
  9641. }
  9642. static struct mg_connection *
  9643. mg_connect_client_impl(const struct mg_client_options *client_options,
  9644. int use_ssl,
  9645. char *ebuf,
  9646. size_t ebuf_len)
  9647. {
  9648. static struct mg_context fake_ctx;
  9649. struct mg_connection *conn = NULL;
  9650. SOCKET sock;
  9651. union usa sa;
  9652. if (!connect_socket(&fake_ctx,
  9653. client_options->host,
  9654. client_options->port,
  9655. use_ssl,
  9656. ebuf,
  9657. ebuf_len,
  9658. &sock,
  9659. &sa)) {
  9660. ;
  9661. } else if ((conn = (struct mg_connection *)
  9662. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9663. mg_snprintf(NULL,
  9664. NULL, /* No truncation check for ebuf */
  9665. ebuf,
  9666. ebuf_len,
  9667. "calloc(): %s",
  9668. strerror(ERRNO));
  9669. closesocket(sock);
  9670. #ifndef NO_SSL
  9671. } else if (use_ssl
  9672. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9673. == NULL) {
  9674. mg_snprintf(NULL,
  9675. NULL, /* No truncation check for ebuf */
  9676. ebuf,
  9677. ebuf_len,
  9678. "SSL_CTX_new error");
  9679. closesocket(sock);
  9680. mg_free(conn);
  9681. conn = NULL;
  9682. #endif /* NO_SSL */
  9683. } else {
  9684. #ifdef USE_IPV6
  9685. socklen_t len = (sa.sa.sa_family == AF_INET)
  9686. ? sizeof(conn->client.rsa.sin)
  9687. : sizeof(conn->client.rsa.sin6);
  9688. struct sockaddr *psa =
  9689. (sa.sa.sa_family == AF_INET)
  9690. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9691. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9692. #else
  9693. socklen_t len = sizeof(conn->client.rsa.sin);
  9694. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9695. #endif
  9696. conn->buf_size = MAX_REQUEST_SIZE;
  9697. conn->buf = (char *)(conn + 1);
  9698. conn->ctx = &fake_ctx;
  9699. conn->client.sock = sock;
  9700. conn->client.lsa = sa;
  9701. if (getsockname(sock, psa, &len) != 0) {
  9702. mg_cry(conn,
  9703. "%s: getsockname() failed: %s",
  9704. __func__,
  9705. strerror(ERRNO));
  9706. }
  9707. conn->client.is_ssl = use_ssl ? 1 : 0;
  9708. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9709. #ifndef NO_SSL
  9710. if (use_ssl) {
  9711. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9712. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9713. SSL_CTX_set_verify call is needed to switch off server
  9714. * certificate checking, which is off by default in OpenSSL and
  9715. on
  9716. * in yaSSL. */
  9717. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9718. // SSL_VERIFY_PEER,
  9719. // verify_ssl_server);
  9720. if (client_options->client_cert) {
  9721. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9722. mg_snprintf(NULL,
  9723. NULL, /* No truncation check for ebuf */
  9724. ebuf,
  9725. ebuf_len,
  9726. "Can not use SSL client certificate");
  9727. SSL_CTX_free(conn->client_ssl_ctx);
  9728. closesocket(sock);
  9729. mg_free(conn);
  9730. conn = NULL;
  9731. }
  9732. }
  9733. if (client_options->server_cert) {
  9734. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9735. client_options->server_cert,
  9736. NULL);
  9737. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9738. } else {
  9739. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9740. }
  9741. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9742. mg_snprintf(NULL,
  9743. NULL, /* No truncation check for ebuf */
  9744. ebuf,
  9745. ebuf_len,
  9746. "SSL connection error");
  9747. SSL_CTX_free(conn->client_ssl_ctx);
  9748. closesocket(sock);
  9749. mg_free(conn);
  9750. conn = NULL;
  9751. }
  9752. }
  9753. #endif
  9754. }
  9755. return conn;
  9756. }
  9757. CIVETWEB_API struct mg_connection *
  9758. mg_connect_client_secure(const struct mg_client_options *client_options,
  9759. char *error_buffer,
  9760. size_t error_buffer_size)
  9761. {
  9762. return mg_connect_client_impl(client_options,
  9763. 1,
  9764. error_buffer,
  9765. error_buffer_size);
  9766. }
  9767. struct mg_connection *
  9768. mg_connect_client(const char *host,
  9769. int port,
  9770. int use_ssl,
  9771. char *error_buffer,
  9772. size_t error_buffer_size)
  9773. {
  9774. struct mg_client_options opts;
  9775. memset(&opts, 0, sizeof(opts));
  9776. opts.host = host;
  9777. opts.port = port;
  9778. return mg_connect_client_impl(&opts,
  9779. use_ssl,
  9780. error_buffer,
  9781. error_buffer_size);
  9782. }
  9783. static const struct {
  9784. const char *proto;
  9785. size_t proto_len;
  9786. unsigned default_port;
  9787. } abs_uri_protocols[] = {{"http://", 7, 80},
  9788. {"https://", 8, 443},
  9789. {"ws://", 5, 80},
  9790. {"wss://", 6, 443},
  9791. {NULL, 0, 0}};
  9792. /* Check if the uri is valid.
  9793. * return 0 for invalid uri,
  9794. * return 1 for *,
  9795. * return 2 for relative uri,
  9796. * return 3 for absolute uri without port,
  9797. * return 4 for absolute uri with port */
  9798. static int
  9799. get_uri_type(const char *uri)
  9800. {
  9801. int i;
  9802. char *hostend, *portbegin, *portend;
  9803. unsigned long port;
  9804. /* According to the HTTP standard
  9805. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9806. * URI can be an asterisk (*) or should start with slash (relative uri),
  9807. * or it should start with the protocol (absolute uri). */
  9808. if (uri[0] == '*' && uri[1] == '\0') {
  9809. /* asterisk */
  9810. return 1;
  9811. }
  9812. if (uri[0] == '/') {
  9813. /* relative uri */
  9814. return 2;
  9815. }
  9816. /* It could be an absolute uri: */
  9817. /* This function only checks if the uri is valid, not if it is
  9818. * addressing the current server. So civetweb can also be used
  9819. * as a proxy server. */
  9820. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9821. if (mg_strncasecmp(uri,
  9822. abs_uri_protocols[i].proto,
  9823. abs_uri_protocols[i].proto_len) == 0) {
  9824. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9825. if (!hostend) {
  9826. return 0;
  9827. }
  9828. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9829. if (!portbegin) {
  9830. return 3;
  9831. }
  9832. port = strtoul(portbegin + 1, &portend, 10);
  9833. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9834. return 0;
  9835. }
  9836. return 4;
  9837. }
  9838. }
  9839. return 0;
  9840. }
  9841. /* Return NULL or the relative uri at the current server */
  9842. static const char *
  9843. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9844. {
  9845. const char *server_domain;
  9846. size_t server_domain_len;
  9847. size_t request_domain_len = 0;
  9848. unsigned long port = 0;
  9849. int i;
  9850. const char *hostbegin = NULL;
  9851. const char *hostend = NULL;
  9852. const char *portbegin;
  9853. char *portend;
  9854. /* DNS is case insensitive, so use case insensitive string compare here
  9855. */
  9856. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9857. if (!server_domain) {
  9858. return 0;
  9859. }
  9860. server_domain_len = strlen(server_domain);
  9861. if (!server_domain_len) {
  9862. return 0;
  9863. }
  9864. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9865. if (mg_strncasecmp(uri,
  9866. abs_uri_protocols[i].proto,
  9867. abs_uri_protocols[i].proto_len) == 0) {
  9868. hostbegin = uri + abs_uri_protocols[i].proto_len;
  9869. hostend = strchr(hostbegin, '/');
  9870. if (!hostend) {
  9871. return 0;
  9872. }
  9873. portbegin = strchr(hostbegin, ':');
  9874. if ((!portbegin) || (portbegin > hostend)) {
  9875. port = abs_uri_protocols[i].default_port;
  9876. request_domain_len = (size_t)(hostend - hostbegin);
  9877. } else {
  9878. port = strtoul(portbegin + 1, &portend, 10);
  9879. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9880. return 0;
  9881. }
  9882. request_domain_len = (size_t)(portbegin - hostbegin);
  9883. }
  9884. /* protocol found, port set */
  9885. break;
  9886. }
  9887. }
  9888. if (!port) {
  9889. /* port remains 0 if the protocol is not found */
  9890. return 0;
  9891. }
  9892. #if defined(USE_IPV6)
  9893. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9894. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9895. /* Request is directed to a different port */
  9896. return 0;
  9897. }
  9898. } else
  9899. #endif
  9900. {
  9901. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9902. /* Request is directed to a different port */
  9903. return 0;
  9904. }
  9905. }
  9906. if ((request_domain_len != server_domain_len)
  9907. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  9908. /* Request is directed to another server */
  9909. return 0;
  9910. }
  9911. return hostend;
  9912. }
  9913. static int
  9914. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9915. {
  9916. const char *cl;
  9917. if (ebuf_len > 0) {
  9918. ebuf[0] = '\0';
  9919. }
  9920. *err = 0;
  9921. reset_per_request_attributes(conn);
  9922. if (!conn) {
  9923. mg_snprintf(conn,
  9924. NULL, /* No truncation check for ebuf */
  9925. ebuf,
  9926. ebuf_len,
  9927. "%s",
  9928. "Internal error");
  9929. *err = 500;
  9930. return 0;
  9931. }
  9932. /* Set the time the request was received. This value should be used for
  9933. * timeouts. */
  9934. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  9935. conn->request_len =
  9936. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  9937. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  9938. */
  9939. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  9940. mg_snprintf(conn,
  9941. NULL, /* No truncation check for ebuf */
  9942. ebuf,
  9943. ebuf_len,
  9944. "%s",
  9945. "Invalid request size");
  9946. *err = 500;
  9947. return 0;
  9948. }
  9949. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  9950. mg_snprintf(conn,
  9951. NULL, /* No truncation check for ebuf */
  9952. ebuf,
  9953. ebuf_len,
  9954. "%s",
  9955. "Request Too Large");
  9956. *err = 413;
  9957. return 0;
  9958. } else if (conn->request_len <= 0) {
  9959. if (conn->data_len > 0) {
  9960. mg_snprintf(conn,
  9961. NULL, /* No truncation check for ebuf */
  9962. ebuf,
  9963. ebuf_len,
  9964. "%s",
  9965. "Client sent malformed request");
  9966. *err = 400;
  9967. } else {
  9968. /* Server did not send anything -> just close the connection */
  9969. conn->must_close = 1;
  9970. mg_snprintf(conn,
  9971. NULL, /* No truncation check for ebuf */
  9972. ebuf,
  9973. ebuf_len,
  9974. "%s",
  9975. "Client did not send a request");
  9976. *err = 0;
  9977. }
  9978. return 0;
  9979. } else if (parse_http_message(conn->buf,
  9980. conn->buf_size,
  9981. &conn->request_info) <= 0) {
  9982. mg_snprintf(conn,
  9983. NULL, /* No truncation check for ebuf */
  9984. ebuf,
  9985. ebuf_len,
  9986. "%s",
  9987. "Bad Request");
  9988. *err = 400;
  9989. return 0;
  9990. } else {
  9991. /* Message is a valid request or response */
  9992. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9993. /* Request/response has content length set */
  9994. char *endptr = NULL;
  9995. conn->content_len = strtoll(cl, &endptr, 10);
  9996. if (endptr == cl) {
  9997. mg_snprintf(conn,
  9998. NULL, /* No truncation check for ebuf */
  9999. ebuf,
  10000. ebuf_len,
  10001. "%s",
  10002. "Bad Request");
  10003. *err = 411;
  10004. return 0;
  10005. }
  10006. /* Publish the content length back to the request info. */
  10007. conn->request_info.content_length = conn->content_len;
  10008. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10009. != NULL
  10010. && strcmp(cl, "chunked") == 0) {
  10011. conn->is_chunked = 1;
  10012. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10013. || !mg_strcasecmp(conn->request_info.request_method,
  10014. "PUT")) {
  10015. /* POST or PUT request without content length set */
  10016. conn->content_len = -1;
  10017. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10018. "HTTP/",
  10019. 5)) {
  10020. /* Response without content length set */
  10021. conn->content_len = -1;
  10022. } else {
  10023. /* Other request */
  10024. conn->content_len = 0;
  10025. }
  10026. }
  10027. return 1;
  10028. }
  10029. int
  10030. mg_get_response(struct mg_connection *conn,
  10031. char *ebuf,
  10032. size_t ebuf_len,
  10033. int timeout)
  10034. {
  10035. if (conn) {
  10036. /* Implementation of API function for HTTP clients */
  10037. int err, ret;
  10038. struct mg_context *octx = conn->ctx;
  10039. struct mg_context rctx = *(conn->ctx);
  10040. char txt[32]; /* will not overflow */
  10041. if (timeout >= 0) {
  10042. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10043. rctx.config[REQUEST_TIMEOUT] = txt;
  10044. set_sock_timeout(conn->client.sock, timeout);
  10045. } else {
  10046. rctx.config[REQUEST_TIMEOUT] = NULL;
  10047. }
  10048. conn->ctx = &rctx;
  10049. ret = getreq(conn, ebuf, ebuf_len, &err);
  10050. conn->ctx = octx;
  10051. /* TODO: 1) uri is deprecated;
  10052. * 2) here, ri.uri is the http response code */
  10053. conn->request_info.uri = conn->request_info.request_uri;
  10054. /* TODO (mid): Define proper return values - maybe return length?
  10055. * For the first test use <0 for error and >0 for OK */
  10056. return (ret == 0) ? -1 : +1;
  10057. }
  10058. return -1;
  10059. }
  10060. struct mg_connection *
  10061. mg_download(const char *host,
  10062. int port,
  10063. int use_ssl,
  10064. char *ebuf,
  10065. size_t ebuf_len,
  10066. const char *fmt,
  10067. ...)
  10068. {
  10069. struct mg_connection *conn;
  10070. va_list ap;
  10071. int i;
  10072. int reqerr;
  10073. va_start(ap, fmt);
  10074. ebuf[0] = '\0';
  10075. /* open a connection */
  10076. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10077. if (conn != NULL) {
  10078. i = mg_vprintf(conn, fmt, ap);
  10079. if (i <= 0) {
  10080. mg_snprintf(conn,
  10081. NULL, /* No truncation check for ebuf */
  10082. ebuf,
  10083. ebuf_len,
  10084. "%s",
  10085. "Error sending request");
  10086. } else {
  10087. getreq(conn, ebuf, ebuf_len, &reqerr);
  10088. /* TODO: 1) uri is deprecated;
  10089. * 2) here, ri.uri is the http response code */
  10090. conn->request_info.uri = conn->request_info.request_uri;
  10091. }
  10092. }
  10093. /* if an error occured, close the connection */
  10094. if (ebuf[0] != '\0' && conn != NULL) {
  10095. mg_close_connection(conn);
  10096. conn = NULL;
  10097. }
  10098. va_end(ap);
  10099. return conn;
  10100. }
  10101. struct websocket_client_thread_data {
  10102. struct mg_connection *conn;
  10103. mg_websocket_data_handler data_handler;
  10104. mg_websocket_close_handler close_handler;
  10105. void *callback_data;
  10106. };
  10107. #if defined(USE_WEBSOCKET)
  10108. #ifdef _WIN32
  10109. static unsigned __stdcall websocket_client_thread(void *data)
  10110. #else
  10111. static void *
  10112. websocket_client_thread(void *data)
  10113. #endif
  10114. {
  10115. struct websocket_client_thread_data *cdata =
  10116. (struct websocket_client_thread_data *)data;
  10117. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10118. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10119. if (cdata->close_handler != NULL) {
  10120. cdata->close_handler(cdata->conn, cdata->callback_data);
  10121. }
  10122. mg_free((void *)cdata);
  10123. #ifdef _WIN32
  10124. return 0;
  10125. #else
  10126. return NULL;
  10127. #endif
  10128. }
  10129. #endif
  10130. struct mg_connection *
  10131. mg_connect_websocket_client(const char *host,
  10132. int port,
  10133. int use_ssl,
  10134. char *error_buffer,
  10135. size_t error_buffer_size,
  10136. const char *path,
  10137. const char *origin,
  10138. mg_websocket_data_handler data_func,
  10139. mg_websocket_close_handler close_func,
  10140. void *user_data)
  10141. {
  10142. struct mg_connection *conn = NULL;
  10143. #if defined(USE_WEBSOCKET)
  10144. struct mg_context *newctx = NULL;
  10145. struct websocket_client_thread_data *thread_data;
  10146. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10147. static const char *handshake_req;
  10148. if (origin != NULL) {
  10149. handshake_req = "GET %s HTTP/1.1\r\n"
  10150. "Host: %s\r\n"
  10151. "Upgrade: websocket\r\n"
  10152. "Connection: Upgrade\r\n"
  10153. "Sec-WebSocket-Key: %s\r\n"
  10154. "Sec-WebSocket-Version: 13\r\n"
  10155. "Origin: %s\r\n"
  10156. "\r\n";
  10157. } else {
  10158. handshake_req = "GET %s HTTP/1.1\r\n"
  10159. "Host: %s\r\n"
  10160. "Upgrade: websocket\r\n"
  10161. "Connection: Upgrade\r\n"
  10162. "Sec-WebSocket-Key: %s\r\n"
  10163. "Sec-WebSocket-Version: 13\r\n"
  10164. "\r\n";
  10165. }
  10166. /* Establish the client connection and request upgrade */
  10167. conn = mg_download(host,
  10168. port,
  10169. use_ssl,
  10170. error_buffer,
  10171. error_buffer_size,
  10172. handshake_req,
  10173. path,
  10174. host,
  10175. magic,
  10176. origin);
  10177. /* Connection object will be null if something goes wrong */
  10178. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10179. if (!*error_buffer) {
  10180. /* if there is a connection, but it did not return 101,
  10181. * error_buffer is not yet set */
  10182. mg_snprintf(conn,
  10183. NULL, /* No truncation check for ebuf */
  10184. error_buffer,
  10185. error_buffer_size,
  10186. "Unexpected server reply");
  10187. }
  10188. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10189. if (conn != NULL) {
  10190. mg_free(conn);
  10191. conn = NULL;
  10192. }
  10193. return conn;
  10194. }
  10195. /* For client connections, mg_context is fake. Since we need to set a
  10196. * callback function, we need to create a copy and modify it. */
  10197. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10198. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10199. newctx->user_data = user_data;
  10200. newctx->context_type = 2; /* client context type */
  10201. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10202. newctx->workerthreadids =
  10203. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10204. conn->ctx = newctx;
  10205. thread_data = (struct websocket_client_thread_data *)
  10206. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10207. thread_data->conn = conn;
  10208. thread_data->data_handler = data_func;
  10209. thread_data->close_handler = close_func;
  10210. thread_data->callback_data = NULL;
  10211. /* Start a thread to read the websocket client connection
  10212. * This thread will automatically stop when mg_disconnect is
  10213. * called on the client connection */
  10214. if (mg_start_thread_with_id(websocket_client_thread,
  10215. (void *)thread_data,
  10216. newctx->workerthreadids) != 0) {
  10217. mg_free((void *)thread_data);
  10218. mg_free((void *)newctx->workerthreadids);
  10219. mg_free((void *)newctx);
  10220. mg_free((void *)conn);
  10221. conn = NULL;
  10222. DEBUG_TRACE("%s",
  10223. "Websocket client connect thread could not be started\r\n");
  10224. }
  10225. #else
  10226. /* Appease "unused parameter" warnings */
  10227. (void)host;
  10228. (void)port;
  10229. (void)use_ssl;
  10230. (void)error_buffer;
  10231. (void)error_buffer_size;
  10232. (void)path;
  10233. (void)origin;
  10234. (void)user_data;
  10235. (void)data_func;
  10236. (void)close_func;
  10237. #endif
  10238. return conn;
  10239. }
  10240. static void
  10241. process_new_connection(struct mg_connection *conn)
  10242. {
  10243. if (conn && conn->ctx) {
  10244. struct mg_request_info *ri = &conn->request_info;
  10245. int keep_alive_enabled, keep_alive, discard_len;
  10246. char ebuf[100];
  10247. const char *hostend;
  10248. int reqerr, uri_type;
  10249. keep_alive_enabled =
  10250. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10251. /* Important: on new connection, reset the receiving buffer. Credit
  10252. * goes to crule42. */
  10253. conn->data_len = 0;
  10254. do {
  10255. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10256. /* The request sent by the client could not be understood by
  10257. * the server, or it was incomplete or a timeout. Send an
  10258. * error message and close the connection. */
  10259. if (reqerr > 0) {
  10260. /*assert(ebuf[0] != '\0');*/
  10261. send_http_error(conn, reqerr, "%s", ebuf);
  10262. }
  10263. } else if (strcmp(ri->http_version, "1.0")
  10264. && strcmp(ri->http_version, "1.1")) {
  10265. mg_snprintf(conn,
  10266. NULL, /* No truncation check for ebuf */
  10267. ebuf,
  10268. sizeof(ebuf),
  10269. "Bad HTTP version: [%s]",
  10270. ri->http_version);
  10271. send_http_error(conn, 505, "%s", ebuf);
  10272. }
  10273. if (ebuf[0] == '\0') {
  10274. uri_type = get_uri_type(conn->request_info.request_uri);
  10275. switch (uri_type) {
  10276. case 1:
  10277. /* Asterisk */
  10278. conn->request_info.local_uri = NULL;
  10279. break;
  10280. case 2:
  10281. /* relative uri */
  10282. conn->request_info.local_uri =
  10283. conn->request_info.request_uri;
  10284. break;
  10285. case 3:
  10286. case 4:
  10287. /* absolute uri (with/without port) */
  10288. hostend = get_rel_url_at_current_server(
  10289. conn->request_info.request_uri, conn);
  10290. if (hostend) {
  10291. conn->request_info.local_uri = hostend;
  10292. } else {
  10293. conn->request_info.local_uri = NULL;
  10294. }
  10295. break;
  10296. default:
  10297. mg_snprintf(conn,
  10298. NULL, /* No truncation check for ebuf */
  10299. ebuf,
  10300. sizeof(ebuf),
  10301. "Invalid URI: [%s]",
  10302. ri->request_uri);
  10303. send_http_error(conn, 400, "%s", ebuf);
  10304. break;
  10305. }
  10306. /* TODO: cleanup uri, local_uri and request_uri */
  10307. conn->request_info.uri = conn->request_info.local_uri;
  10308. }
  10309. if (ebuf[0] == '\0') {
  10310. if (conn->request_info.local_uri) {
  10311. /* handle request to local server */
  10312. handle_request(conn);
  10313. if (conn->ctx->callbacks.end_request != NULL) {
  10314. conn->ctx->callbacks.end_request(conn,
  10315. conn->status_code);
  10316. }
  10317. log_access(conn);
  10318. } else {
  10319. /* TODO: handle non-local request (PROXY) */
  10320. conn->must_close = 1;
  10321. }
  10322. } else {
  10323. conn->must_close = 1;
  10324. }
  10325. if (ri->remote_user != NULL) {
  10326. mg_free((void *)ri->remote_user);
  10327. /* Important! When having connections with and without auth
  10328. * would cause double free and then crash */
  10329. ri->remote_user = NULL;
  10330. }
  10331. /* NOTE(lsm): order is important here. should_keep_alive() call
  10332. * is
  10333. * using parsed request, which will be invalid after memmove's
  10334. * below.
  10335. * Therefore, memorize should_keep_alive() result now for later
  10336. * use
  10337. * in loop exit condition. */
  10338. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10339. && conn->content_len >= 0 && should_keep_alive(conn);
  10340. /* Discard all buffered data for this request */
  10341. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10342. && conn->request_len + conn->content_len
  10343. < (int64_t)conn->data_len
  10344. ? (int)(conn->request_len + conn->content_len)
  10345. : conn->data_len;
  10346. /*assert(discard_len >= 0);*/
  10347. if (discard_len < 0)
  10348. break;
  10349. conn->data_len -= discard_len;
  10350. if (conn->data_len > 0) {
  10351. memmove(conn->buf,
  10352. conn->buf + discard_len,
  10353. (size_t)conn->data_len);
  10354. }
  10355. /* assert(conn->data_len >= 0); */
  10356. /* assert(conn->data_len <= conn->buf_size); */
  10357. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10358. break;
  10359. }
  10360. } while (keep_alive);
  10361. }
  10362. }
  10363. /* Worker threads take accepted socket from the queue */
  10364. static int
  10365. consume_socket(struct mg_context *ctx, struct socket *sp)
  10366. {
  10367. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10368. if (!ctx) {
  10369. return 0;
  10370. }
  10371. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10372. DEBUG_TRACE("%s", "going idle");
  10373. /* If the queue is empty, wait. We're idle at this point. */
  10374. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10375. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10376. }
  10377. /* If we're stopping, sq_head may be equal to sq_tail. */
  10378. if (ctx->sq_head > ctx->sq_tail) {
  10379. /* Copy socket from the queue and increment tail */
  10380. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10381. ctx->sq_tail++;
  10382. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10383. /* Wrap pointers if needed */
  10384. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10385. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10386. ctx->sq_head -= QUEUE_SIZE(ctx);
  10387. }
  10388. }
  10389. (void)pthread_cond_signal(&ctx->sq_empty);
  10390. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10391. return !ctx->stop_flag;
  10392. #undef QUEUE_SIZE
  10393. }
  10394. static void *
  10395. worker_thread_run(void *thread_func_param)
  10396. {
  10397. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10398. struct mg_connection *conn;
  10399. struct mg_workerTLS tls;
  10400. #if defined(MG_LEGACY_INTERFACE)
  10401. uint32_t addr;
  10402. #endif
  10403. mg_set_thread_name("worker");
  10404. tls.is_master = 0;
  10405. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10406. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10407. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10408. #endif
  10409. conn =
  10410. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10411. if (conn == NULL) {
  10412. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10413. } else {
  10414. pthread_setspecific(sTlsKey, &tls);
  10415. conn->buf_size = MAX_REQUEST_SIZE;
  10416. conn->buf = (char *)(conn + 1);
  10417. conn->ctx = ctx;
  10418. conn->request_info.user_data = ctx->user_data;
  10419. /* Allocate a mutex for this connection to allow communication both
  10420. * within the request handler and from elsewhere in the application
  10421. */
  10422. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10423. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10424. * signal sq_empty condvar to wake up the master waiting in
  10425. * produce_socket() */
  10426. while (consume_socket(ctx, &conn->client)) {
  10427. conn->conn_birth_time = time(NULL);
  10428. /* Fill in IP, port info early so even if SSL setup below fails,
  10429. * error handler would have the corresponding info.
  10430. * Thanks to Johannes Winkelmann for the patch.
  10431. */
  10432. #if defined(USE_IPV6)
  10433. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10434. conn->request_info.remote_port =
  10435. ntohs(conn->client.rsa.sin6.sin6_port);
  10436. } else
  10437. #endif
  10438. {
  10439. conn->request_info.remote_port =
  10440. ntohs(conn->client.rsa.sin.sin_port);
  10441. }
  10442. sockaddr_to_string(conn->request_info.remote_addr,
  10443. sizeof(conn->request_info.remote_addr),
  10444. &conn->client.rsa);
  10445. #if defined(MG_LEGACY_INTERFACE)
  10446. /* This legacy interface only works for the IPv4 case */
  10447. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10448. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10449. #endif
  10450. conn->request_info.is_ssl = conn->client.is_ssl;
  10451. if (!conn->client.is_ssl
  10452. #ifndef NO_SSL
  10453. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10454. #endif
  10455. ) {
  10456. process_new_connection(conn);
  10457. }
  10458. close_connection(conn);
  10459. }
  10460. }
  10461. /* Signal master that we're done with connection and exiting */
  10462. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10463. ctx->running_worker_threads--;
  10464. (void)pthread_cond_signal(&ctx->thread_cond);
  10465. /* assert(ctx->running_worker_threads >= 0); */
  10466. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10467. pthread_setspecific(sTlsKey, NULL);
  10468. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10469. CloseHandle(tls.pthread_cond_helper_mutex);
  10470. #endif
  10471. pthread_mutex_destroy(&conn->mutex);
  10472. mg_free(conn);
  10473. DEBUG_TRACE("%s", "exiting");
  10474. return NULL;
  10475. }
  10476. /* Threads have different return types on Windows and Unix. */
  10477. #ifdef _WIN32
  10478. static unsigned __stdcall worker_thread(void *thread_func_param)
  10479. {
  10480. worker_thread_run(thread_func_param);
  10481. return 0;
  10482. }
  10483. #else
  10484. static void *
  10485. worker_thread(void *thread_func_param)
  10486. {
  10487. worker_thread_run(thread_func_param);
  10488. return NULL;
  10489. }
  10490. #endif /* _WIN32 */
  10491. /* Master thread adds accepted socket to a queue */
  10492. static void
  10493. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10494. {
  10495. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10496. if (!ctx) {
  10497. return;
  10498. }
  10499. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10500. /* If the queue is full, wait */
  10501. while (ctx->stop_flag == 0
  10502. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10503. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10504. }
  10505. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10506. /* Copy socket to the queue and increment head */
  10507. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10508. ctx->sq_head++;
  10509. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10510. }
  10511. (void)pthread_cond_signal(&ctx->sq_full);
  10512. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10513. #undef QUEUE_SIZE
  10514. }
  10515. static void
  10516. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10517. {
  10518. struct socket so;
  10519. char src_addr[IP_ADDR_STR_LEN];
  10520. socklen_t len = sizeof(so.rsa);
  10521. int on = 1;
  10522. int timeout;
  10523. if (!listener) {
  10524. return;
  10525. }
  10526. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10527. == INVALID_SOCKET) {
  10528. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10529. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10530. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10531. closesocket(so.sock);
  10532. so.sock = INVALID_SOCKET;
  10533. } else {
  10534. /* Put so socket structure into the queue */
  10535. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10536. set_close_on_exec(so.sock, fc(ctx));
  10537. so.is_ssl = listener->is_ssl;
  10538. so.ssl_redir = listener->ssl_redir;
  10539. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10540. mg_cry(fc(ctx),
  10541. "%s: getsockname() failed: %s",
  10542. __func__,
  10543. strerror(ERRNO));
  10544. }
  10545. /* Set TCP keep-alive. This is needed because if HTTP-level
  10546. * keep-alive
  10547. * is enabled, and client resets the connection, server won't get
  10548. * TCP FIN or RST and will keep the connection open forever. With
  10549. * TCP keep-alive, next keep-alive handshake will figure out that
  10550. * the client is down and will close the server end.
  10551. * Thanks to Igor Klopov who suggested the patch. */
  10552. if (setsockopt(so.sock,
  10553. SOL_SOCKET,
  10554. SO_KEEPALIVE,
  10555. (SOCK_OPT_TYPE)&on,
  10556. sizeof(on)) != 0) {
  10557. mg_cry(fc(ctx),
  10558. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10559. __func__,
  10560. strerror(ERRNO));
  10561. }
  10562. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  10563. * to effectively fill up the underlying IP packet payload and reduce
  10564. * the overhead of sending lots of small buffers. However this hurts
  10565. * the server's throughput (ie. operations per second) when HTTP 1.1
  10566. * persistent connections are used and the responses are relatively
  10567. * small (eg. less than 1400 bytes).
  10568. */
  10569. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10570. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10571. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10572. mg_cry(fc(ctx),
  10573. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10574. __func__,
  10575. strerror(ERRNO));
  10576. }
  10577. }
  10578. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10579. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10580. } else {
  10581. timeout = -1;
  10582. }
  10583. /* Set socket timeout to the given value, but not more than a
  10584. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10585. * so the server can exit after that time if requested. */
  10586. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10587. set_sock_timeout(so.sock, timeout);
  10588. } else {
  10589. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10590. }
  10591. produce_socket(ctx, &so);
  10592. }
  10593. }
  10594. static void
  10595. master_thread_run(void *thread_func_param)
  10596. {
  10597. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10598. struct mg_workerTLS tls;
  10599. struct pollfd *pfd;
  10600. unsigned int i;
  10601. unsigned int workerthreadcount;
  10602. if (!ctx) {
  10603. return;
  10604. }
  10605. mg_set_thread_name("master");
  10606. /* Increase priority of the master thread */
  10607. #if defined(_WIN32)
  10608. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10609. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10610. int min_prio = sched_get_priority_min(SCHED_RR);
  10611. int max_prio = sched_get_priority_max(SCHED_RR);
  10612. if ((min_prio >= 0) && (max_prio >= 0)
  10613. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10614. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10615. struct sched_param sched_param = {0};
  10616. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10617. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10618. }
  10619. #endif
  10620. /* Initialize thread local storage */
  10621. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10622. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10623. #endif
  10624. tls.is_master = 1;
  10625. pthread_setspecific(sTlsKey, &tls);
  10626. /* Server starts *now* */
  10627. ctx->start_time = time(NULL);
  10628. /* Allocate memory for the listening sockets, and start the server */
  10629. pfd =
  10630. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10631. while (pfd != NULL && ctx->stop_flag == 0) {
  10632. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10633. pfd[i].fd = ctx->listening_sockets[i].sock;
  10634. pfd[i].events = POLLIN;
  10635. }
  10636. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10637. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10638. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10639. * successful poll, and POLLIN is defined as
  10640. * (POLLRDNORM | POLLRDBAND)
  10641. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10642. * pfd[i].revents == POLLIN. */
  10643. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10644. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10645. }
  10646. }
  10647. }
  10648. }
  10649. mg_free(pfd);
  10650. DEBUG_TRACE("%s", "stopping workers");
  10651. /* Stop signal received: somebody called mg_stop. Quit. */
  10652. close_all_listening_sockets(ctx);
  10653. /* Wakeup workers that are waiting for connections to handle. */
  10654. pthread_cond_broadcast(&ctx->sq_full);
  10655. /* Wait until all threads finish */
  10656. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10657. while (ctx->running_worker_threads > 0) {
  10658. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10659. }
  10660. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10661. /* Join all worker threads to avoid leaking threads. */
  10662. workerthreadcount = ctx->cfg_worker_threads;
  10663. for (i = 0; i < workerthreadcount; i++) {
  10664. if (ctx->workerthreadids[i] != 0) {
  10665. mg_join_thread(ctx->workerthreadids[i]);
  10666. }
  10667. }
  10668. #if !defined(NO_SSL)
  10669. if (ctx->ssl_ctx != NULL) {
  10670. uninitialize_ssl(ctx);
  10671. }
  10672. #endif
  10673. DEBUG_TRACE("%s", "exiting");
  10674. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10675. CloseHandle(tls.pthread_cond_helper_mutex);
  10676. #endif
  10677. pthread_setspecific(sTlsKey, NULL);
  10678. /* Signal mg_stop() that we're done.
  10679. * WARNING: This must be the very last thing this
  10680. * thread does, as ctx becomes invalid after this line. */
  10681. ctx->stop_flag = 2;
  10682. }
  10683. /* Threads have different return types on Windows and Unix. */
  10684. #ifdef _WIN32
  10685. static unsigned __stdcall master_thread(void *thread_func_param)
  10686. {
  10687. master_thread_run(thread_func_param);
  10688. return 0;
  10689. }
  10690. #else
  10691. static void *
  10692. master_thread(void *thread_func_param)
  10693. {
  10694. master_thread_run(thread_func_param);
  10695. return NULL;
  10696. }
  10697. #endif /* _WIN32 */
  10698. static void
  10699. free_context(struct mg_context *ctx)
  10700. {
  10701. int i;
  10702. struct mg_handler_info *tmp_rh;
  10703. if (ctx == NULL) {
  10704. return;
  10705. }
  10706. if (ctx->callbacks.exit_context) {
  10707. ctx->callbacks.exit_context(ctx);
  10708. }
  10709. /* All threads exited, no sync is needed. Destroy thread mutex and
  10710. * condvars
  10711. */
  10712. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10713. (void)pthread_cond_destroy(&ctx->thread_cond);
  10714. (void)pthread_cond_destroy(&ctx->sq_empty);
  10715. (void)pthread_cond_destroy(&ctx->sq_full);
  10716. /* Destroy other context global data structures mutex */
  10717. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10718. #if defined(USE_TIMERS)
  10719. timers_exit(ctx);
  10720. #endif
  10721. /* Deallocate config parameters */
  10722. for (i = 0; i < NUM_OPTIONS; i++) {
  10723. if (ctx->config[i] != NULL) {
  10724. #if defined(_MSC_VER)
  10725. #pragma warning(suppress : 6001)
  10726. #endif
  10727. mg_free(ctx->config[i]);
  10728. }
  10729. }
  10730. /* Deallocate request handlers */
  10731. while (ctx->handlers) {
  10732. tmp_rh = ctx->handlers;
  10733. ctx->handlers = tmp_rh->next;
  10734. mg_free(tmp_rh->uri);
  10735. mg_free(tmp_rh);
  10736. }
  10737. #ifndef NO_SSL
  10738. /* Deallocate SSL context */
  10739. if (ctx->ssl_ctx != NULL) {
  10740. SSL_CTX_free(ctx->ssl_ctx);
  10741. }
  10742. if (ssl_mutexes != NULL) {
  10743. mg_free(ssl_mutexes);
  10744. ssl_mutexes = NULL;
  10745. }
  10746. #endif /* !NO_SSL */
  10747. /* Deallocate worker thread ID array */
  10748. if (ctx->workerthreadids != NULL) {
  10749. mg_free(ctx->workerthreadids);
  10750. }
  10751. /* Deallocate the tls variable */
  10752. if (mg_atomic_dec(&sTlsInit) == 0) {
  10753. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10754. DeleteCriticalSection(&global_log_file_lock);
  10755. #endif /* _WIN32 && !__SYMBIAN32__ */
  10756. #if !defined(_WIN32)
  10757. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10758. #endif
  10759. pthread_key_delete(sTlsKey);
  10760. }
  10761. /* deallocate system name string */
  10762. mg_free(ctx->systemName);
  10763. /* Deallocate context itself */
  10764. mg_free(ctx);
  10765. }
  10766. void
  10767. mg_stop(struct mg_context *ctx)
  10768. {
  10769. pthread_t mt;
  10770. if (!ctx) {
  10771. return;
  10772. }
  10773. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10774. * two threads is not allowed. */
  10775. mt = ctx->masterthreadid;
  10776. if (mt == 0) {
  10777. return;
  10778. }
  10779. ctx->masterthreadid = 0;
  10780. ctx->stop_flag = 1;
  10781. /* Wait until mg_fini() stops */
  10782. while (ctx->stop_flag != 2) {
  10783. (void)mg_sleep(10);
  10784. }
  10785. mg_join_thread(mt);
  10786. free_context(ctx);
  10787. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10788. (void)WSACleanup();
  10789. #endif /* _WIN32 && !__SYMBIAN32__ */
  10790. }
  10791. static void
  10792. get_system_name(char **sysName)
  10793. {
  10794. #if defined(_WIN32)
  10795. #if !defined(__SYMBIAN32__)
  10796. char name[128];
  10797. DWORD dwVersion = 0;
  10798. DWORD dwMajorVersion = 0;
  10799. DWORD dwMinorVersion = 0;
  10800. DWORD dwBuild = 0;
  10801. #ifdef _MSC_VER
  10802. #pragma warning(push)
  10803. // GetVersion was declared deprecated
  10804. #pragma warning(disable : 4996)
  10805. #endif
  10806. dwVersion = GetVersion();
  10807. #ifdef _MSC_VER
  10808. #pragma warning(pop)
  10809. #endif
  10810. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10811. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10812. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10813. (void)dwBuild;
  10814. sprintf(name,
  10815. "Windows %u.%u",
  10816. (unsigned)dwMajorVersion,
  10817. (unsigned)dwMinorVersion);
  10818. *sysName = mg_strdup(name);
  10819. #else
  10820. *sysName = mg_strdup("Symbian");
  10821. #endif
  10822. #else
  10823. struct utsname name;
  10824. memset(&name, 0, sizeof(name));
  10825. uname(&name);
  10826. *sysName = mg_strdup(name.sysname);
  10827. #endif
  10828. }
  10829. struct mg_context *
  10830. mg_start(const struct mg_callbacks *callbacks,
  10831. void *user_data,
  10832. const char **options)
  10833. {
  10834. struct mg_context *ctx;
  10835. const char *name, *value, *default_value;
  10836. int idx, ok, workerthreadcount;
  10837. unsigned int i;
  10838. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10839. struct mg_workerTLS tls;
  10840. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10841. WSADATA data;
  10842. WSAStartup(MAKEWORD(2, 2), &data);
  10843. #endif /* _WIN32 && !__SYMBIAN32__ */
  10844. /* Allocate context and initialize reasonable general case defaults. */
  10845. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10846. return NULL;
  10847. }
  10848. /* Random number generator will initialize at the first call */
  10849. ctx->auth_nonce_mask =
  10850. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10851. if (mg_atomic_inc(&sTlsInit) == 1) {
  10852. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10853. InitializeCriticalSection(&global_log_file_lock);
  10854. #endif /* _WIN32 && !__SYMBIAN32__ */
  10855. #if !defined(_WIN32)
  10856. pthread_mutexattr_init(&pthread_mutex_attr);
  10857. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10858. #endif
  10859. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10860. /* Fatal error - abort start. However, this situation should
  10861. * never
  10862. * occur in practice. */
  10863. mg_atomic_dec(&sTlsInit);
  10864. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10865. mg_free(ctx);
  10866. return NULL;
  10867. }
  10868. } else {
  10869. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10870. * initialized. */
  10871. mg_sleep(1);
  10872. }
  10873. tls.is_master = -1;
  10874. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10875. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10876. tls.pthread_cond_helper_mutex = NULL;
  10877. #endif
  10878. pthread_setspecific(sTlsKey, &tls);
  10879. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10880. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10881. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10882. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10883. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10884. if (!ok) {
  10885. /* Fatal error - abort start. However, this situation should never
  10886. * occur in practice. */
  10887. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10888. mg_free(ctx);
  10889. pthread_setspecific(sTlsKey, NULL);
  10890. return NULL;
  10891. }
  10892. if (callbacks) {
  10893. ctx->callbacks = *callbacks;
  10894. exit_callback = callbacks->exit_context;
  10895. ctx->callbacks.exit_context = 0;
  10896. }
  10897. ctx->user_data = user_data;
  10898. ctx->handlers = NULL;
  10899. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10900. ctx->shared_lua_websockets = 0;
  10901. #endif
  10902. while (options && (name = *options++) != NULL) {
  10903. if ((idx = get_option_index(name)) == -1) {
  10904. mg_cry(fc(ctx), "Invalid option: %s", name);
  10905. free_context(ctx);
  10906. pthread_setspecific(sTlsKey, NULL);
  10907. return NULL;
  10908. } else if ((value = *options++) == NULL) {
  10909. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10910. free_context(ctx);
  10911. pthread_setspecific(sTlsKey, NULL);
  10912. return NULL;
  10913. }
  10914. if (ctx->config[idx] != NULL) {
  10915. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10916. mg_free(ctx->config[idx]);
  10917. }
  10918. ctx->config[idx] = mg_strdup(value);
  10919. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10920. }
  10921. /* Set default value if needed */
  10922. for (i = 0; config_options[i].name != NULL; i++) {
  10923. default_value = config_options[i].default_value;
  10924. if (ctx->config[i] == NULL && default_value != NULL) {
  10925. ctx->config[i] = mg_strdup(default_value);
  10926. }
  10927. }
  10928. #if defined(NO_FILES)
  10929. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  10930. mg_cry(fc(ctx), "%s", "Document root must not be set");
  10931. free_context(ctx);
  10932. pthread_setspecific(sTlsKey, NULL);
  10933. return NULL;
  10934. }
  10935. #endif
  10936. get_system_name(&ctx->systemName);
  10937. /* NOTE(lsm): order is important here. SSL certificates must
  10938. * be initialized before listening ports. UID must be set last. */
  10939. if (!set_gpass_option(ctx) ||
  10940. #if !defined(NO_SSL)
  10941. !set_ssl_option(ctx) ||
  10942. #endif
  10943. !set_ports_option(ctx) ||
  10944. #if !defined(_WIN32)
  10945. !set_uid_option(ctx) ||
  10946. #endif
  10947. !set_acl_option(ctx)) {
  10948. free_context(ctx);
  10949. pthread_setspecific(sTlsKey, NULL);
  10950. return NULL;
  10951. }
  10952. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  10953. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  10954. * won't kill the whole process. */
  10955. (void)signal(SIGPIPE, SIG_IGN);
  10956. #endif /* !_WIN32 && !__SYMBIAN32__ */
  10957. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  10958. if (workerthreadcount > MAX_WORKER_THREADS) {
  10959. mg_cry(fc(ctx), "Too many worker threads");
  10960. free_context(ctx);
  10961. pthread_setspecific(sTlsKey, NULL);
  10962. return NULL;
  10963. }
  10964. if (workerthreadcount > 0) {
  10965. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  10966. ctx->workerthreadids =
  10967. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  10968. if (ctx->workerthreadids == NULL) {
  10969. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  10970. free_context(ctx);
  10971. pthread_setspecific(sTlsKey, NULL);
  10972. return NULL;
  10973. }
  10974. }
  10975. #if defined(USE_TIMERS)
  10976. if (timers_init(ctx) != 0) {
  10977. mg_cry(fc(ctx), "Error creating timers");
  10978. free_context(ctx);
  10979. pthread_setspecific(sTlsKey, NULL);
  10980. return NULL;
  10981. }
  10982. #endif
  10983. /* Context has been created - init user libraries */
  10984. if (ctx->callbacks.init_context) {
  10985. ctx->callbacks.init_context(ctx);
  10986. }
  10987. ctx->callbacks.exit_context = exit_callback;
  10988. ctx->context_type = 1; /* server context */
  10989. /* Start master (listening) thread */
  10990. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  10991. /* Start worker threads */
  10992. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10993. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10994. ctx->running_worker_threads++;
  10995. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10996. if (mg_start_thread_with_id(worker_thread,
  10997. ctx,
  10998. &ctx->workerthreadids[i]) != 0) {
  10999. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11000. ctx->running_worker_threads--;
  11001. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11002. if (i > 0) {
  11003. mg_cry(fc(ctx),
  11004. "Cannot start worker thread %i: error %ld",
  11005. i + 1,
  11006. (long)ERRNO);
  11007. } else {
  11008. mg_cry(fc(ctx),
  11009. "Cannot create threads: error %ld",
  11010. (long)ERRNO);
  11011. free_context(ctx);
  11012. pthread_setspecific(sTlsKey, NULL);
  11013. return NULL;
  11014. }
  11015. break;
  11016. }
  11017. }
  11018. pthread_setspecific(sTlsKey, NULL);
  11019. return ctx;
  11020. }
  11021. /* Feature check API function */
  11022. unsigned
  11023. mg_check_feature(unsigned feature)
  11024. {
  11025. static const unsigned feature_set = 0
  11026. /* Set bits for available features according to API documentation.
  11027. * This bit mask is created at compile time, according to the active
  11028. * preprocessor defines. It is a single const value at runtime. */
  11029. #if !defined(NO_FILES)
  11030. | 1
  11031. #endif
  11032. #if !defined(NO_SSL)
  11033. | 2
  11034. #endif
  11035. #if !defined(NO_CGI)
  11036. | 4
  11037. #endif
  11038. #if defined(USE_IPV6)
  11039. | 8
  11040. #endif
  11041. #if defined(USE_WEBSOCKET)
  11042. | 16
  11043. #endif
  11044. #if defined(USE_LUA)
  11045. | 32
  11046. #endif
  11047. #if defined(USE_DUKTAPE)
  11048. | 64
  11049. #endif
  11050. /* Set some extra bits not defined in the API documentation.
  11051. * These bits may change without further notice. */
  11052. #if defined(MG_LEGACY_INTERFACE)
  11053. | 128
  11054. #endif
  11055. #if defined(MEMORY_DEBUGGING)
  11056. | 256
  11057. #endif
  11058. #if defined(USE_TIMERS)
  11059. | 512
  11060. #endif
  11061. #if !defined(NO_NONCE_CHECK)
  11062. | 1024
  11063. #endif
  11064. #if !defined(NO_POPEN)
  11065. | 2048
  11066. #endif
  11067. ;
  11068. return (feature & feature_set);
  11069. }