civetweb.c 275 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054
  1. /* Copyright (c) 2013-2015 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. #ifdef __linux__
  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(_MSC_VER)
  54. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  55. #pragma warning(disable : 4306)
  56. /* conditional expression is constant: introduced by FD_SET(..) */
  57. #pragma warning(disable : 4127)
  58. /* non-constant aggregate initializer: issued due to missing C99 support */
  59. #pragma warning(disable : 4204)
  60. /* padding added after data member */
  61. #pragma warning(disable : 4820)
  62. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  63. #pragma warning(disable : 4668)
  64. /* no function prototype given: converting '()' to '(void)' */
  65. #pragma warning(disable : 4255)
  66. /* function has been selected for automatic inline expansion */
  67. #pragma warning(disable : 4711)
  68. #endif
  69. /* This code uses static_assert to check some conditions.
  70. * Unfortunately some compilers still do not support it, so we have a
  71. * replacement function here. */
  72. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  73. #define mg_static_assert static_assert
  74. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  75. #define mg_static_assert static_assert
  76. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  77. #define mg_static_assert _Static_assert
  78. #else
  79. char static_assert_replacement[1];
  80. #define mg_static_assert(cond, txt) \
  81. extern char static_assert_replacement[(cond) ? 1 : -1]
  82. #endif
  83. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  84. "int data type size check");
  85. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  86. "pointer data type size check");
  87. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  88. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  89. * type size check"); */
  90. /* DTL -- including winsock2.h works better if lean and mean */
  91. #ifndef WIN32_LEAN_AND_MEAN
  92. #define WIN32_LEAN_AND_MEAN
  93. #endif
  94. #if defined(__SYMBIAN32__)
  95. #define NO_SSL /* SSL is not supported */
  96. #define NO_CGI /* CGI is not supported */
  97. #define PATH_MAX FILENAME_MAX
  98. #endif /* __SYMBIAN32__ */
  99. #ifndef IGNORE_UNUSED_RESULT
  100. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  101. #endif
  102. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  103. #include <sys/types.h>
  104. #include <sys/stat.h>
  105. #include <errno.h>
  106. #include <signal.h>
  107. #include <fcntl.h>
  108. #endif /* !_WIN32_WCE */
  109. #ifdef __MACH__
  110. #define CLOCK_MONOTONIC (1)
  111. #define CLOCK_REALTIME (2)
  112. #include <sys/time.h>
  113. #include <mach/clock.h>
  114. #include <mach/mach.h>
  115. #include <mach/mach_time.h>
  116. #include <assert.h>
  117. /* clock_gettime is not implemented on OSX */
  118. int clock_gettime(int clk_id, struct timespec *t);
  119. int clock_gettime(int clk_id, struct timespec *t)
  120. {
  121. if (clk_id == CLOCK_REALTIME) {
  122. struct timeval now;
  123. int rv = gettimeofday(&now, NULL);
  124. if (rv)
  125. return rv;
  126. t->tv_sec = now.tv_sec;
  127. t->tv_nsec = now.tv_usec * 1000;
  128. return 0;
  129. } else if (clk_id == CLOCK_MONOTONIC) {
  130. static uint64_t start_time = 0;
  131. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  132. uint64_t now = mach_absolute_time();
  133. if (start_time == 0) {
  134. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  135. #if defined(DEBUG)
  136. assert(mach_status == KERN_SUCCESS);
  137. #else
  138. /* appease "unused variable" warning for release builds */
  139. (void)mach_status;
  140. #endif
  141. start_time = now;
  142. }
  143. now =
  144. (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer /
  145. (double)timebase_ifo.denom);
  146. t->tv_sec = now / 1000000000;
  147. t->tv_nsec = now % 1000000000;
  148. return 0;
  149. }
  150. return -1; /* EINVAL - Clock ID is unknown */
  151. }
  152. #endif
  153. #include <time.h>
  154. #include <stdlib.h>
  155. #include <stdarg.h>
  156. #include <assert.h>
  157. #include <string.h>
  158. #include <ctype.h>
  159. #include <limits.h>
  160. #include <stddef.h>
  161. #include <stdio.h>
  162. #ifndef MAX_WORKER_THREADS
  163. #define MAX_WORKER_THREADS (1024 * 64)
  164. #endif
  165. #ifndef SOCKET_TIMEOUT_QUANTUM
  166. #define SOCKET_TIMEOUT_QUANTUM (10000)
  167. #endif
  168. mg_static_assert(MAX_WORKER_THREADS >= 1,
  169. "worker threads must be a positive number");
  170. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  171. #include <windows.h>
  172. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  173. #include <ws2tcpip.h>
  174. typedef const char *SOCK_OPT_TYPE;
  175. #if !defined(PATH_MAX)
  176. #define PATH_MAX (MAX_PATH)
  177. #endif
  178. #if !defined(PATH_MAX)
  179. #define PATH_MAX (4096)
  180. #endif
  181. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  182. #ifndef _IN_PORT_T
  183. #ifndef in_port_t
  184. #define in_port_t u_short
  185. #endif
  186. #endif
  187. #ifndef _WIN32_WCE
  188. #include <process.h>
  189. #include <direct.h>
  190. #include <io.h>
  191. #else /* _WIN32_WCE */
  192. #define NO_CGI /* WinCE has no pipes */
  193. typedef long off_t;
  194. #define errno ((int)(GetLastError()))
  195. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  196. #endif /* _WIN32_WCE */
  197. #define MAKEUQUAD(lo, hi) \
  198. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  199. #define RATE_DIFF (10000000) /* 100 nsecs */
  200. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  201. #define SYS2UNIX_TIME(lo, hi) \
  202. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  203. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  204. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  205. * Also use _strtoui64 on modern M$ compilers */
  206. #if defined(_MSC_VER)
  207. #if (_MSC_VER < 1300)
  208. #define STRX(x) #x
  209. #define STR(x) STRX(x)
  210. #define __func__ __FILE__ ":" STR(__LINE__)
  211. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  212. #define strtoll(x, y, z) (_atoi64(x))
  213. #else
  214. #define __func__ __FUNCTION__
  215. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  216. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  217. #endif
  218. #endif /* _MSC_VER */
  219. #define ERRNO ((int)(GetLastError()))
  220. #define NO_SOCKLEN_T
  221. #define SSL_LIB "ssleay32.dll"
  222. #define CRYPTO_LIB "libeay32.dll"
  223. #define O_NONBLOCK (0)
  224. #ifndef W_OK
  225. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  226. #endif
  227. #if !defined(EWOULDBLOCK)
  228. #define EWOULDBLOCK WSAEWOULDBLOCK
  229. #endif /* !EWOULDBLOCK */
  230. #define _POSIX_
  231. #define INT64_FMT "I64d"
  232. #define WINCDECL __cdecl
  233. #define SHUT_RD (0)
  234. #define SHUT_WR (1)
  235. #define SHUT_BOTH (2)
  236. #define snprintf _snprintf
  237. #define vsnprintf _vsnprintf
  238. #define access _access
  239. #define mg_sleep(x) (Sleep(x))
  240. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  241. #ifndef popen
  242. #define popen(x, y) (_popen(x, y))
  243. #endif
  244. #ifndef pclose
  245. #define pclose(x) (_pclose(x))
  246. #endif
  247. #define close(x) (_close(x))
  248. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  249. #define RTLD_LAZY (0)
  250. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)))
  251. #define fdopen(x, y) (_fdopen((x), (y)))
  252. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  253. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  254. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  255. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  256. #define sleep(x) (Sleep((x)*1000))
  257. #define rmdir(x) (_rmdir(x))
  258. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  259. #define USE_TIMERS
  260. #endif
  261. #if !defined(fileno)
  262. #define fileno(x) (_fileno(x))
  263. #endif /* !fileno MINGW #defines fileno */
  264. typedef HANDLE pthread_mutex_t;
  265. typedef DWORD pthread_key_t;
  266. typedef HANDLE pthread_t;
  267. typedef struct {
  268. CRITICAL_SECTION threadIdSec;
  269. int waitingthreadcount; /* The number of threads queued. */
  270. pthread_t *waitingthreadhdls; /* The thread handles. */
  271. } pthread_cond_t;
  272. #ifndef __clockid_t_defined
  273. typedef DWORD clockid_t;
  274. #endif
  275. #ifndef CLOCK_MONOTONIC
  276. #define CLOCK_MONOTONIC (1)
  277. #endif
  278. #ifndef CLOCK_REALTIME
  279. #define CLOCK_REALTIME (2)
  280. #endif
  281. #ifndef _TIMESPEC_DEFINED
  282. struct timespec {
  283. time_t tv_sec; /* seconds */
  284. long tv_nsec; /* nanoseconds */
  285. };
  286. #endif
  287. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  288. static int pthread_mutex_lock(pthread_mutex_t *);
  289. static int pthread_mutex_unlock(pthread_mutex_t *);
  290. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  291. struct file;
  292. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  293. #if defined(HAVE_STDINT)
  294. #include <stdint.h>
  295. #else
  296. typedef unsigned int uint32_t;
  297. typedef unsigned short uint16_t;
  298. typedef unsigned __int64 uint64_t;
  299. typedef __int64 int64_t;
  300. #define INT64_MAX (9223372036854775807)
  301. #endif /* HAVE_STDINT */
  302. /* POSIX dirent interface */
  303. struct dirent {
  304. char d_name[PATH_MAX];
  305. };
  306. typedef struct DIR {
  307. HANDLE handle;
  308. WIN32_FIND_DATAW info;
  309. struct dirent result;
  310. } DIR;
  311. #if defined(_WIN32) && !defined(POLLIN)
  312. #ifndef HAVE_POLL
  313. struct pollfd {
  314. SOCKET fd;
  315. short events;
  316. short revents;
  317. };
  318. #define POLLIN (0x0300)
  319. #endif
  320. #endif
  321. /* Mark required libraries */
  322. #if defined(_MSC_VER)
  323. #pragma comment(lib, "Ws2_32.lib")
  324. #endif
  325. #else /* UNIX specific */
  326. #include <sys/wait.h>
  327. #include <sys/socket.h>
  328. #include <sys/poll.h>
  329. #include <netinet/in.h>
  330. #include <arpa/inet.h>
  331. #include <sys/time.h>
  332. #include <sys/utsname.h>
  333. #include <stdint.h>
  334. #include <inttypes.h>
  335. #include <netdb.h>
  336. typedef const void *SOCK_OPT_TYPE;
  337. #if defined(ANDROID)
  338. typedef unsigned short int in_port_t;
  339. #endif
  340. #include <pwd.h>
  341. #include <unistd.h>
  342. #include <grp.h>
  343. #include <dirent.h>
  344. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  345. #include <dlfcn.h>
  346. #endif
  347. #include <pthread.h>
  348. #if defined(__MACH__)
  349. #define SSL_LIB "libssl.dylib"
  350. #define CRYPTO_LIB "libcrypto.dylib"
  351. #else
  352. #if !defined(SSL_LIB)
  353. #define SSL_LIB "libssl.so"
  354. #endif
  355. #if !defined(CRYPTO_LIB)
  356. #define CRYPTO_LIB "libcrypto.so"
  357. #endif
  358. #endif
  359. #ifndef O_BINARY
  360. #define O_BINARY (0)
  361. #endif /* O_BINARY */
  362. #define closesocket(a) (close(a))
  363. #define mg_mkdir(x, y) (mkdir(x, y))
  364. #define mg_remove(x) (remove(x))
  365. #define mg_sleep(x) (usleep((x)*1000))
  366. #define ERRNO (errno)
  367. #define INVALID_SOCKET (-1)
  368. #define INT64_FMT PRId64
  369. typedef int SOCKET;
  370. #define WINCDECL
  371. #if defined(__hpux)
  372. /* HPUX 11 does not have monotonic, fall back to realtime */
  373. #ifndef CLOCK_MONOTONIC
  374. #define CLOCK_MONOTONIC CLOCK_REALTIME
  375. #endif
  376. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  377. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  378. * the prototypes use int* rather than socklen_t* which matches the
  379. * actual library expectation. When called with the wrong size arg
  380. * accept() returns a zero client inet addr and check_acl() always
  381. * fails. Since socklen_t is widely used below, just force replace
  382. * their typedef with int. - DTL
  383. */
  384. #define socklen_t int
  385. #endif /* hpux */
  386. #endif /* End of Windows and UNIX specific includes */
  387. /* va_copy should always be a macro, C99 and C++11 - DTL */
  388. #ifndef va_copy
  389. #define va_copy(x, y) ((x) = (y))
  390. #endif
  391. #ifdef _WIN32
  392. static CRITICAL_SECTION global_log_file_lock;
  393. static DWORD pthread_self(void) { return GetCurrentThreadId(); }
  394. static int pthread_key_create(
  395. pthread_key_t *key,
  396. void (*_must_be_zero)(
  397. void *) /* destructor function not supported for windows */)
  398. {
  399. assert(_must_be_zero == NULL);
  400. if ((key != 0) && (_must_be_zero == NULL)) {
  401. *key = TlsAlloc();
  402. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  403. }
  404. return -2;
  405. }
  406. static int pthread_key_delete(pthread_key_t key)
  407. {
  408. return TlsFree(key) ? 0 : 1;
  409. }
  410. static int pthread_setspecific(pthread_key_t key, void *value)
  411. {
  412. return TlsSetValue(key, value) ? 0 : 1;
  413. }
  414. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  415. static void *pthread_getspecific(pthread_key_t key) { return TlsGetValue(key); }
  416. #endif
  417. #endif /* _WIN32 */
  418. #include "civetweb.h"
  419. #define PASSWORDS_FILE_NAME ".htpasswd"
  420. #define CGI_ENVIRONMENT_SIZE (4096)
  421. #define MAX_CGI_ENVIR_VARS (64)
  422. #define MG_BUF_LEN (8192)
  423. #ifndef MAX_REQUEST_SIZE
  424. #define MAX_REQUEST_SIZE (16384)
  425. #endif
  426. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  427. "request size length must be a positive number");
  428. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  429. #if !defined(DEBUG_TRACE)
  430. #if defined(DEBUG)
  431. static void DEBUG_TRACE_FUNC(const char *func,
  432. unsigned line,
  433. PRINTF_FORMAT_STRING(const char *fmt),
  434. ...) PRINTF_ARGS(3, 4);
  435. static void
  436. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  437. {
  438. va_list args;
  439. flockfile(stdout);
  440. printf("*** %lu.%p.%s.%u: ",
  441. (unsigned long)time(NULL),
  442. (void *)pthread_self(),
  443. func,
  444. line);
  445. va_start(args, fmt);
  446. vprintf(fmt, args);
  447. va_end(args);
  448. putchar('\n');
  449. fflush(stdout);
  450. funlockfile(stdout);
  451. }
  452. #define DEBUG_TRACE(fmt, ...) \
  453. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  454. #else
  455. #define DEBUG_TRACE(fmt, ...) \
  456. do { \
  457. } while (0)
  458. #endif /* DEBUG */
  459. #endif /* DEBUG_TRACE */
  460. #if defined(MEMORY_DEBUGGING)
  461. unsigned long mg_memory_debug_blockCount = 0;
  462. unsigned long mg_memory_debug_totalMemUsed = 0;
  463. static void *mg_malloc_ex(size_t size, const char *file, unsigned line)
  464. {
  465. void *data = malloc(size + sizeof(size_t));
  466. void *memory = 0;
  467. char mallocStr[256];
  468. if (data) {
  469. *(size_t *)data = size;
  470. mg_memory_debug_totalMemUsed += size;
  471. mg_memory_debug_blockCount++;
  472. memory = (void *)(((char *)data) + sizeof(size_t));
  473. }
  474. sprintf(mallocStr,
  475. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  476. memory,
  477. (unsigned long)size,
  478. mg_memory_debug_totalMemUsed,
  479. mg_memory_debug_blockCount,
  480. file,
  481. line);
  482. #if defined(_WIN32)
  483. OutputDebugStringA(mallocStr);
  484. #else
  485. DEBUG_TRACE("%s", mallocStr);
  486. #endif
  487. return memory;
  488. }
  489. static void *
  490. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  491. {
  492. void *data = mg_malloc_ex(size * count, file, line);
  493. if (data)
  494. memset(data, 0, size);
  495. return data;
  496. }
  497. static void mg_free_ex(void *memory, const char *file, unsigned line)
  498. {
  499. char mallocStr[256];
  500. void *data = (void *)(((char *)memory) - sizeof(size_t));
  501. size_t size;
  502. if (memory) {
  503. size = *(size_t *)data;
  504. mg_memory_debug_totalMemUsed -= size;
  505. mg_memory_debug_blockCount--;
  506. sprintf(mallocStr,
  507. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  508. memory,
  509. (unsigned long)size,
  510. mg_memory_debug_totalMemUsed,
  511. mg_memory_debug_blockCount,
  512. file,
  513. line);
  514. #if defined(_WIN32)
  515. OutputDebugStringA(mallocStr);
  516. #else
  517. DEBUG_TRACE("%s", mallocStr);
  518. #endif
  519. free(data);
  520. }
  521. }
  522. static void *
  523. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  524. {
  525. char mallocStr[256];
  526. void *data;
  527. void *_realloc;
  528. size_t oldsize;
  529. if (newsize) {
  530. if (memory) {
  531. data = (void *)(((char *)memory) - sizeof(size_t));
  532. oldsize = *(size_t *)data;
  533. _realloc = realloc(data, newsize + sizeof(size_t));
  534. if (_realloc) {
  535. data = _realloc;
  536. mg_memory_debug_totalMemUsed -= oldsize;
  537. sprintf(mallocStr,
  538. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  539. memory,
  540. (unsigned long)oldsize,
  541. mg_memory_debug_totalMemUsed,
  542. mg_memory_debug_blockCount,
  543. file,
  544. line);
  545. #if defined(_WIN32)
  546. OutputDebugStringA(mallocStr);
  547. #else
  548. DEBUG_TRACE("%s", mallocStr);
  549. #endif
  550. mg_memory_debug_totalMemUsed += newsize;
  551. sprintf(mallocStr,
  552. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  553. memory,
  554. (unsigned long)newsize,
  555. mg_memory_debug_totalMemUsed,
  556. mg_memory_debug_blockCount,
  557. file,
  558. line);
  559. #if defined(_WIN32)
  560. OutputDebugStringA(mallocStr);
  561. #else
  562. DEBUG_TRACE("%s", mallocStr);
  563. #endif
  564. *(size_t *)data = newsize;
  565. data = (void *)(((char *)data) + sizeof(size_t));
  566. } else {
  567. #if defined(_WIN32)
  568. OutputDebugStringA("MEM: realloc failed\n");
  569. #else
  570. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  571. #endif
  572. return _realloc;
  573. }
  574. } else {
  575. data = mg_malloc_ex(newsize, file, line);
  576. }
  577. } else {
  578. data = 0;
  579. mg_free_ex(memory, file, line);
  580. }
  581. return data;
  582. }
  583. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  584. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  585. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  586. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  587. #else
  588. static __inline void *mg_malloc(size_t a) { return malloc(a); }
  589. static __inline void *mg_calloc(size_t a, size_t b) { return calloc(a, b); }
  590. static __inline void *mg_realloc(void *a, size_t b) { return realloc(a, b); }
  591. static __inline void mg_free(void *a) { free(a); }
  592. #endif
  593. /* This following lines are just meant as a reminder to use the mg-functions
  594. * for memory management */
  595. #ifdef malloc
  596. #undef malloc
  597. #endif
  598. #ifdef calloc
  599. #undef calloc
  600. #endif
  601. #ifdef realloc
  602. #undef realloc
  603. #endif
  604. #ifdef free
  605. #undef free
  606. #endif
  607. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  608. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  609. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  610. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  611. #define MD5_STATIC static
  612. #include "md5.inl"
  613. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  614. #ifdef NO_SOCKLEN_T
  615. typedef int socklen_t;
  616. #endif /* NO_SOCKLEN_T */
  617. #define _DARWIN_UNLIMITED_SELECT
  618. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  619. #if !defined(MSG_NOSIGNAL)
  620. #define MSG_NOSIGNAL (0)
  621. #endif
  622. #if !defined(SOMAXCONN)
  623. #define SOMAXCONN (100)
  624. #endif
  625. /* Size of the accepted socket queue */
  626. #if !defined(MGSQLEN)
  627. #define MGSQLEN (20)
  628. #endif
  629. #if defined(NO_SSL_DL)
  630. #include <openssl/ssl.h>
  631. #include <openssl/err.h>
  632. #else
  633. /* SSL loaded dynamically from DLL.
  634. * I put the prototypes here to be independent from OpenSSL source
  635. * installation. */
  636. typedef struct ssl_st SSL;
  637. typedef struct ssl_method_st SSL_METHOD;
  638. typedef struct ssl_ctx_st SSL_CTX;
  639. struct ssl_func {
  640. const char *name; /* SSL function name */
  641. void (*ptr)(void); /* Function pointer */
  642. };
  643. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  644. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  645. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  646. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  647. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  648. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  649. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  650. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  651. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  652. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  653. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  654. #define SSL_CTX_use_PrivateKey_file \
  655. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  656. #define SSL_CTX_use_certificate_file \
  657. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  658. #define SSL_CTX_set_default_passwd_cb \
  659. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  660. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  661. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  662. #define SSL_CTX_use_certificate_chain_file \
  663. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  664. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  665. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  666. #define SSL_CTX_set_verify (*(void (*)(SSL_CTX *, int, int))ssl_sw[19].ptr)
  667. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  668. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  669. #define CRYPTO_set_locking_callback \
  670. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  671. #define CRYPTO_set_id_callback \
  672. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  673. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  674. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  675. /* set_ssl_option() function updates this array.
  676. * It loads SSL library dynamically and changes NULLs to the actual addresses
  677. * of respective functions. The macros above (like SSL_connect()) are really
  678. * just calling these functions indirectly via the pointer. */
  679. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  680. {"SSL_accept", NULL},
  681. {"SSL_connect", NULL},
  682. {"SSL_read", NULL},
  683. {"SSL_write", NULL},
  684. {"SSL_get_error", NULL},
  685. {"SSL_set_fd", NULL},
  686. {"SSL_new", NULL},
  687. {"SSL_CTX_new", NULL},
  688. {"SSLv23_server_method", NULL},
  689. {"SSL_library_init", NULL},
  690. {"SSL_CTX_use_PrivateKey_file", NULL},
  691. {"SSL_CTX_use_certificate_file", NULL},
  692. {"SSL_CTX_set_default_passwd_cb", NULL},
  693. {"SSL_CTX_free", NULL},
  694. {"SSL_load_error_strings", NULL},
  695. {"SSL_CTX_use_certificate_chain_file", NULL},
  696. {"SSLv23_client_method", NULL},
  697. {"SSL_pending", NULL},
  698. {"SSL_CTX_set_verify", NULL},
  699. {"SSL_shutdown", NULL},
  700. {NULL, NULL}};
  701. /* Similar array as ssl_sw. These functions could be located in different
  702. * lib. */
  703. #if !defined(NO_SSL)
  704. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  705. {"CRYPTO_set_locking_callback", NULL},
  706. {"CRYPTO_set_id_callback", NULL},
  707. {"ERR_get_error", NULL},
  708. {"ERR_error_string", NULL},
  709. {NULL, NULL}};
  710. #endif /* NO_SSL */
  711. #endif /* NO_SSL_DL */
  712. static const char *month_names[] = {"Jan",
  713. "Feb",
  714. "Mar",
  715. "Apr",
  716. "May",
  717. "Jun",
  718. "Jul",
  719. "Aug",
  720. "Sep",
  721. "Oct",
  722. "Nov",
  723. "Dec"};
  724. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  725. * union u. */
  726. union usa {
  727. struct sockaddr sa;
  728. struct sockaddr_in sin;
  729. #if defined(USE_IPV6)
  730. struct sockaddr_in6 sin6;
  731. #endif
  732. };
  733. /* Describes a string (chunk of memory). */
  734. struct vec {
  735. const char *ptr;
  736. size_t len;
  737. };
  738. struct file {
  739. int is_directory;
  740. time_t modification_time;
  741. uint64_t size;
  742. FILE *fp;
  743. const char *membuf; /* Non-NULL if file data is in memory */
  744. /* set to 1 if the content is gzipped
  745. * in which case we need a content-encoding: gzip header */
  746. int gzipped;
  747. };
  748. #define STRUCT_FILE_INITIALIZER \
  749. { \
  750. 0, 0, 0, NULL, NULL, 0 \
  751. }
  752. /* Describes listening socket, or socket which was accept()-ed by the master
  753. * thread and queued for future handling by the worker thread. */
  754. struct socket {
  755. SOCKET sock; /* Listening socket */
  756. union usa lsa; /* Local socket address */
  757. union usa rsa; /* Remote socket address */
  758. unsigned char is_ssl; /* Is port SSL-ed */
  759. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  760. * port */
  761. };
  762. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  763. enum {
  764. CGI_EXTENSIONS,
  765. CGI_ENVIRONMENT,
  766. PUT_DELETE_PASSWORDS_FILE,
  767. CGI_INTERPRETER,
  768. PROTECT_URI,
  769. AUTHENTICATION_DOMAIN,
  770. SSI_EXTENSIONS,
  771. THROTTLE,
  772. ACCESS_LOG_FILE,
  773. ENABLE_DIRECTORY_LISTING,
  774. ERROR_LOG_FILE,
  775. GLOBAL_PASSWORDS_FILE,
  776. INDEX_FILES,
  777. ENABLE_KEEP_ALIVE,
  778. ACCESS_CONTROL_LIST,
  779. EXTRA_MIME_TYPES,
  780. LISTENING_PORTS,
  781. DOCUMENT_ROOT,
  782. SSL_CERTIFICATE,
  783. NUM_THREADS,
  784. RUN_AS_USER,
  785. REWRITE,
  786. HIDE_FILES,
  787. REQUEST_TIMEOUT,
  788. #if defined(USE_WEBSOCKET)
  789. WEBSOCKET_TIMEOUT,
  790. #endif
  791. DECODE_URL,
  792. #if defined(USE_LUA)
  793. LUA_PRELOAD_FILE,
  794. LUA_SCRIPT_EXTENSIONS,
  795. LUA_SERVER_PAGE_EXTENSIONS,
  796. #endif
  797. #if defined(USE_WEBSOCKET)
  798. WEBSOCKET_ROOT,
  799. #endif
  800. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  801. LUA_WEBSOCKET_EXTENSIONS,
  802. #endif
  803. ACCESS_CONTROL_ALLOW_ORIGIN,
  804. ERROR_PAGES,
  805. NUM_OPTIONS
  806. };
  807. /* Config option name, config types, default value */
  808. static struct mg_option config_options[] = {
  809. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  810. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  811. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  812. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  813. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  814. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  815. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  816. {"throttle", CONFIG_TYPE_STRING, NULL},
  817. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  818. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  819. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  820. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  821. {"index_files",
  822. CONFIG_TYPE_STRING,
  823. #ifdef USE_LUA
  824. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  825. "index.shtml,index.php"},
  826. #else
  827. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  828. #endif
  829. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  830. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  831. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  832. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  833. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  834. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  835. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  836. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  837. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  838. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  839. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  840. #if defined(USE_WEBSOCKET)
  841. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  842. #endif
  843. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  844. #if defined(USE_LUA)
  845. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  846. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  847. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  848. #endif
  849. #if defined(USE_WEBSOCKET)
  850. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  851. #endif
  852. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  853. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  854. #endif
  855. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  856. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  857. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  858. /* Check if the config_options and the corresponding enum have compatible
  859. * sizes. */
  860. mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) ==
  861. (NUM_OPTIONS + 1),
  862. "config_options and enum not sync");
  863. struct mg_request_handler_info {
  864. /* Name/Pattern of the URI. */
  865. char *uri;
  866. size_t uri_len;
  867. /* URI type: ws/wss (websocket) or http/https (web page). */
  868. int is_websocket_handler;
  869. /* Handler for http/https requests. */
  870. mg_request_handler handler;
  871. /* Handler for ws/wss (websocket) requests. */
  872. mg_websocket_connect_handler connect_handler;
  873. mg_websocket_ready_handler ready_handler;
  874. mg_websocket_data_handler data_handler;
  875. mg_websocket_close_handler close_handler;
  876. /* User supplied argument for the handler function. */
  877. void *cbdata;
  878. /* next request handler in a linked list */
  879. struct mg_request_handler_info *next;
  880. };
  881. struct mg_context {
  882. volatile int stop_flag; /* Should we stop event loop */
  883. SSL_CTX *ssl_ctx; /* SSL context */
  884. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  885. struct mg_callbacks callbacks; /* User-defined callback function */
  886. void *user_data; /* User-defined data */
  887. int context_type; /* 1 = server context, 2 = client context */
  888. struct socket *listening_sockets;
  889. in_port_t *listening_ports;
  890. unsigned int num_listening_sockets;
  891. volatile int num_threads; /* Number of threads */
  892. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  893. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  894. struct socket queue[MGSQLEN]; /* Accepted sockets */
  895. volatile int sq_head; /* Head of the socket queue */
  896. volatile int sq_tail; /* Tail of the socket queue */
  897. pthread_cond_t sq_full; /* Signaled when socket is produced */
  898. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  899. pthread_t masterthreadid; /* The master thread ID */
  900. unsigned int workerthreadcount; /* The amount of worker threads. */
  901. pthread_t *workerthreadids; /* The worker thread IDs */
  902. unsigned long start_time; /* Server start time, used for authentication */
  903. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  904. unsigned long nonce_count; /* Used nonces, used for authentication */
  905. char *systemName; /* What operating system is running */
  906. /* linked list of uri handlers */
  907. struct mg_request_handler_info *request_handlers;
  908. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  909. /* linked list of shared lua websockets */
  910. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  911. #endif
  912. #ifdef USE_TIMERS
  913. struct ttimers *timers;
  914. #endif
  915. };
  916. struct mg_connection {
  917. struct mg_request_info request_info;
  918. struct mg_context *ctx;
  919. SSL *ssl; /* SSL descriptor */
  920. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  921. struct socket client; /* Connected client */
  922. time_t conn_birth_time; /* Time (wall clock) when connection was
  923. * established */
  924. struct timespec req_time; /* Time (since system start) when the request
  925. * was received */
  926. int64_t num_bytes_sent; /* Total bytes sent to client */
  927. int64_t content_len; /* Content-Length header value */
  928. int64_t consumed_content; /* How many bytes of content have been read */
  929. int is_chunked; /* Transfer-encoding is chunked: 0=no, 1=yes:
  930. * data available, 2: all data read */
  931. size_t chunk_remainder; /* Unread data from the last chunk */
  932. char *buf; /* Buffer for received data */
  933. char *path_info; /* PATH_INFO part of the URL */
  934. int must_close; /* 1 if connection must be closed */
  935. int in_error_handler; /* 1 if in handler for user defined error
  936. * pages */
  937. int buf_size; /* Buffer size */
  938. int request_len; /* Size of the request + headers in a buffer */
  939. int data_len; /* Total size of data in a buffer */
  940. int status_code; /* HTTP reply status code, e.g. 200 */
  941. int throttle; /* Throttling, bytes/sec. <= 0 means no
  942. * throttle */
  943. time_t last_throttle_time; /* Last time throttled data was sent */
  944. int64_t last_throttle_bytes; /* Bytes sent this second */
  945. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  946. * atomic transmissions for websockets */
  947. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  948. void *lua_websocket_state; /* Lua_State for a websocket connection */
  949. #endif
  950. };
  951. static pthread_key_t sTlsKey; /* Thread local storage index */
  952. static int sTlsInit = 0;
  953. struct mg_workerTLS {
  954. int is_master;
  955. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  956. HANDLE pthread_cond_helper_mutex;
  957. #endif
  958. };
  959. /* Directory entry */
  960. struct de {
  961. struct mg_connection *conn;
  962. char *file_name;
  963. struct file file;
  964. };
  965. #if defined(USE_WEBSOCKET)
  966. static int is_websocket_protocol(const struct mg_connection *conn);
  967. #else
  968. #define is_websocket_protocol(conn) (0)
  969. #endif
  970. static int mg_atomic_inc(volatile int *addr)
  971. {
  972. int ret;
  973. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  974. /* Depending on the SDK, this function uses either
  975. * (volatile unsigned int *) or (volatile LONG *),
  976. * so whatever you use, the other SDK is likely to raise a warning. */
  977. ret = InterlockedIncrement((volatile long *)addr);
  978. #elif defined(__GNUC__)
  979. ret = __sync_add_and_fetch(addr, 1);
  980. #else
  981. ret = (++(*addr));
  982. #endif
  983. return ret;
  984. }
  985. static int mg_atomic_dec(volatile int *addr)
  986. {
  987. int ret;
  988. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  989. /* Depending on the SDK, this function uses either
  990. * (volatile unsigned int *) or (volatile LONG *),
  991. * so whatever you use, the other SDK is likely to raise a warning. */
  992. ret = InterlockedDecrement((volatile long *)addr);
  993. #elif defined(__GNUC__)
  994. ret = __sync_sub_and_fetch(addr, 1);
  995. #else
  996. ret = (--(*addr));
  997. #endif
  998. return ret;
  999. }
  1000. #if !defined(NO_THREAD_NAME)
  1001. #if defined(_WIN32) && defined(_MSC_VER)
  1002. /* Set the thread name for debugging purposes in Visual Studio
  1003. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1004. */
  1005. #pragma pack(push, 8)
  1006. typedef struct tagTHREADNAME_INFO {
  1007. DWORD dwType; /* Must be 0x1000. */
  1008. LPCSTR szName; /* Pointer to name (in user addr space). */
  1009. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1010. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1011. } THREADNAME_INFO;
  1012. #pragma pack(pop)
  1013. #elif defined(__linux__)
  1014. #include <sys/prctl.h>
  1015. #endif
  1016. static void mg_set_thread_name(const char *name)
  1017. {
  1018. char threadName[16]; /* Max. thread length in Linux/OSX/.. */
  1019. /* TODO (low): use strcpy and strcat instad of snprintf, use server name,
  1020. * don't
  1021. * return */
  1022. if (snprintf(threadName, sizeof(threadName), "civetweb-%s", name) < 0)
  1023. return;
  1024. threadName[sizeof(threadName) - 1] = 0;
  1025. #if defined(_WIN32)
  1026. #if defined(_MSC_VER)
  1027. /* Windows and Visual Studio Compiler */
  1028. __try
  1029. {
  1030. THREADNAME_INFO info;
  1031. info.dwType = 0x1000;
  1032. info.szName = threadName;
  1033. info.dwThreadID = ~0U;
  1034. info.dwFlags = 0;
  1035. RaiseException(0x406D1388,
  1036. 0,
  1037. sizeof(info) / sizeof(ULONG_PTR),
  1038. (ULONG_PTR *)&info);
  1039. }
  1040. __except(EXCEPTION_EXECUTE_HANDLER) {}
  1041. #elif defined(__MINGW32__)
  1042. /* No option known to set thread name for MinGW */
  1043. ;
  1044. #endif
  1045. #elif defined(__linux__)
  1046. /* Linux */
  1047. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1048. #elif defined(__APPLE__) || defined(__MACH__)
  1049. /* OS X (TODO: test) */
  1050. (void)pthread_setname_np(threadName);
  1051. #elif defined(BSD) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1052. /* BSD (TODO: test) */
  1053. pthread_set_name_np(pthread_self(), threadName);
  1054. #elif defined(__AIX__) || defined(_AIX) || defined(__hpux) || defined(__sun)
  1055. /* pthread_set_name_np seems to be missing on AIX, hpux, sun, ... */
  1056. #else
  1057. /* POSIX */
  1058. (void)pthread_setname_np(pthread_self(), threadName);
  1059. #endif
  1060. }
  1061. #else /* !defined(NO_THREAD_NAME) */
  1062. void mg_set_thread_name(const char *threadName) {}
  1063. #endif
  1064. #if defined(MG_LEGACY_INTERFACE)
  1065. const char **mg_get_valid_option_names(void)
  1066. {
  1067. static const char *
  1068. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1069. int i;
  1070. for (i = 0; config_options[i].name != NULL; i++) {
  1071. data[i * 2] = config_options[i].name;
  1072. data[i * 2 + 1] = config_options[i].default_value;
  1073. }
  1074. return data;
  1075. }
  1076. #endif
  1077. const struct mg_option *mg_get_valid_options(void) { return config_options; }
  1078. static int is_file_in_memory(struct mg_connection *conn,
  1079. const char *path,
  1080. struct file *filep)
  1081. {
  1082. size_t size = 0;
  1083. if (!conn || !filep)
  1084. return 0;
  1085. if ((filep->membuf =
  1086. conn->ctx->callbacks.open_file == NULL
  1087. ? NULL
  1088. : conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  1089. /* NOTE: override filep->size only on success. Otherwise, it might
  1090. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1091. filep->size = size;
  1092. }
  1093. return filep->membuf != NULL;
  1094. }
  1095. static int is_file_opened(const struct file *filep)
  1096. {
  1097. if (!filep) {
  1098. return 0;
  1099. }
  1100. return filep->membuf != NULL || filep->fp != NULL;
  1101. }
  1102. static int mg_fopen(struct mg_connection *conn,
  1103. const char *path,
  1104. const char *mode,
  1105. struct file *filep)
  1106. {
  1107. if (!filep) {
  1108. return 0;
  1109. }
  1110. if (!is_file_in_memory(conn, path, filep)) {
  1111. #ifdef _WIN32
  1112. wchar_t wbuf[PATH_MAX], wmode[20];
  1113. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1114. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1115. filep->fp = _wfopen(wbuf, wmode);
  1116. #else
  1117. filep->fp = fopen(path, mode);
  1118. #endif
  1119. }
  1120. return is_file_opened(filep);
  1121. }
  1122. static void mg_fclose(struct file *filep)
  1123. {
  1124. if (filep != NULL && filep->fp != NULL) {
  1125. fclose(filep->fp);
  1126. }
  1127. }
  1128. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  1129. {
  1130. for (; *src != '\0' && n > 1; n--) {
  1131. *dst++ = *src++;
  1132. }
  1133. *dst = '\0';
  1134. }
  1135. static int lowercase(const char *s)
  1136. {
  1137. return tolower(*(const unsigned char *)s);
  1138. }
  1139. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1140. {
  1141. int diff = 0;
  1142. if (len > 0)
  1143. do {
  1144. diff = lowercase(s1++) - lowercase(s2++);
  1145. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1146. return diff;
  1147. }
  1148. static int mg_strcasecmp(const char *s1, const char *s2)
  1149. {
  1150. int diff;
  1151. do {
  1152. diff = lowercase(s1++) - lowercase(s2++);
  1153. } while (diff == 0 && s1[-1] != '\0');
  1154. return diff;
  1155. }
  1156. static char *mg_strndup(const char *ptr, size_t len)
  1157. {
  1158. char *p;
  1159. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1160. mg_strlcpy(p, ptr, len + 1);
  1161. }
  1162. return p;
  1163. }
  1164. static char *mg_strdup(const char *str) { return mg_strndup(str, strlen(str)); }
  1165. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  1166. {
  1167. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1168. if (big_len >= small_len) {
  1169. for (i = 0; i <= (big_len - small_len); i++) {
  1170. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1171. return big_str + i;
  1172. }
  1173. }
  1174. }
  1175. return NULL;
  1176. }
  1177. /* Like snprintf(), but never returns negative value, or a value
  1178. * that is larger than a supplied buffer.
  1179. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  1180. * in his audit report. */
  1181. static int mg_vsnprintf(struct mg_connection *conn,
  1182. char *buf,
  1183. size_t buflen,
  1184. const char *fmt,
  1185. va_list ap)
  1186. {
  1187. int n;
  1188. if (buflen == 0)
  1189. return 0;
  1190. #ifdef __clang__
  1191. #pragma clang diagnostic push
  1192. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1193. /* Using fmt as a non-literal is intended here, since it is mostly called
  1194. * indirectly by mg_snprintf */
  1195. #endif
  1196. n = vsnprintf(buf, buflen, fmt, ap);
  1197. #ifdef __clang__
  1198. #pragma clang diagnostic pop
  1199. #endif
  1200. if (n < 0) {
  1201. mg_cry(conn, "vsnprintf error");
  1202. n = 0;
  1203. } else if (n >= (int)buflen) {
  1204. mg_cry(conn,
  1205. "truncating vsnprintf buffer: [%.*s]",
  1206. n > 200 ? 200 : n,
  1207. buf);
  1208. n = (int)buflen - 1;
  1209. }
  1210. buf[n] = '\0';
  1211. return n;
  1212. }
  1213. static int mg_snprintf(struct mg_connection *conn,
  1214. char *buf,
  1215. size_t buflen,
  1216. PRINTF_FORMAT_STRING(const char *fmt),
  1217. ...) PRINTF_ARGS(4, 5);
  1218. static int mg_snprintf(
  1219. struct mg_connection *conn, char *buf, size_t buflen, const char *fmt, ...)
  1220. {
  1221. va_list ap;
  1222. int n;
  1223. va_start(ap, fmt);
  1224. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  1225. va_end(ap);
  1226. return n;
  1227. }
  1228. static int get_option_index(const char *name)
  1229. {
  1230. int i;
  1231. for (i = 0; config_options[i].name != NULL; i++) {
  1232. if (strcmp(config_options[i].name, name) == 0) {
  1233. return i;
  1234. }
  1235. }
  1236. return -1;
  1237. }
  1238. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  1239. {
  1240. int i;
  1241. if ((i = get_option_index(name)) == -1) {
  1242. return NULL;
  1243. } else if (!ctx || ctx->config[i] == NULL) {
  1244. return "";
  1245. } else {
  1246. return ctx->config[i];
  1247. }
  1248. }
  1249. struct mg_context *mg_get_context(const struct mg_connection *conn)
  1250. {
  1251. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1252. }
  1253. void *mg_get_user_data(const struct mg_context *ctx)
  1254. {
  1255. return (ctx == NULL) ? NULL : ctx->user_data;
  1256. }
  1257. void mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1258. {
  1259. if (conn != NULL) {
  1260. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1261. }
  1262. }
  1263. void *mg_get_user_connection_data(const struct mg_connection *conn)
  1264. {
  1265. if (conn != NULL) {
  1266. return conn->request_info.conn_data;
  1267. }
  1268. return NULL;
  1269. }
  1270. size_t
  1271. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1272. {
  1273. size_t i;
  1274. if (!ctx) {
  1275. return 0;
  1276. }
  1277. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1278. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1279. ports[i] = ctx->listening_ports[i];
  1280. }
  1281. return i;
  1282. }
  1283. static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1284. {
  1285. buf[0] = '\0';
  1286. if (!usa) {
  1287. return;
  1288. }
  1289. if (usa->sa.sa_family == AF_INET) {
  1290. getnameinfo(&usa->sa,
  1291. sizeof(usa->sin),
  1292. buf,
  1293. (unsigned)len,
  1294. NULL,
  1295. 0,
  1296. NI_NUMERICHOST);
  1297. }
  1298. #if defined(USE_IPV6)
  1299. else if (usa->sa.sa_family == AF_INET6) {
  1300. getnameinfo(&usa->sa,
  1301. sizeof(usa->sin6),
  1302. buf,
  1303. (unsigned)len,
  1304. NULL,
  1305. 0,
  1306. NI_NUMERICHOST);
  1307. }
  1308. #endif
  1309. }
  1310. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1311. * included in all responses other than 100, 101, 5xx. */
  1312. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1313. {
  1314. struct tm *tm;
  1315. tm = gmtime(t);
  1316. if (tm != NULL) {
  1317. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1318. } else {
  1319. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1320. buf[buf_len - 1] = '\0';
  1321. }
  1322. }
  1323. /* difftime for struct timespec. Return value is in seconds. */
  1324. static double mg_difftimespec(const struct timespec *ts_now,
  1325. const struct timespec *ts_before)
  1326. {
  1327. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 +
  1328. (double)(ts_now->tv_sec - ts_before->tv_sec);
  1329. }
  1330. /* Print error message to the opened error log stream. */
  1331. void mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1332. {
  1333. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1334. va_list ap;
  1335. FILE *fp;
  1336. time_t timestamp;
  1337. va_start(ap, fmt);
  1338. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  1339. va_end(ap);
  1340. /* Do not lock when getting the callback value, here and below.
  1341. * I suppose this is fine, since function cannot disappear in the
  1342. * same way string option can. */
  1343. if (conn && (conn->ctx->callbacks.log_message == NULL ||
  1344. conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1345. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1346. ? NULL
  1347. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1348. if (fp != NULL) {
  1349. flockfile(fp);
  1350. timestamp = time(NULL);
  1351. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1352. fprintf(fp,
  1353. "[%010lu] [error] [client %s] ",
  1354. (unsigned long)timestamp,
  1355. src_addr);
  1356. if (conn->request_info.request_method != NULL) {
  1357. fprintf(fp,
  1358. "%s %s: ",
  1359. conn->request_info.request_method,
  1360. conn->request_info.uri);
  1361. }
  1362. fprintf(fp, "%s", buf);
  1363. fputc('\n', fp);
  1364. funlockfile(fp);
  1365. fclose(fp);
  1366. }
  1367. }
  1368. }
  1369. /* Return fake connection structure. Used for logging, if connection
  1370. * is not applicable at the moment of logging. */
  1371. static struct mg_connection *fc(struct mg_context *ctx)
  1372. {
  1373. static struct mg_connection fake_connection;
  1374. fake_connection.ctx = ctx;
  1375. return &fake_connection;
  1376. }
  1377. const char *mg_version(void) { return CIVETWEB_VERSION; }
  1378. const struct mg_request_info *
  1379. mg_get_request_info(const struct mg_connection *conn)
  1380. {
  1381. if (!conn) {
  1382. return NULL;
  1383. }
  1384. return &conn->request_info;
  1385. }
  1386. /* Skip the characters until one of the delimiters characters found.
  1387. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1388. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1389. * Delimiters can be quoted with quotechar. */
  1390. static char *skip_quoted(char **buf,
  1391. const char *delimiters,
  1392. const char *whitespace,
  1393. char quotechar)
  1394. {
  1395. char *p, *begin_word, *end_word, *end_whitespace;
  1396. begin_word = *buf;
  1397. end_word = begin_word + strcspn(begin_word, delimiters);
  1398. /* Check for quotechar */
  1399. if (end_word > begin_word) {
  1400. p = end_word - 1;
  1401. while (*p == quotechar) {
  1402. /* TODO (bel, low): it seems this code is never reached, so
  1403. * quotechar is actually not needed - check if this code may be
  1404. * droped */
  1405. /* If there is anything beyond end_word, copy it */
  1406. if (*end_word == '\0') {
  1407. *p = '\0';
  1408. break;
  1409. } else {
  1410. size_t end_off = strcspn(end_word + 1, delimiters);
  1411. memmove(p, end_word, end_off + 1);
  1412. p += end_off; /* p must correspond to end_word - 1 */
  1413. end_word += end_off + 1;
  1414. }
  1415. }
  1416. for (p++; p < end_word; p++) {
  1417. *p = '\0';
  1418. }
  1419. }
  1420. if (*end_word == '\0') {
  1421. *buf = end_word;
  1422. } else {
  1423. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1424. for (p = end_word; p < end_whitespace; p++) {
  1425. *p = '\0';
  1426. }
  1427. *buf = end_whitespace;
  1428. }
  1429. return begin_word;
  1430. }
  1431. /* Simplified version of skip_quoted without quote char
  1432. * and whitespace == delimiters */
  1433. static char *skip(char **buf, const char *delimiters)
  1434. {
  1435. return skip_quoted(buf, delimiters, delimiters, 0);
  1436. }
  1437. /* Return HTTP header value, or NULL if not found. */
  1438. static const char *get_header(const struct mg_request_info *ri,
  1439. const char *name)
  1440. {
  1441. int i;
  1442. if (ri) {
  1443. for (i = 0; i < ri->num_headers; i++) {
  1444. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1445. return ri->http_headers[i].value;
  1446. }
  1447. }
  1448. }
  1449. return NULL;
  1450. }
  1451. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  1452. {
  1453. if (!conn) {
  1454. return NULL;
  1455. }
  1456. return get_header(&conn->request_info, name);
  1457. }
  1458. /* A helper function for traversing a comma separated list of values.
  1459. * It returns a list pointer shifted to the next value, or NULL if the end
  1460. * of the list found.
  1461. * Value is stored in val vector. If value has form "x=y", then eq_val
  1462. * vector is initialized to point to the "y" part, and val vector length
  1463. * is adjusted to point only to "x". */
  1464. static const char *
  1465. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1466. {
  1467. if (val == NULL || list == NULL || *list == '\0') {
  1468. /* End of the list */
  1469. list = NULL;
  1470. } else {
  1471. val->ptr = list;
  1472. if ((list = strchr(val->ptr, ',')) != NULL) {
  1473. /* Comma found. Store length and shift the list ptr */
  1474. val->len = ((size_t)(list - val->ptr));
  1475. list++;
  1476. } else {
  1477. /* This value is the last one */
  1478. list = val->ptr + strlen(val->ptr);
  1479. val->len = ((size_t)(list - val->ptr));
  1480. }
  1481. if (eq_val != NULL) {
  1482. /* Value has form "x=y", adjust pointers and lengths
  1483. * so that val points to "x", and eq_val points to "y". */
  1484. eq_val->len = 0;
  1485. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1486. if (eq_val->ptr != NULL) {
  1487. eq_val->ptr++; /* Skip over '=' character */
  1488. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1489. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1490. }
  1491. }
  1492. }
  1493. return list;
  1494. }
  1495. /* Perform case-insensitive match of string against pattern */
  1496. static int
  1497. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1498. {
  1499. const char *or_str;
  1500. size_t i;
  1501. int j, len, res;
  1502. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1503. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1504. return res > 0 ? res : match_prefix(or_str + 1,
  1505. (size_t)((pattern + pattern_len) -
  1506. (or_str + 1)),
  1507. str);
  1508. }
  1509. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1510. if (pattern[i] == '?' && str[j] != '\0') {
  1511. continue;
  1512. } else if (pattern[i] == '$') {
  1513. return str[j] == '\0' ? j : -1;
  1514. } else if (pattern[i] == '*') {
  1515. i++;
  1516. if (pattern[i] == '*') {
  1517. i++;
  1518. len = (int)strlen(str + j);
  1519. } else {
  1520. len = (int)strcspn(str + j, "/");
  1521. }
  1522. if (i == pattern_len) {
  1523. return j + len;
  1524. }
  1525. do {
  1526. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1527. } while (res == -1 && len-- > 0);
  1528. return res == -1 ? -1 : j + res + len;
  1529. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1530. return -1;
  1531. }
  1532. }
  1533. return j;
  1534. }
  1535. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1536. * This function must tolerate situations when connection info is not
  1537. * set up, for example if request parsing failed. */
  1538. static int should_keep_alive(const struct mg_connection *conn)
  1539. {
  1540. if (conn != NULL) {
  1541. const char *http_version = conn->request_info.http_version;
  1542. const char *header = mg_get_header(conn, "Connection");
  1543. if (conn->must_close || conn->status_code == 401 ||
  1544. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1545. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1546. (header == NULL && http_version &&
  1547. 0 != strcmp(http_version, "1.1"))) {
  1548. return 0;
  1549. }
  1550. return 1;
  1551. }
  1552. return 0;
  1553. }
  1554. static int should_decode_url(const struct mg_connection *conn)
  1555. {
  1556. if (!conn || !conn->ctx) {
  1557. return 0;
  1558. }
  1559. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1560. }
  1561. static const char *suggest_connection_header(const struct mg_connection *conn)
  1562. {
  1563. return should_keep_alive(conn) ? "keep-alive" : "close";
  1564. }
  1565. static void handle_file_based_request(struct mg_connection *conn,
  1566. const char *path,
  1567. struct file *filep);
  1568. static int
  1569. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1570. static const char *mg_get_response_code_text(int response_code,
  1571. struct mg_connection *conn)
  1572. {
  1573. switch (response_code) {
  1574. /* RFC2616 Section 10.1 - Informational 1xx */
  1575. case 100:
  1576. return "Continue"; /* RFC2616 Section 10.1.1 */
  1577. case 101:
  1578. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1579. case 102:
  1580. return "Processing"; /* RFC2518 Section 10.1 */
  1581. /* RFC2616 Section 10.2 - Successful 2xx */
  1582. case 200:
  1583. return "OK"; /* RFC2616 Section 10.2.1 */
  1584. case 201:
  1585. return "Created"; /* RFC2616 Section 10.2.2 */
  1586. case 202:
  1587. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1588. case 203:
  1589. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1590. case 204:
  1591. return "No Content"; /* RFC2616 Section 10.2.5 */
  1592. case 205:
  1593. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1594. case 206:
  1595. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1596. case 207:
  1597. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1598. /* RFC2616 Section 10.3 - Redirection 3xx */
  1599. case 300:
  1600. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1601. case 301:
  1602. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1603. case 302:
  1604. return "Found"; /* RFC2616 Section 10.3.3 */
  1605. case 303:
  1606. return "See Other"; /* RFC2616 Section 10.3.4 */
  1607. case 304:
  1608. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1609. case 305:
  1610. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1611. case 307:
  1612. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1613. /* RFC2616 Section 10.4 - Client Error 4xx */
  1614. case 400:
  1615. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1616. case 401:
  1617. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1618. case 402:
  1619. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1620. case 403:
  1621. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1622. case 404:
  1623. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1624. case 405:
  1625. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1626. case 406:
  1627. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1628. case 407:
  1629. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1630. case 408:
  1631. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1632. case 409:
  1633. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1634. case 410:
  1635. return "Gone"; /* RFC2616 Section 10.4.11 */
  1636. case 411:
  1637. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1638. case 412:
  1639. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1640. case 413:
  1641. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1642. case 414:
  1643. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1644. case 415:
  1645. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1646. case 416:
  1647. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1648. case 417:
  1649. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1650. case 422:
  1651. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1652. * Section 11.2 */
  1653. case 423:
  1654. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1655. case 424:
  1656. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1657. * Section 11.4 */
  1658. case 428:
  1659. return "Precondition Required"; /* RFC 6585, Section 3 */
  1660. case 429:
  1661. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1662. case 431:
  1663. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1664. /* RFC2616 Section 10.5 - Server Error 5xx */
  1665. case 500:
  1666. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1667. case 501:
  1668. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1669. case 502:
  1670. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1671. case 503:
  1672. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1673. case 504:
  1674. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1675. case 505:
  1676. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1677. case 507:
  1678. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1679. * Section 11.5 */
  1680. case 511:
  1681. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1682. /* Other RFCs */
  1683. case 426:
  1684. return "Upgrade Required"; /* RFC 2817 */
  1685. /* Return codes from non normative RFCs: */
  1686. /* Informative and experimental RFCs, "de facto" standards due to common
  1687. * use, ... */
  1688. case 208:
  1689. return "Already Reported"; /* RFC5842 Section 7.1 */
  1690. case 226:
  1691. return "IM used"; /* RFC3229 Section 10.4.1 */
  1692. case 308:
  1693. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1694. case 418:
  1695. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1696. case 419:
  1697. return "Authentication Timeout"; /* common use */
  1698. case 451:
  1699. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1700. * Section 3 */
  1701. case 506:
  1702. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1703. case 508:
  1704. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1705. case 510:
  1706. return "Not Extended"; /* RFC 2774, Section 7 */
  1707. default:
  1708. /* This error code is unknown. This should not happen. */
  1709. if (conn) {
  1710. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1711. }
  1712. /* Return at least a category according to RFC 2616 Section 10. */
  1713. if (response_code >= 100 && response_code < 200) {
  1714. /* Unknown informational status code */
  1715. return "Information";
  1716. }
  1717. if (response_code >= 200 && response_code < 300) {
  1718. /* Unknown success code */
  1719. return "Success";
  1720. }
  1721. if (response_code >= 300 && response_code < 400) {
  1722. /* Unknown redirection code */
  1723. return "Redirection";
  1724. }
  1725. if (response_code >= 400 && response_code < 500) {
  1726. /* Unknown request error code */
  1727. return "Client Error";
  1728. }
  1729. if (response_code >= 500 && response_code < 600) {
  1730. /* Unknown server error code */
  1731. return "Server Error";
  1732. }
  1733. /* Response code not even within reasonable range */
  1734. return "";
  1735. }
  1736. }
  1737. static void send_http_error(struct mg_connection *,
  1738. int,
  1739. PRINTF_FORMAT_STRING(const char *fmt),
  1740. ...) PRINTF_ARGS(3, 4);
  1741. static void
  1742. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1743. {
  1744. char buf[MG_BUF_LEN];
  1745. va_list ap;
  1746. int len = 0, i, page_handler_found, scope;
  1747. char date[64];
  1748. time_t curtime = time(NULL);
  1749. const char *error_handler = NULL;
  1750. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1751. const char *error_page_file_ext, *tstr;
  1752. const char *status_text = mg_get_response_code_text(status, conn);
  1753. if (conn == NULL) {
  1754. return;
  1755. }
  1756. conn->status_code = status;
  1757. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL ||
  1758. conn->ctx->callbacks.http_error(conn, status)) {
  1759. if (!conn->in_error_handler) {
  1760. /* Send user defined error pages, if defined */
  1761. error_handler = conn->ctx->config[ERROR_PAGES];
  1762. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1763. page_handler_found = 0;
  1764. if (error_handler != NULL) {
  1765. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1766. switch (scope) {
  1767. case 1:
  1768. len = mg_snprintf(conn,
  1769. buf,
  1770. sizeof(buf) - 32,
  1771. "%serror%03u.",
  1772. error_handler,
  1773. status);
  1774. break;
  1775. case 2:
  1776. len = mg_snprintf(conn,
  1777. buf,
  1778. sizeof(buf) - 32,
  1779. "%serror%01uxx.",
  1780. error_handler,
  1781. status / 100);
  1782. break;
  1783. default:
  1784. len = mg_snprintf(conn,
  1785. buf,
  1786. sizeof(buf) - 32,
  1787. "%serror.",
  1788. error_handler);
  1789. break;
  1790. }
  1791. tstr = strchr(error_page_file_ext, '.');
  1792. while (tstr) {
  1793. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  1794. i++)
  1795. buf[len + i - 1] = tstr[i];
  1796. buf[len + i - 1] = 0;
  1797. if (mg_stat(conn, buf, &error_page_file)) {
  1798. page_handler_found = 1;
  1799. break;
  1800. }
  1801. tstr = strchr(tstr + i, '.');
  1802. }
  1803. }
  1804. }
  1805. if (page_handler_found) {
  1806. conn->in_error_handler = 1;
  1807. handle_file_based_request(conn, buf, &error_page_file);
  1808. conn->in_error_handler = 0;
  1809. return;
  1810. }
  1811. }
  1812. buf[0] = '\0';
  1813. gmt_time_string(date, sizeof(date), &curtime);
  1814. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1815. if (status > 199 && status != 204 && status != 304) {
  1816. len = mg_snprintf(conn,
  1817. buf,
  1818. sizeof(buf) - 1,
  1819. "Error %d: %s",
  1820. status,
  1821. status_text);
  1822. buf[len] = '\n';
  1823. len++;
  1824. buf[len] = 0;
  1825. va_start(ap, fmt);
  1826. len += mg_vsnprintf(
  1827. conn, buf + len, sizeof(buf) - (size_t)len, fmt, ap);
  1828. va_end(ap);
  1829. }
  1830. DEBUG_TRACE("[%s]", buf);
  1831. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  1832. if (len > 0) {
  1833. mg_printf(conn, "Content-Type: text/plain\r\n");
  1834. }
  1835. mg_printf(conn,
  1836. "Content-Length: %d\r\n"
  1837. "Date: %s\r\n"
  1838. "Connection: %s\r\n\r\n",
  1839. len,
  1840. date,
  1841. suggest_connection_header(conn));
  1842. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  1843. }
  1844. }
  1845. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1846. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  1847. {
  1848. (void)unused;
  1849. *mutex = CreateMutex(NULL, FALSE, NULL);
  1850. return *mutex == NULL ? -1 : 0;
  1851. }
  1852. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  1853. {
  1854. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1855. }
  1856. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  1857. {
  1858. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  1859. }
  1860. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  1861. static int pthread_mutex_trylock(pthread_mutex_t *mutex)
  1862. {
  1863. switch (WaitForSingleObject(*mutex, 0)) {
  1864. case WAIT_OBJECT_0:
  1865. return 0;
  1866. case WAIT_TIMEOUT:
  1867. return -2; /* EBUSY */
  1868. }
  1869. return -1;
  1870. }
  1871. #endif
  1872. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  1873. {
  1874. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1875. }
  1876. #ifndef WIN_PTHREADS_TIME_H
  1877. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  1878. {
  1879. FILETIME ft;
  1880. ULARGE_INTEGER li;
  1881. BOOL ok = FALSE;
  1882. double d;
  1883. static double perfcnt_per_sec = 0.0;
  1884. if (tp) {
  1885. if (clk_id == CLOCK_REALTIME) {
  1886. GetSystemTimeAsFileTime(&ft);
  1887. li.LowPart = ft.dwLowDateTime;
  1888. li.HighPart = ft.dwHighDateTime;
  1889. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1890. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1891. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1892. ok = TRUE;
  1893. } else if (clk_id == CLOCK_MONOTONIC) {
  1894. if (perfcnt_per_sec == 0.0) {
  1895. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  1896. perfcnt_per_sec = 1.0 / li.QuadPart;
  1897. }
  1898. if (perfcnt_per_sec != 0.0) {
  1899. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  1900. d = li.QuadPart * perfcnt_per_sec;
  1901. tp->tv_sec = (time_t)d;
  1902. d -= tp->tv_sec;
  1903. tp->tv_nsec = (long)(d * 1.0E9);
  1904. ok = TRUE;
  1905. }
  1906. }
  1907. }
  1908. return ok ? 0 : -1;
  1909. }
  1910. #endif
  1911. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1912. {
  1913. (void)unused;
  1914. InitializeCriticalSection(&cv->threadIdSec);
  1915. cv->waitingthreadcount = 0;
  1916. cv->waitingthreadhdls =
  1917. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1918. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  1919. }
  1920. static int pthread_cond_timedwait(pthread_cond_t *cv,
  1921. pthread_mutex_t *mutex,
  1922. const struct timespec *abstime)
  1923. {
  1924. struct mg_workerTLS *tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1925. int ok;
  1926. struct timespec tsnow;
  1927. int64_t nsnow, nswaitabs, nswaitrel;
  1928. DWORD mswaitrel;
  1929. EnterCriticalSection(&cv->threadIdSec);
  1930. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1931. cv->waitingthreadhdls[cv->waitingthreadcount] =
  1932. tls->pthread_cond_helper_mutex;
  1933. cv->waitingthreadcount++;
  1934. LeaveCriticalSection(&cv->threadIdSec);
  1935. if (abstime) {
  1936. clock_gettime(CLOCK_REALTIME, &tsnow);
  1937. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  1938. nswaitabs =
  1939. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  1940. nswaitrel = nswaitabs - nsnow;
  1941. if (nswaitrel < 0)
  1942. nswaitrel = 0;
  1943. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1944. } else {
  1945. mswaitrel = INFINITE;
  1946. }
  1947. pthread_mutex_unlock(mutex);
  1948. ok = (WAIT_OBJECT_0 ==
  1949. WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1950. pthread_mutex_lock(mutex);
  1951. return ok ? 0 : -1;
  1952. }
  1953. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  1954. {
  1955. return pthread_cond_timedwait(cv, mutex, NULL);
  1956. }
  1957. static int pthread_cond_signal(pthread_cond_t *cv)
  1958. {
  1959. int i;
  1960. HANDLE wkup = NULL;
  1961. BOOL ok = FALSE;
  1962. EnterCriticalSection(&cv->threadIdSec);
  1963. if (cv->waitingthreadcount) {
  1964. wkup = cv->waitingthreadhdls[0];
  1965. ok = SetEvent(wkup);
  1966. for (i = 1; i < cv->waitingthreadcount; i++) {
  1967. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  1968. }
  1969. cv->waitingthreadcount--;
  1970. assert(ok);
  1971. }
  1972. LeaveCriticalSection(&cv->threadIdSec);
  1973. return ok ? 0 : 1;
  1974. }
  1975. static int pthread_cond_broadcast(pthread_cond_t *cv)
  1976. {
  1977. EnterCriticalSection(&cv->threadIdSec);
  1978. while (cv->waitingthreadcount) {
  1979. pthread_cond_signal(cv);
  1980. }
  1981. LeaveCriticalSection(&cv->threadIdSec);
  1982. return 0;
  1983. }
  1984. static int pthread_cond_destroy(pthread_cond_t *cv)
  1985. {
  1986. EnterCriticalSection(&cv->threadIdSec);
  1987. assert(cv->waitingthreadcount == 0);
  1988. mg_free(cv->waitingthreadhdls);
  1989. cv->waitingthreadhdls = 0;
  1990. LeaveCriticalSection(&cv->threadIdSec);
  1991. DeleteCriticalSection(&cv->threadIdSec);
  1992. return 0;
  1993. }
  1994. /* For Windows, change all slashes to backslashes in path names. */
  1995. static void change_slashes_to_backslashes(char *path)
  1996. {
  1997. int i;
  1998. for (i = 0; path[i] != '\0'; i++) {
  1999. if (path[i] == '/') {
  2000. path[i] = '\\';
  2001. }
  2002. /* remove double backslash (check i > 0 to preserve UNC paths,
  2003. * like \\server\file.txt) */
  2004. if ((path[i] == '\\') && (i > 0)) {
  2005. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2006. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2007. }
  2008. }
  2009. }
  2010. }
  2011. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2012. * wbuf and wbuf_len is a target buffer and its length. */
  2013. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2014. {
  2015. char buf[PATH_MAX], buf2[PATH_MAX];
  2016. mg_strlcpy(buf, path, sizeof(buf));
  2017. change_slashes_to_backslashes(buf);
  2018. /* Convert to Unicode and back. If doubly-converted string does not
  2019. * match the original, something is fishy, reject. */
  2020. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2021. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2022. WideCharToMultiByte(
  2023. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2024. if (strcmp(buf, buf2) != 0) {
  2025. wbuf[0] = L'\0';
  2026. }
  2027. }
  2028. #if defined(_WIN32_WCE)
  2029. static time_t time(time_t *ptime)
  2030. {
  2031. time_t t;
  2032. SYSTEMTIME st;
  2033. FILETIME ft;
  2034. GetSystemTime(&st);
  2035. SystemTimeToFileTime(&st, &ft);
  2036. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2037. if (ptime != NULL) {
  2038. *ptime = t;
  2039. }
  2040. return t;
  2041. }
  2042. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  2043. {
  2044. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2045. FILETIME ft, lft;
  2046. SYSTEMTIME st;
  2047. TIME_ZONE_INFORMATION tzinfo;
  2048. if (ptm == NULL) {
  2049. return NULL;
  2050. }
  2051. *(int64_t *)&ft = t;
  2052. FileTimeToLocalFileTime(&ft, &lft);
  2053. FileTimeToSystemTime(&lft, &st);
  2054. ptm->tm_year = st.wYear - 1900;
  2055. ptm->tm_mon = st.wMonth - 1;
  2056. ptm->tm_wday = st.wDayOfWeek;
  2057. ptm->tm_mday = st.wDay;
  2058. ptm->tm_hour = st.wHour;
  2059. ptm->tm_min = st.wMinute;
  2060. ptm->tm_sec = st.wSecond;
  2061. ptm->tm_yday = 0; /* hope nobody uses this */
  2062. ptm->tm_isdst =
  2063. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2064. return ptm;
  2065. }
  2066. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  2067. {
  2068. /* FIXME(lsm): fix this. */
  2069. return localtime(ptime, ptm);
  2070. }
  2071. static size_t
  2072. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2073. {
  2074. (void)snprintf(dst, dst_size, "implement strftime() for WinCE");
  2075. return 0;
  2076. }
  2077. #endif
  2078. /* Windows happily opens files with some garbage at the end of file name.
  2079. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2080. * "a.cgi", despite one would expect an error back.
  2081. * This function returns non-0 if path ends with some garbage. */
  2082. static int path_cannot_disclose_cgi(const char *path)
  2083. {
  2084. static const char *allowed_last_characters = "_-";
  2085. int last = path[strlen(path) - 1];
  2086. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2087. }
  2088. static int
  2089. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2090. {
  2091. wchar_t wbuf[PATH_MAX];
  2092. WIN32_FILE_ATTRIBUTE_DATA info;
  2093. if (!is_file_in_memory(conn, path, filep)) {
  2094. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2095. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2096. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2097. filep->modification_time =
  2098. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2099. info.ftLastWriteTime.dwHighDateTime);
  2100. /* On Windows, the file creation time can be higher than the
  2101. * modification time, e.g. when a file is copied.
  2102. * Since the Last-Modified timestamp is used for caching
  2103. * it should be based on the most recent timestamp. */
  2104. time_t creation_time =
  2105. SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2106. info.ftCreationTime.dwHighDateTime);
  2107. if (creation_time > filep->modification_time) {
  2108. filep->modification_time = creation_time;
  2109. }
  2110. filep->is_directory =
  2111. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2112. /* If file name is fishy, reset the file structure and return
  2113. * error.
  2114. * Note it is important to reset, not just return the error, cause
  2115. * functions like is_file_opened() check the struct. */
  2116. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2117. memset(filep, 0, sizeof(*filep));
  2118. }
  2119. }
  2120. }
  2121. return filep->membuf != NULL || filep->modification_time != 0;
  2122. }
  2123. static int mg_remove(const char *path)
  2124. {
  2125. wchar_t wbuf[PATH_MAX];
  2126. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2127. return DeleteFileW(wbuf) ? 0 : -1;
  2128. }
  2129. static int mg_mkdir(const char *path, int mode)
  2130. {
  2131. char buf[PATH_MAX];
  2132. wchar_t wbuf[PATH_MAX];
  2133. (void)mode;
  2134. mg_strlcpy(buf, path, sizeof(buf));
  2135. change_slashes_to_backslashes(buf);
  2136. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2137. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2138. }
  2139. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2140. static DIR *opendir(const char *name)
  2141. {
  2142. DIR *dir = NULL;
  2143. wchar_t wpath[PATH_MAX];
  2144. DWORD attrs;
  2145. if (name == NULL) {
  2146. SetLastError(ERROR_BAD_ARGUMENTS);
  2147. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2148. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2149. } else {
  2150. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2151. attrs = GetFileAttributesW(wpath);
  2152. if (attrs != 0xFFFFFFFF &&
  2153. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2154. (void)wcscat(wpath, L"\\*");
  2155. dir->handle = FindFirstFileW(wpath, &dir->info);
  2156. dir->result.d_name[0] = '\0';
  2157. } else {
  2158. mg_free(dir);
  2159. dir = NULL;
  2160. }
  2161. }
  2162. return dir;
  2163. }
  2164. static int closedir(DIR *dir)
  2165. {
  2166. int result = 0;
  2167. if (dir != NULL) {
  2168. if (dir->handle != INVALID_HANDLE_VALUE)
  2169. result = FindClose(dir->handle) ? 0 : -1;
  2170. mg_free(dir);
  2171. } else {
  2172. result = -1;
  2173. SetLastError(ERROR_BAD_ARGUMENTS);
  2174. }
  2175. return result;
  2176. }
  2177. static struct dirent *readdir(DIR *dir)
  2178. {
  2179. struct dirent *result = 0;
  2180. if (dir) {
  2181. if (dir->handle != INVALID_HANDLE_VALUE) {
  2182. result = &dir->result;
  2183. (void)WideCharToMultiByte(CP_UTF8,
  2184. 0,
  2185. dir->info.cFileName,
  2186. -1,
  2187. result->d_name,
  2188. sizeof(result->d_name),
  2189. NULL,
  2190. NULL);
  2191. if (!FindNextFileW(dir->handle, &dir->info)) {
  2192. (void)FindClose(dir->handle);
  2193. dir->handle = INVALID_HANDLE_VALUE;
  2194. }
  2195. } else {
  2196. SetLastError(ERROR_FILE_NOT_FOUND);
  2197. }
  2198. } else {
  2199. SetLastError(ERROR_BAD_ARGUMENTS);
  2200. }
  2201. return result;
  2202. }
  2203. #ifndef HAVE_POLL
  2204. static int poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2205. {
  2206. struct timeval tv;
  2207. fd_set set;
  2208. unsigned int i;
  2209. int result;
  2210. SOCKET maxfd = 0;
  2211. tv.tv_sec = milliseconds / 1000;
  2212. tv.tv_usec = (milliseconds % 1000) * 1000;
  2213. FD_ZERO(&set);
  2214. for (i = 0; i < n; i++) {
  2215. FD_SET((SOCKET)pfd[i].fd, &set);
  2216. pfd[i].revents = 0;
  2217. if (pfd[i].fd > maxfd) {
  2218. maxfd = pfd[i].fd;
  2219. }
  2220. }
  2221. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2222. for (i = 0; i < n; i++) {
  2223. if (FD_ISSET(pfd[i].fd, &set)) {
  2224. pfd[i].revents = POLLIN;
  2225. }
  2226. }
  2227. }
  2228. return result;
  2229. }
  2230. #endif /* HAVE_POLL */
  2231. static void set_close_on_exec(SOCKET sock,
  2232. struct mg_connection *conn /* may be null */)
  2233. {
  2234. (void)conn; /* Unused. */
  2235. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2236. }
  2237. int mg_start_thread(mg_thread_func_t f, void *p)
  2238. {
  2239. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2240. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2241. */
  2242. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2243. ((uintptr_t)(-1L)))
  2244. ? -1
  2245. : 0);
  2246. #else
  2247. return (
  2248. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2249. ? -1
  2250. : 0);
  2251. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2252. }
  2253. /* Start a thread storing the thread context. */
  2254. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2255. void *p,
  2256. pthread_t *threadidptr)
  2257. {
  2258. uintptr_t uip;
  2259. HANDLE threadhandle;
  2260. int result = -1;
  2261. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2262. threadhandle = (HANDLE)uip;
  2263. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2264. *threadidptr = threadhandle;
  2265. result = 0;
  2266. }
  2267. return result;
  2268. }
  2269. /* Wait for a thread to finish. */
  2270. static int mg_join_thread(pthread_t threadid)
  2271. {
  2272. int result;
  2273. DWORD dwevent;
  2274. result = -1;
  2275. dwevent = WaitForSingleObject(threadid, INFINITE);
  2276. if (dwevent == WAIT_FAILED) {
  2277. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2278. } else {
  2279. if (dwevent == WAIT_OBJECT_0) {
  2280. CloseHandle(threadid);
  2281. result = 0;
  2282. }
  2283. }
  2284. return result;
  2285. }
  2286. static HANDLE dlopen(const char *dll_name, int flags)
  2287. {
  2288. wchar_t wbuf[PATH_MAX];
  2289. (void)flags;
  2290. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2291. return LoadLibraryW(wbuf);
  2292. }
  2293. static int dlclose(void *handle)
  2294. {
  2295. int result;
  2296. if (FreeLibrary((HMODULE)handle) != 0) {
  2297. result = 0;
  2298. } else {
  2299. result = -1;
  2300. }
  2301. return result;
  2302. }
  2303. #if !defined(NO_CGI)
  2304. #define SIGKILL (0)
  2305. static int kill(pid_t pid, int sig_num)
  2306. {
  2307. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2308. (void)CloseHandle((HANDLE)pid);
  2309. return 0;
  2310. }
  2311. static void trim_trailing_whitespaces(char *s)
  2312. {
  2313. char *e = s + strlen(s) - 1;
  2314. while (e > s && isspace(*(unsigned char *)e)) {
  2315. *e-- = '\0';
  2316. }
  2317. }
  2318. static pid_t spawn_process(struct mg_connection *conn,
  2319. const char *prog,
  2320. char *envblk,
  2321. char *envp[],
  2322. int fdin,
  2323. int fdout,
  2324. const char *dir)
  2325. {
  2326. HANDLE me;
  2327. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2328. cmdline[PATH_MAX], buf[PATH_MAX];
  2329. struct file file = STRUCT_FILE_INITIALIZER;
  2330. STARTUPINFOA si;
  2331. PROCESS_INFORMATION pi = {0};
  2332. (void)envp;
  2333. memset(&si, 0, sizeof(si));
  2334. si.cb = sizeof(si);
  2335. /* TODO(lsm, mid): redirect CGI errors to the error log file */
  2336. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2337. si.wShowWindow = SW_HIDE;
  2338. me = GetCurrentProcess();
  2339. DuplicateHandle(me,
  2340. (HANDLE)_get_osfhandle(fdin),
  2341. me,
  2342. &si.hStdInput,
  2343. 0,
  2344. TRUE,
  2345. DUPLICATE_SAME_ACCESS);
  2346. DuplicateHandle(me,
  2347. (HANDLE)_get_osfhandle(fdout),
  2348. me,
  2349. &si.hStdOutput,
  2350. 0,
  2351. TRUE,
  2352. DUPLICATE_SAME_ACCESS);
  2353. /* If CGI file is a script, try to read the interpreter line */
  2354. interp = conn->ctx->config[CGI_INTERPRETER];
  2355. if (interp == NULL) {
  2356. buf[0] = buf[1] = '\0';
  2357. /* Read the first line of the script into the buffer */
  2358. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  2359. if (mg_fopen(conn, cmdline, "r", &file)) {
  2360. p = (char *)file.membuf;
  2361. mg_fgets(buf, sizeof(buf), &file, &p);
  2362. mg_fclose(&file);
  2363. buf[sizeof(buf) - 1] = '\0';
  2364. }
  2365. if (buf[0] == '#' && buf[1] == '!') {
  2366. trim_trailing_whitespaces(buf + 2);
  2367. } else {
  2368. buf[2] = '\0';
  2369. }
  2370. interp = buf + 2;
  2371. }
  2372. if (interp[0] != '\0') {
  2373. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2374. interp = full_interp;
  2375. }
  2376. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2377. if (interp[0] != '\0')
  2378. mg_snprintf(conn,
  2379. cmdline,
  2380. sizeof(cmdline),
  2381. "\"%s\" \"%s\\%s\"",
  2382. interp,
  2383. full_dir,
  2384. prog);
  2385. else
  2386. mg_snprintf(
  2387. conn, cmdline, sizeof(cmdline), "\"%s\\%s\"", full_dir, prog);
  2388. DEBUG_TRACE("Running [%s]", cmdline);
  2389. if (CreateProcessA(NULL,
  2390. cmdline,
  2391. NULL,
  2392. NULL,
  2393. TRUE,
  2394. CREATE_NEW_PROCESS_GROUP,
  2395. envblk,
  2396. NULL,
  2397. &si,
  2398. &pi) == 0) {
  2399. mg_cry(conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, ERRNO);
  2400. pi.hProcess = (pid_t)-1;
  2401. }
  2402. (void)CloseHandle(si.hStdOutput);
  2403. (void)CloseHandle(si.hStdInput);
  2404. if (pi.hThread != NULL)
  2405. (void)CloseHandle(pi.hThread);
  2406. return (pid_t)pi.hProcess;
  2407. }
  2408. #endif /* !NO_CGI */
  2409. static int set_non_blocking_mode(SOCKET sock)
  2410. {
  2411. unsigned long on = 1;
  2412. return ioctlsocket(sock, (long)FIONBIO, &on);
  2413. }
  2414. #else
  2415. static int
  2416. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2417. {
  2418. struct stat st;
  2419. if (!filep) {
  2420. return 0;
  2421. }
  2422. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  2423. filep->size = (uint64_t)(st.st_size);
  2424. filep->modification_time = st.st_mtime;
  2425. filep->is_directory = S_ISDIR(st.st_mode);
  2426. } else {
  2427. filep->modification_time = (time_t)0;
  2428. }
  2429. return filep->membuf != NULL || filep->modification_time != (time_t)0;
  2430. }
  2431. static void set_close_on_exec(SOCKET fd,
  2432. struct mg_connection *conn /* may be null */)
  2433. {
  2434. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2435. if (conn) {
  2436. mg_cry(conn,
  2437. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2438. __func__,
  2439. strerror(ERRNO));
  2440. }
  2441. }
  2442. }
  2443. int mg_start_thread(mg_thread_func_t func, void *param)
  2444. {
  2445. pthread_t thread_id;
  2446. pthread_attr_t attr;
  2447. int result;
  2448. (void)pthread_attr_init(&attr);
  2449. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2450. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2451. /* Compile-time option to control stack size,
  2452. * e.g. -DUSE_STACK_SIZE=16384 */
  2453. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2454. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2455. result = pthread_create(&thread_id, &attr, func, param);
  2456. pthread_attr_destroy(&attr);
  2457. return result;
  2458. }
  2459. /* Start a thread storing the thread context. */
  2460. static int mg_start_thread_with_id(mg_thread_func_t func,
  2461. void *param,
  2462. pthread_t *threadidptr)
  2463. {
  2464. pthread_t thread_id;
  2465. pthread_attr_t attr;
  2466. int result;
  2467. (void)pthread_attr_init(&attr);
  2468. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2469. /* Compile-time option to control stack size,
  2470. * e.g. -DUSE_STACK_SIZE=16384 */
  2471. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2472. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2473. result = pthread_create(&thread_id, &attr, func, param);
  2474. pthread_attr_destroy(&attr);
  2475. if ((result == 0) && (threadidptr != NULL)) {
  2476. *threadidptr = thread_id;
  2477. }
  2478. return result;
  2479. }
  2480. /* Wait for a thread to finish. */
  2481. static int mg_join_thread(pthread_t threadid)
  2482. {
  2483. int result;
  2484. result = pthread_join(threadid, NULL);
  2485. return result;
  2486. }
  2487. #ifndef NO_CGI
  2488. static pid_t spawn_process(struct mg_connection *conn,
  2489. const char *prog,
  2490. char *envblk,
  2491. char *envp[],
  2492. int fdin,
  2493. int fdout,
  2494. const char *dir)
  2495. {
  2496. pid_t pid;
  2497. const char *interp;
  2498. (void)envblk;
  2499. if (conn == NULL) {
  2500. return 0;
  2501. }
  2502. if ((pid = fork()) == -1) {
  2503. /* Parent */
  2504. send_http_error(conn,
  2505. 500,
  2506. "Error: Creating CGI process\nfork(): %s",
  2507. strerror(ERRNO));
  2508. } else if (pid == 0) {
  2509. /* Child */
  2510. if (chdir(dir) != 0) {
  2511. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2512. } else if (dup2(fdin, 0) == -1) {
  2513. mg_cry(
  2514. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2515. } else if (dup2(fdout, 1) == -1) {
  2516. mg_cry(
  2517. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2518. } else {
  2519. /* Not redirecting stderr to stdout, to avoid output being littered
  2520. * with the error messages. */
  2521. (void)close(fdin);
  2522. (void)close(fdout);
  2523. /* After exec, all signal handlers are restored to their default
  2524. * values, with one exception of SIGCHLD. According to
  2525. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2526. * leave unchanged after exec if it was set to be ignored. Restore
  2527. * it to default action. */
  2528. signal(SIGCHLD, SIG_DFL);
  2529. interp = conn->ctx->config[CGI_INTERPRETER];
  2530. if (interp == NULL) {
  2531. (void)execle(prog, prog, NULL, envp);
  2532. mg_cry(conn,
  2533. "%s: execle(%s): %s",
  2534. __func__,
  2535. prog,
  2536. strerror(ERRNO));
  2537. } else {
  2538. (void)execle(interp, interp, prog, NULL, envp);
  2539. mg_cry(conn,
  2540. "%s: execle(%s %s): %s",
  2541. __func__,
  2542. interp,
  2543. prog,
  2544. strerror(ERRNO));
  2545. }
  2546. }
  2547. exit(EXIT_FAILURE);
  2548. }
  2549. return pid;
  2550. }
  2551. #endif /* !NO_CGI */
  2552. static int set_non_blocking_mode(SOCKET sock)
  2553. {
  2554. int flags;
  2555. flags = fcntl(sock, F_GETFL, 0);
  2556. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2557. return 0;
  2558. }
  2559. #endif /* _WIN32 */
  2560. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2561. * descriptor. Return number of bytes written. */
  2562. static int push(struct mg_context *ctx,
  2563. FILE *fp,
  2564. SOCKET sock,
  2565. SSL *ssl,
  2566. const char *buf,
  2567. int len,
  2568. double timeout)
  2569. {
  2570. struct timespec start, now;
  2571. int n;
  2572. #ifdef _WIN32
  2573. typedef int len_t;
  2574. #else
  2575. typedef size_t len_t;
  2576. #endif
  2577. if (timeout > 0) {
  2578. memset(&start, 0, sizeof(start));
  2579. memset(&now, 0, sizeof(now));
  2580. clock_gettime(CLOCK_MONOTONIC, &start);
  2581. }
  2582. if (ctx == NULL) {
  2583. return -1;
  2584. }
  2585. do {
  2586. #ifndef NO_SSL
  2587. if (ssl != NULL) {
  2588. n = SSL_write(ssl, buf, len);
  2589. } else
  2590. #endif
  2591. if (fp != NULL) {
  2592. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2593. if (ferror(fp))
  2594. n = -1;
  2595. } else {
  2596. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2597. }
  2598. if (ctx->stop_flag) {
  2599. return -1;
  2600. }
  2601. if ((n > 0) || (n == 0 && len == 0)) {
  2602. /* some data has been read, or no data was requested */
  2603. return n;
  2604. }
  2605. if (n == 0) {
  2606. /* shutdown of the socket at client side */
  2607. return -1;
  2608. }
  2609. if (n < 0) {
  2610. /* socket error - check errno */
  2611. int err = ERRNO;
  2612. DEBUG_TRACE("send() failed, error %d", err);
  2613. (void)err; /* TODO: error handling depending on the error code.
  2614. * These codes are different between Windows and Linux.
  2615. */
  2616. return -1;
  2617. }
  2618. if (timeout > 0) {
  2619. clock_gettime(CLOCK_MONOTONIC, &now);
  2620. }
  2621. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2622. return -1;
  2623. }
  2624. static int64_t push_all(struct mg_context *ctx,
  2625. FILE *fp,
  2626. SOCKET sock,
  2627. SSL *ssl,
  2628. const char *buf,
  2629. int64_t len)
  2630. {
  2631. double timeout = -1.0;
  2632. int64_t n, nwritten = 0;
  2633. if (ctx == NULL) {
  2634. return -1;
  2635. }
  2636. if (ctx->config[REQUEST_TIMEOUT]) {
  2637. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2638. }
  2639. while (len > 0 && ctx->stop_flag == 0) {
  2640. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2641. if (n < 0) {
  2642. nwritten = n; /* Propagate the error */
  2643. break;
  2644. } else if (n == 0) {
  2645. break; /* No more data to write */
  2646. } else {
  2647. nwritten += n;
  2648. len -= n;
  2649. }
  2650. }
  2651. return nwritten;
  2652. }
  2653. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2654. * Return negative value on error, or number of bytes read on success. */
  2655. static int
  2656. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  2657. {
  2658. int nread;
  2659. struct timespec start, now;
  2660. #ifdef _WIN32
  2661. typedef int len_t;
  2662. #else
  2663. typedef size_t len_t;
  2664. #endif
  2665. if (timeout > 0) {
  2666. memset(&start, 0, sizeof(start));
  2667. memset(&now, 0, sizeof(now));
  2668. clock_gettime(CLOCK_MONOTONIC, &start);
  2669. }
  2670. do {
  2671. if (fp != NULL) {
  2672. /* Use read() instead of fread(), because if we're reading from the
  2673. * CGI pipe, fread() may block until IO buffer is filled up. We
  2674. * cannot afford to block and must pass all read bytes immediately
  2675. * to the client. */
  2676. nread = (int)read(fileno(fp), buf, (size_t)len);
  2677. #ifndef NO_SSL
  2678. } else if (conn->ssl != NULL) {
  2679. nread = SSL_read(conn->ssl, buf, len);
  2680. #endif
  2681. } else {
  2682. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  2683. }
  2684. if (conn->ctx->stop_flag) {
  2685. return -1;
  2686. }
  2687. if ((nread > 0) || (nread == 0 && len == 0)) {
  2688. /* some data has been read, or no data was requested */
  2689. return nread;
  2690. }
  2691. if (nread == 0) {
  2692. /* shutdown of the socket at client side */
  2693. return -1;
  2694. }
  2695. if (nread < 0) {
  2696. /* socket error - check errno */
  2697. int err = ERRNO;
  2698. #ifdef _WIN32
  2699. if (err == WSAEWOULDBLOCK) {
  2700. /* standard case if called from close_socket_gracefully */
  2701. return -1;
  2702. } else if (err == WSAETIMEDOUT) {
  2703. /* timeout is handled by the while loop */
  2704. } else {
  2705. DEBUG_TRACE("recv() failed, error %d", err);
  2706. return -1;
  2707. }
  2708. #else
  2709. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  2710. * if the timeout is reached and if the socket was set to non-
  2711. * blocking in close_socket_gracefully, so we can not distinguish
  2712. * here. We have to wait for the timeout in both cases for now.
  2713. */
  2714. if (err == EAGAIN || err == EWOULDBLOCK) {
  2715. /* standard case if called from close_socket_gracefully
  2716. * => should return -1 */
  2717. /* or timeout occured
  2718. * => the code must stay in the while loop */
  2719. } else {
  2720. DEBUG_TRACE("recv() failed, error %d", err);
  2721. return -1;
  2722. }
  2723. #endif
  2724. }
  2725. if (timeout > 0) {
  2726. clock_gettime(CLOCK_MONOTONIC, &now);
  2727. }
  2728. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2729. /* Timeout occured, but no data available. */
  2730. return -1;
  2731. }
  2732. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  2733. {
  2734. int n, nread = 0;
  2735. double timeout = -1.0;
  2736. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2737. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2738. }
  2739. while (len > 0 && conn->ctx->stop_flag == 0) {
  2740. n = pull(fp, conn, buf + nread, len, timeout);
  2741. if (n < 0) {
  2742. nread = n; /* Propagate the error */
  2743. break;
  2744. } else if (n == 0) {
  2745. break; /* No more data to read */
  2746. } else {
  2747. conn->consumed_content += n;
  2748. nread += n;
  2749. len -= n;
  2750. }
  2751. }
  2752. return nread;
  2753. }
  2754. static void discard_unread_request_data(struct mg_connection *conn)
  2755. {
  2756. char buf[MG_BUF_LEN];
  2757. size_t to_read;
  2758. int nread;
  2759. if (conn == NULL) {
  2760. return;
  2761. }
  2762. to_read = sizeof(buf);
  2763. if (conn->is_chunked) {
  2764. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2765. * completely */
  2766. while (conn->is_chunked == 1) {
  2767. nread = mg_read(conn, buf, to_read);
  2768. if (nread <= 0) {
  2769. break;
  2770. }
  2771. }
  2772. } else {
  2773. /* Not chunked: content length is known */
  2774. while (conn->consumed_content < conn->content_len) {
  2775. if (to_read >
  2776. (size_t)(conn->content_len - conn->consumed_content)) {
  2777. to_read = (size_t)(conn->content_len - conn->consumed_content);
  2778. }
  2779. nread = mg_read(conn, buf, to_read);
  2780. if (nread <= 0) {
  2781. break;
  2782. }
  2783. }
  2784. }
  2785. }
  2786. static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  2787. {
  2788. int64_t n, buffered_len, nread;
  2789. int64_t len64 =
  2790. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2791. * int, we may not read more
  2792. * bytes */
  2793. const char *body;
  2794. if (conn == NULL)
  2795. return 0;
  2796. /* If Content-Length is not set for a PUT or POST request, read until
  2797. * socket is closed */
  2798. if (conn->consumed_content == 0 && conn->content_len == -1) {
  2799. conn->content_len = INT64_MAX;
  2800. conn->must_close = 1;
  2801. }
  2802. nread = 0;
  2803. if (conn->consumed_content < conn->content_len) {
  2804. /* Adjust number of bytes to read. */
  2805. int64_t left_to_read = conn->content_len - conn->consumed_content;
  2806. if (left_to_read < len64) {
  2807. /* Do not reade more than the total content length of the request.
  2808. */
  2809. len64 = left_to_read;
  2810. }
  2811. /* Return buffered data */
  2812. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  2813. conn->consumed_content;
  2814. if (buffered_len > 0) {
  2815. if (len64 < buffered_len) {
  2816. buffered_len = len64;
  2817. }
  2818. body = conn->buf + conn->request_len + conn->consumed_content;
  2819. memcpy(buf, body, (size_t)buffered_len);
  2820. len64 -= buffered_len;
  2821. conn->consumed_content += buffered_len;
  2822. nread += buffered_len;
  2823. buf = (char *)buf + buffered_len;
  2824. }
  2825. /* We have returned all buffered data. Read new data from the remote
  2826. * socket.
  2827. */
  2828. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  2829. nread += n;
  2830. } else {
  2831. nread = (nread > 0 ? nread : n);
  2832. }
  2833. }
  2834. return (int)nread;
  2835. }
  2836. static char mg_getc(struct mg_connection *conn)
  2837. {
  2838. char c;
  2839. if (conn == NULL) {
  2840. return 0;
  2841. }
  2842. conn->content_len++;
  2843. if (mg_read_inner(conn, &c, 1) <= 0) {
  2844. return (char)0;
  2845. }
  2846. return c;
  2847. }
  2848. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  2849. {
  2850. if (len > INT_MAX)
  2851. len = INT_MAX;
  2852. if (conn == NULL)
  2853. return 0;
  2854. if (conn->is_chunked) {
  2855. size_t all_read = 0;
  2856. while (len > 0) {
  2857. if (conn->chunk_remainder) {
  2858. /* copy from the remainder of the last received chunk */
  2859. long read_ret;
  2860. size_t read_now =
  2861. ((conn->chunk_remainder > len) ? (len)
  2862. : (conn->chunk_remainder));
  2863. conn->content_len += (int)read_now;
  2864. read_ret =
  2865. mg_read_inner(conn, (char *)buf + all_read, read_now);
  2866. all_read += (size_t)read_ret;
  2867. conn->chunk_remainder -= read_now;
  2868. len -= read_now;
  2869. if (conn->chunk_remainder == 0) {
  2870. /* the rest of the data in the current chunk has been read
  2871. */
  2872. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  2873. /* Protocol violation */
  2874. return -1;
  2875. }
  2876. }
  2877. } else {
  2878. /* fetch a new chunk */
  2879. int i = 0;
  2880. char lenbuf[64];
  2881. char *end = 0;
  2882. unsigned long chunkSize = 0;
  2883. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  2884. lenbuf[i] = mg_getc(conn);
  2885. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r')
  2886. continue;
  2887. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  2888. lenbuf[i + 1] = 0;
  2889. chunkSize = strtoul(lenbuf, &end, 16);
  2890. break;
  2891. }
  2892. if (!isalnum(lenbuf[i])) {
  2893. /* illegal character for chunk length */
  2894. return -1;
  2895. }
  2896. }
  2897. if ((end == NULL) || (*end != '\r')) {
  2898. /* chunksize not set correctly */
  2899. return -1;
  2900. }
  2901. conn->chunk_remainder = chunkSize;
  2902. if (chunkSize == 0) {
  2903. /* regular end of content */
  2904. conn->is_chunked = 2;
  2905. break;
  2906. }
  2907. }
  2908. }
  2909. return (int)all_read;
  2910. }
  2911. return mg_read_inner(conn, buf, len);
  2912. }
  2913. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  2914. {
  2915. time_t now;
  2916. int64_t n, total, allowed;
  2917. if (conn == NULL) {
  2918. return 0;
  2919. }
  2920. if (conn->throttle > 0) {
  2921. if ((now = time(NULL)) != conn->last_throttle_time) {
  2922. conn->last_throttle_time = now;
  2923. conn->last_throttle_bytes = 0;
  2924. }
  2925. allowed = conn->throttle - conn->last_throttle_bytes;
  2926. if (allowed > (int64_t)len) {
  2927. allowed = (int64_t)len;
  2928. }
  2929. if ((total = push_all(conn->ctx,
  2930. NULL,
  2931. conn->client.sock,
  2932. conn->ssl,
  2933. (const char *)buf,
  2934. (int64_t)allowed)) == allowed) {
  2935. buf = (char *)buf + total;
  2936. conn->last_throttle_bytes += total;
  2937. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  2938. allowed = conn->throttle > (int64_t)len - total
  2939. ? (int64_t)len - total
  2940. : conn->throttle;
  2941. if ((n = push_all(conn->ctx,
  2942. NULL,
  2943. conn->client.sock,
  2944. conn->ssl,
  2945. (const char *)buf,
  2946. (int64_t)allowed)) != allowed) {
  2947. break;
  2948. }
  2949. sleep(1);
  2950. conn->last_throttle_bytes = allowed;
  2951. conn->last_throttle_time = time(NULL);
  2952. buf = (char *)buf + n;
  2953. total += n;
  2954. }
  2955. }
  2956. } else {
  2957. total = push_all(conn->ctx,
  2958. NULL,
  2959. conn->client.sock,
  2960. conn->ssl,
  2961. (const char *)buf,
  2962. (int64_t)len);
  2963. }
  2964. return (int)total;
  2965. }
  2966. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  2967. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  2968. {
  2969. va_list ap_copy;
  2970. size_t size = MG_BUF_LEN;
  2971. int len = -1;
  2972. *buf = NULL;
  2973. while (len == -1) {
  2974. if (*buf)
  2975. mg_free(*buf);
  2976. *buf = (char *)mg_malloc(size *= 4);
  2977. if (!*buf)
  2978. break;
  2979. va_copy(ap_copy, ap);
  2980. len = vsnprintf(*buf, size, fmt, ap_copy);
  2981. va_end(ap_copy);
  2982. }
  2983. return len;
  2984. }
  2985. /* Print message to buffer. If buffer is large enough to hold the message,
  2986. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  2987. * and return allocated buffer. */
  2988. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  2989. {
  2990. va_list ap_copy;
  2991. int len;
  2992. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  2993. * buffer is too small. Also, older versions of msvcrt.dll do not have
  2994. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  2995. * Therefore, we make two passes: on first pass, get required message
  2996. * length.
  2997. * On second pass, actually print the message. */
  2998. va_copy(ap_copy, ap);
  2999. len = vsnprintf(NULL, 0, fmt, ap_copy);
  3000. va_end(ap_copy);
  3001. if (len < 0) {
  3002. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3003. * Switch to alternative code path that uses incremental allocations.
  3004. */
  3005. va_copy(ap_copy, ap);
  3006. len = alloc_vprintf2(buf, fmt, ap);
  3007. va_end(ap_copy);
  3008. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0 &&
  3009. (*buf = (char *)mg_malloc(size)) == NULL) {
  3010. len = -1; /* Allocation failed, mark failure */
  3011. } else {
  3012. va_copy(ap_copy, ap);
  3013. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  3014. va_end(ap_copy);
  3015. }
  3016. return len;
  3017. }
  3018. static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3019. {
  3020. char mem[MG_BUF_LEN], *buf = mem;
  3021. int len;
  3022. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3023. len = mg_write(conn, buf, (size_t)len);
  3024. }
  3025. if (buf != mem && buf != NULL) {
  3026. mg_free(buf);
  3027. }
  3028. return len;
  3029. }
  3030. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3031. {
  3032. va_list ap;
  3033. int result;
  3034. va_start(ap, fmt);
  3035. result = mg_vprintf(conn, fmt, ap);
  3036. va_end(ap);
  3037. return result;
  3038. }
  3039. int mg_url_decode(const char *src,
  3040. int src_len,
  3041. char *dst,
  3042. int dst_len,
  3043. int is_form_url_encoded)
  3044. {
  3045. int i, j, a, b;
  3046. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3047. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3048. if (i < src_len - 2 && src[i] == '%' &&
  3049. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  3050. isxdigit(*(const unsigned char *)(src + i + 2))) {
  3051. a = tolower(*(const unsigned char *)(src + i + 1));
  3052. b = tolower(*(const unsigned char *)(src + i + 2));
  3053. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3054. i += 2;
  3055. } else if (is_form_url_encoded && src[i] == '+') {
  3056. dst[j] = ' ';
  3057. } else {
  3058. dst[j] = src[i];
  3059. }
  3060. }
  3061. dst[j] = '\0'; /* Null-terminate the destination */
  3062. return i >= src_len ? j : -1;
  3063. }
  3064. int mg_get_var(const char *data,
  3065. size_t data_len,
  3066. const char *name,
  3067. char *dst,
  3068. size_t dst_len)
  3069. {
  3070. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3071. }
  3072. int mg_get_var2(const char *data,
  3073. size_t data_len,
  3074. const char *name,
  3075. char *dst,
  3076. size_t dst_len,
  3077. size_t occurrence)
  3078. {
  3079. const char *p, *e, *s;
  3080. size_t name_len;
  3081. int len;
  3082. if (dst == NULL || dst_len == 0) {
  3083. len = -2;
  3084. } else if (data == NULL || name == NULL || data_len == 0) {
  3085. len = -1;
  3086. dst[0] = '\0';
  3087. } else {
  3088. name_len = strlen(name);
  3089. e = data + data_len;
  3090. len = -1;
  3091. dst[0] = '\0';
  3092. /* data is "var1=val1&var2=val2...". Find variable first */
  3093. for (p = data; p + name_len < e; p++) {
  3094. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3095. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3096. /* Point p to variable value */
  3097. p += name_len + 1;
  3098. /* Point s to the end of the value */
  3099. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3100. if (s == NULL) {
  3101. s = e;
  3102. }
  3103. /* assert(s >= p); */
  3104. if (s < p) {
  3105. return -3;
  3106. }
  3107. /* Decode variable into destination buffer */
  3108. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3109. /* Redirect error code from -1 to -2 (destination buffer too
  3110. * small). */
  3111. if (len == -1) {
  3112. len = -2;
  3113. }
  3114. break;
  3115. }
  3116. }
  3117. }
  3118. return len;
  3119. }
  3120. int mg_get_cookie(const char *cookie_header,
  3121. const char *var_name,
  3122. char *dst,
  3123. size_t dst_size)
  3124. {
  3125. const char *s, *p, *end;
  3126. int name_len, len = -1;
  3127. if (dst == NULL || dst_size == 0) {
  3128. len = -2;
  3129. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3130. len = -1;
  3131. dst[0] = '\0';
  3132. } else {
  3133. name_len = (int)strlen(var_name);
  3134. end = s + strlen(s);
  3135. dst[0] = '\0';
  3136. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3137. if (s[name_len] == '=') {
  3138. s += name_len + 1;
  3139. if ((p = strchr(s, ' ')) == NULL)
  3140. p = end;
  3141. if (p[-1] == ';')
  3142. p--;
  3143. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3144. s++;
  3145. p--;
  3146. }
  3147. if ((size_t)(p - s) < dst_size) {
  3148. len = (int)(p - s);
  3149. mg_strlcpy(dst, s, (size_t)len + 1);
  3150. } else {
  3151. len = -3;
  3152. }
  3153. break;
  3154. }
  3155. }
  3156. }
  3157. return len;
  3158. }
  3159. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3160. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3161. {
  3162. static const char *b64 =
  3163. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3164. int i, j, a, b, c;
  3165. for (i = j = 0; i < src_len; i += 3) {
  3166. a = src[i];
  3167. b = i + 1 >= src_len ? 0 : src[i + 1];
  3168. c = i + 2 >= src_len ? 0 : src[i + 2];
  3169. dst[j++] = b64[a >> 2];
  3170. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3171. if (i + 1 < src_len) {
  3172. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3173. }
  3174. if (i + 2 < src_len) {
  3175. dst[j++] = b64[c & 63];
  3176. }
  3177. }
  3178. while (j % 4 != 0) {
  3179. dst[j++] = '=';
  3180. }
  3181. dst[j++] = '\0';
  3182. }
  3183. #endif
  3184. #if defined(USE_LUA)
  3185. static unsigned char b64reverse(char letter)
  3186. {
  3187. if (letter >= 'A' && letter <= 'Z')
  3188. return letter - 'A';
  3189. if (letter >= 'a' && letter <= 'z')
  3190. return letter - 'a' + 26;
  3191. if (letter >= '0' && letter <= '9')
  3192. return letter - '0' + 52;
  3193. if (letter == '+')
  3194. return 62;
  3195. if (letter == '/')
  3196. return 63;
  3197. if (letter == '=')
  3198. return 255; /* normal end */
  3199. return 254; /* error */
  3200. }
  3201. static int
  3202. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3203. {
  3204. int i;
  3205. unsigned char a, b, c, d;
  3206. *dst_len = 0;
  3207. for (i = 0; i < src_len; i += 4) {
  3208. a = b64reverse(src[i]);
  3209. if (a >= 254)
  3210. return i;
  3211. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3212. if (b >= 254)
  3213. return i + 1;
  3214. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3215. if (c == 254)
  3216. return i + 2;
  3217. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3218. if (c == 254)
  3219. return i + 3;
  3220. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3221. if (c != 255) {
  3222. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3223. if (d != 255) {
  3224. dst[(*dst_len)++] = (c << 6) + d;
  3225. }
  3226. }
  3227. }
  3228. return -1;
  3229. }
  3230. #endif
  3231. static int is_put_or_delete_method(const struct mg_connection *conn)
  3232. {
  3233. if (conn) {
  3234. const char *s = conn->request_info.request_method;
  3235. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  3236. !strcmp(s, "MKCOL"));
  3237. }
  3238. return 0;
  3239. }
  3240. static void
  3241. interpret_uri(struct mg_connection *conn, /* in: request */
  3242. char *filename, /* out: filename */
  3243. size_t filename_buf_len, /* in: size of filename buffer */
  3244. struct file *filep, /* out: file structure */
  3245. int *is_script_ressource, /* out: handled by a script? */
  3246. int *is_websocket_request, /* out: websocket connetion? */
  3247. int *is_put_or_delete_request /* out: put/delete a file? */
  3248. )
  3249. {
  3250. if (conn && conn->ctx) {
  3251. const char *uri = conn->request_info.uri;
  3252. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3253. #if !defined(NO_FILES)
  3254. const char *rewrite;
  3255. struct vec a, b;
  3256. char *p;
  3257. int match_len;
  3258. char gz_path[PATH_MAX];
  3259. char const *accept_encoding;
  3260. #endif
  3261. memset(filep, 0, sizeof(*filep));
  3262. *filename = 0;
  3263. *is_script_ressource = 0;
  3264. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3265. #if defined(USE_WEBSOCKET)
  3266. *is_websocket_request = is_websocket_protocol(conn);
  3267. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3268. root = conn->ctx->config[WEBSOCKET_ROOT];
  3269. }
  3270. #else
  3271. *is_websocket_request = 0;
  3272. #endif
  3273. #if !defined(NO_FILES)
  3274. /* Note that root == NULL is a regular use case here. This occurs,
  3275. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3276. * config is not required. */
  3277. if (root == NULL) {
  3278. /* all file related outputs have already been set to 0, just return
  3279. */
  3280. return;
  3281. }
  3282. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3283. * of the path one byte on the right.
  3284. * If document_root is NULL, leave the file empty. */
  3285. mg_snprintf(conn, filename, filename_buf_len - 1, "%s%s", root, uri);
  3286. rewrite = conn->ctx->config[REWRITE];
  3287. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3288. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3289. mg_snprintf(conn,
  3290. filename,
  3291. filename_buf_len - 1,
  3292. "%.*s%s",
  3293. (int)b.len,
  3294. b.ptr,
  3295. uri + match_len);
  3296. break;
  3297. }
  3298. }
  3299. /* Local file path and name, corresponding to requested URI
  3300. * is now stored in "filename" variable. */
  3301. if (mg_stat(conn, filename, filep)) {
  3302. /* File exists. Check if it is a script type. */
  3303. if (0
  3304. #if !defined(NO_CGI)
  3305. ||
  3306. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3307. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3308. filename) > 0
  3309. #endif
  3310. #if defined(USE_LUA)
  3311. ||
  3312. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3313. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3314. filename) > 0
  3315. #endif
  3316. ) {
  3317. /* The request addresses a CGI script or a Lua script. The URI
  3318. * corresponds to the script itself (like /path/script.cgi),
  3319. * and there is no additional resource path
  3320. * (like /path/script.cgi/something).
  3321. * Requests that modify (replace or delete) a resource, like
  3322. * PUT and DELETE requests, should replace/delete the script
  3323. * file.
  3324. * Requests that read or write from/to a resource, like GET and
  3325. * POST requests, should call the script and return the
  3326. * generated response. */
  3327. *is_script_ressource = !*is_put_or_delete_request;
  3328. }
  3329. return;
  3330. }
  3331. /* If we can't find the actual file, look for the file
  3332. * with the same name but a .gz extension. If we find it,
  3333. * use that and set the gzipped flag in the file struct
  3334. * to indicate that the response need to have the content-
  3335. * encoding: gzip header.
  3336. * We can only do this if the browser declares support. */
  3337. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  3338. NULL) {
  3339. if (strstr(accept_encoding, "gzip") != NULL) {
  3340. snprintf(gz_path, sizeof(gz_path), "%s.gz", filename);
  3341. if (mg_stat(conn, gz_path, filep)) {
  3342. if (filep)
  3343. filep->gzipped = 1;
  3344. /* Currently gz files can not be scripts. */
  3345. return;
  3346. }
  3347. }
  3348. }
  3349. /* Support PATH_INFO for CGI scripts. */
  3350. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3351. if (*p == '/') {
  3352. *p = '\0';
  3353. if ((0
  3354. #if !defined(NO_CGI)
  3355. ||
  3356. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3357. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3358. filename) > 0
  3359. #endif
  3360. #if defined(USE_LUA)
  3361. ||
  3362. match_prefix(
  3363. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3364. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3365. filename) > 0
  3366. #endif
  3367. ) &&
  3368. mg_stat(conn, filename, filep)) {
  3369. /* Shift PATH_INFO block one character right, e.g.
  3370. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3371. * conn->path_info is pointing to the local variable "path"
  3372. * declared in handle_request(), so PATH_INFO is not valid
  3373. * after handle_request returns. */
  3374. conn->path_info = p + 1;
  3375. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3376. * trailing \0 */
  3377. p[1] = '/';
  3378. *is_script_ressource = 1;
  3379. break;
  3380. } else {
  3381. *p = '/';
  3382. }
  3383. }
  3384. }
  3385. #endif
  3386. }
  3387. }
  3388. /* Check whether full request is buffered. Return:
  3389. * -1 if request is malformed
  3390. * 0 if request is not yet fully buffered
  3391. * >0 actual request length, including last \r\n\r\n */
  3392. static int get_request_len(const char *buf, int buflen)
  3393. {
  3394. const char *s, *e;
  3395. int len = 0;
  3396. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3397. /* Control characters are not allowed but >=128 is. */
  3398. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  3399. *(const unsigned char *)s < 128) {
  3400. len = -1;
  3401. break; /* [i_a] abort scan as soon as one malformed character is
  3402. * found; */
  3403. /* don't let subsequent \r\n\r\n win us over anyhow */
  3404. } else if (s[0] == '\n' && s[1] == '\n') {
  3405. len = (int)(s - buf) + 2;
  3406. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3407. len = (int)(s - buf) + 3;
  3408. }
  3409. return len;
  3410. }
  3411. /* Convert month to the month number. Return -1 on error, or month number */
  3412. static int get_month_index(const char *s)
  3413. {
  3414. size_t i;
  3415. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  3416. if (!strcmp(s, month_names[i]))
  3417. return (int)i;
  3418. return -1;
  3419. }
  3420. static int num_leap_years(int year)
  3421. {
  3422. return year / 4 - year / 100 + year / 400;
  3423. }
  3424. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3425. static time_t parse_date_string(const char *datetime)
  3426. {
  3427. static const unsigned short days_before_month[] = {
  3428. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3429. char month_str[32] = {0};
  3430. int second, minute, hour, day, month, year, leap_days, days;
  3431. time_t result = (time_t)0;
  3432. if ((sscanf(datetime,
  3433. "%d/%3s/%d %d:%d:%d",
  3434. &day,
  3435. month_str,
  3436. &year,
  3437. &hour,
  3438. &minute,
  3439. &second) == 6) ||
  3440. (sscanf(datetime,
  3441. "%d %3s %d %d:%d:%d",
  3442. &day,
  3443. month_str,
  3444. &year,
  3445. &hour,
  3446. &minute,
  3447. &second) == 6) ||
  3448. (sscanf(datetime,
  3449. "%*3s, %d %3s %d %d:%d:%d",
  3450. &day,
  3451. month_str,
  3452. &year,
  3453. &hour,
  3454. &minute,
  3455. &second) == 6) ||
  3456. (sscanf(datetime,
  3457. "%d-%3s-%d %d:%d:%d",
  3458. &day,
  3459. month_str,
  3460. &year,
  3461. &hour,
  3462. &minute,
  3463. &second) == 6)) {
  3464. month = get_month_index(month_str);
  3465. if ((month >= 0) && (year > 1970)) {
  3466. leap_days = num_leap_years(year) - num_leap_years(1970);
  3467. year -= 1970;
  3468. days =
  3469. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3470. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3471. minute * 60 + second;
  3472. }
  3473. }
  3474. return result;
  3475. }
  3476. /* Protect against directory disclosure attack by removing '..',
  3477. * excessive '/' and '\' characters */
  3478. static void remove_double_dots_and_double_slashes(char *s)
  3479. {
  3480. char *p = s;
  3481. while (*s != '\0') {
  3482. *p++ = *s++;
  3483. if (s[-1] == '/' || s[-1] == '\\') {
  3484. /* Skip all following slashes, backslashes and double-dots */
  3485. while (s[0] != '\0') {
  3486. if (s[0] == '/' || s[0] == '\\') {
  3487. s++;
  3488. } else if (s[0] == '.' && s[1] == '.') {
  3489. s += 2;
  3490. } else {
  3491. break;
  3492. }
  3493. }
  3494. }
  3495. }
  3496. *p = '\0';
  3497. }
  3498. static const struct {
  3499. const char *extension;
  3500. size_t ext_len;
  3501. const char *mime_type;
  3502. } builtin_mime_types[] = {
  3503. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3504. * application types */
  3505. {".doc", 4, "application/msword"},
  3506. {".eps", 4, "application/postscript"},
  3507. {".exe", 4, "application/octet-stream"},
  3508. {".js", 3, "application/javascript"},
  3509. {".json", 5, "application/json"},
  3510. {".pdf", 4, "application/pdf"},
  3511. {".ps", 3, "application/postscript"},
  3512. {".rtf", 4, "application/rtf"},
  3513. {".xhtml", 6, "application/xhtml+xml"},
  3514. {".xsl", 4, "application/xml"},
  3515. {".xslt", 5, "application/xml"},
  3516. /* audio */
  3517. {".mp3", 4, "audio/mpeg"},
  3518. {".oga", 4, "audio/ogg"},
  3519. {".ogg", 4, "audio/ogg"},
  3520. /* image */
  3521. {".gif", 4, "image/gif"},
  3522. {".ief", 4, "image/ief"},
  3523. {".jpeg", 5, "image/jpeg"},
  3524. {".jpg", 4, "image/jpeg"},
  3525. {".jpm", 4, "image/jpm"},
  3526. {".jpx", 4, "image/jpx"},
  3527. {".png", 4, "image/png"},
  3528. {".svg", 4, "image/svg+xml"},
  3529. {".tif", 4, "image/tiff"},
  3530. {".tiff", 5, "image/tiff"},
  3531. /* model */
  3532. {".wrl", 4, "model/vrml"},
  3533. /* text */
  3534. {".css", 4, "text/css"},
  3535. {".csv", 4, "text/csv"},
  3536. {".htm", 4, "text/html"},
  3537. {".html", 5, "text/html"},
  3538. {".sgm", 4, "text/sgml"},
  3539. {".shtm", 5, "text/html"},
  3540. {".shtml", 6, "text/html"},
  3541. {".txt", 4, "text/plain"},
  3542. {".xml", 4, "text/xml"},
  3543. /* video */
  3544. {".mov", 4, "video/quicktime"},
  3545. {".mp4", 4, "video/mp4"},
  3546. {".mpeg", 5, "video/mpeg"},
  3547. {".mpg", 4, "video/mpeg"},
  3548. {".ogv", 4, "video/ogg"},
  3549. {".qt", 3, "video/quicktime"},
  3550. /* not registered types
  3551. * (http://reference.sitepoint.com/html/mime-types-full,
  3552. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3553. {".arj", 4, "application/x-arj-compressed"},
  3554. {".gz", 3, "application/x-gunzip"},
  3555. {".rar", 4, "application/x-arj-compressed"},
  3556. {".swf", 4, "application/x-shockwave-flash"},
  3557. {".tar", 4, "application/x-tar"},
  3558. {".tgz", 4, "application/x-tar-gz"},
  3559. {".torrent", 8, "application/x-bittorrent"},
  3560. {".ppt", 4, "application/x-mspowerpoint"},
  3561. {".xls", 4, "application/x-msexcel"},
  3562. {".zip", 4, "application/x-zip-compressed"},
  3563. {".aac",
  3564. 4,
  3565. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3566. {".aif", 4, "audio/x-aif"},
  3567. {".m3u", 4, "audio/x-mpegurl"},
  3568. {".mid", 4, "audio/x-midi"},
  3569. {".ra", 3, "audio/x-pn-realaudio"},
  3570. {".ram", 4, "audio/x-pn-realaudio"},
  3571. {".wav", 4, "audio/x-wav"},
  3572. {".bmp", 4, "image/bmp"},
  3573. {".ico", 4, "image/x-icon"},
  3574. {".pct", 4, "image/x-pct"},
  3575. {".pict", 5, "image/pict"},
  3576. {".rgb", 4, "image/x-rgb"},
  3577. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3578. {".asf", 4, "video/x-ms-asf"},
  3579. {".avi", 4, "video/x-msvideo"},
  3580. {".m4v", 4, "video/x-m4v"},
  3581. {NULL, 0, NULL}};
  3582. const char *mg_get_builtin_mime_type(const char *path)
  3583. {
  3584. const char *ext;
  3585. size_t i, path_len;
  3586. path_len = strlen(path);
  3587. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3588. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3589. if (path_len > builtin_mime_types[i].ext_len &&
  3590. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3591. return builtin_mime_types[i].mime_type;
  3592. }
  3593. }
  3594. return "text/plain";
  3595. }
  3596. /* Look at the "path" extension and figure what mime type it has.
  3597. * Store mime type in the vector. */
  3598. static void
  3599. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  3600. {
  3601. struct vec ext_vec, mime_vec;
  3602. const char *list, *ext;
  3603. size_t path_len;
  3604. path_len = strlen(path);
  3605. if (ctx == NULL || vec == NULL) {
  3606. return;
  3607. }
  3608. /* Scan user-defined mime types first, in case user wants to
  3609. * override default mime types. */
  3610. list = ctx->config[EXTRA_MIME_TYPES];
  3611. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3612. /* ext now points to the path suffix */
  3613. ext = path + path_len - ext_vec.len;
  3614. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3615. *vec = mime_vec;
  3616. return;
  3617. }
  3618. }
  3619. vec->ptr = mg_get_builtin_mime_type(path);
  3620. vec->len = strlen(vec->ptr);
  3621. }
  3622. /* Stringify binary data. Output buffer must be twice as big as input,
  3623. * because each byte takes 2 bytes in string representation */
  3624. static void bin2str(char *to, const unsigned char *p, size_t len)
  3625. {
  3626. static const char *hex = "0123456789abcdef";
  3627. for (; len--; p++) {
  3628. *to++ = hex[p[0] >> 4];
  3629. *to++ = hex[p[0] & 0x0f];
  3630. }
  3631. *to = '\0';
  3632. }
  3633. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3634. char *mg_md5(char buf[33], ...)
  3635. {
  3636. md5_byte_t hash[16];
  3637. const char *p;
  3638. va_list ap;
  3639. md5_state_t ctx;
  3640. md5_init(&ctx);
  3641. va_start(ap, buf);
  3642. while ((p = va_arg(ap, const char *)) != NULL) {
  3643. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  3644. }
  3645. va_end(ap);
  3646. md5_finish(&ctx, hash);
  3647. bin2str(buf, hash, sizeof(hash));
  3648. return buf;
  3649. }
  3650. /* Check the user's password, return 1 if OK */
  3651. static int check_password(const char *method,
  3652. const char *ha1,
  3653. const char *uri,
  3654. const char *nonce,
  3655. const char *nc,
  3656. const char *cnonce,
  3657. const char *qop,
  3658. const char *response)
  3659. {
  3660. char ha2[32 + 1], expected_response[32 + 1];
  3661. /* Some of the parameters may be NULL */
  3662. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3663. qop == NULL || response == NULL) {
  3664. return 0;
  3665. }
  3666. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3667. /* TODO(lsm): check for authentication timeout */
  3668. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3669. strlen(response) != 32
  3670. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3671. ) {
  3672. return 0;
  3673. }
  3674. mg_md5(ha2, method, ":", uri, NULL);
  3675. mg_md5(expected_response,
  3676. ha1,
  3677. ":",
  3678. nonce,
  3679. ":",
  3680. nc,
  3681. ":",
  3682. cnonce,
  3683. ":",
  3684. qop,
  3685. ":",
  3686. ha2,
  3687. NULL);
  3688. return mg_strcasecmp(response, expected_response) == 0;
  3689. }
  3690. /* Use the global passwords file, if specified by auth_gpass option,
  3691. * or search for .htpasswd in the requested directory. */
  3692. static void
  3693. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  3694. {
  3695. if (conn != NULL && conn->ctx != NULL) {
  3696. char name[PATH_MAX];
  3697. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3698. struct file file = STRUCT_FILE_INITIALIZER;
  3699. if (gpass != NULL) {
  3700. /* Use global passwords file */
  3701. if (!mg_fopen(conn, gpass, "r", filep)) {
  3702. #ifdef DEBUG
  3703. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3704. #endif
  3705. }
  3706. /* Important: using local struct file to test path for is_directory
  3707. * flag.
  3708. * If filep is used, mg_stat() makes it appear as if auth file was
  3709. * opened. */
  3710. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3711. mg_snprintf(conn,
  3712. name,
  3713. sizeof(name),
  3714. "%s%c%s",
  3715. path,
  3716. '/',
  3717. PASSWORDS_FILE_NAME);
  3718. if (!mg_fopen(conn, name, "r", filep)) {
  3719. #ifdef DEBUG
  3720. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3721. #endif
  3722. }
  3723. } else {
  3724. /* Try to find .htpasswd in requested directory. */
  3725. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  3726. if (e[0] == '/') {
  3727. break;
  3728. }
  3729. }
  3730. mg_snprintf(conn,
  3731. name,
  3732. sizeof(name),
  3733. "%.*s%c%s",
  3734. (int)(e - p),
  3735. p,
  3736. '/',
  3737. PASSWORDS_FILE_NAME);
  3738. if (!mg_fopen(conn, name, "r", filep)) {
  3739. #ifdef DEBUG
  3740. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3741. #endif
  3742. }
  3743. }
  3744. }
  3745. }
  3746. /* Parsed Authorization header */
  3747. struct ah {
  3748. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  3749. };
  3750. /* Return 1 on success. Always initializes the ah structure. */
  3751. static int parse_auth_header(struct mg_connection *conn,
  3752. char *buf,
  3753. size_t buf_size,
  3754. struct ah *ah)
  3755. {
  3756. char *name, *value, *s;
  3757. const char *auth_header;
  3758. unsigned long nonce;
  3759. if (!ah || !conn)
  3760. return 0;
  3761. (void)memset(ah, 0, sizeof(*ah));
  3762. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  3763. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  3764. return 0;
  3765. }
  3766. /* Make modifiable copy of the auth header */
  3767. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  3768. s = buf;
  3769. /* Parse authorization header */
  3770. for (;;) {
  3771. /* Gobble initial spaces */
  3772. while (isspace(*(unsigned char *)s)) {
  3773. s++;
  3774. }
  3775. name = skip_quoted(&s, "=", " ", 0);
  3776. /* Value is either quote-delimited, or ends at first comma or space. */
  3777. if (s[0] == '\"') {
  3778. s++;
  3779. value = skip_quoted(&s, "\"", " ", '\\');
  3780. if (s[0] == ',') {
  3781. s++;
  3782. }
  3783. } else {
  3784. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  3785. * spaces */
  3786. }
  3787. if (*name == '\0') {
  3788. break;
  3789. }
  3790. if (!strcmp(name, "username")) {
  3791. ah->user = value;
  3792. } else if (!strcmp(name, "cnonce")) {
  3793. ah->cnonce = value;
  3794. } else if (!strcmp(name, "response")) {
  3795. ah->response = value;
  3796. } else if (!strcmp(name, "uri")) {
  3797. ah->uri = value;
  3798. } else if (!strcmp(name, "qop")) {
  3799. ah->qop = value;
  3800. } else if (!strcmp(name, "nc")) {
  3801. ah->nc = value;
  3802. } else if (!strcmp(name, "nonce")) {
  3803. ah->nonce = value;
  3804. }
  3805. }
  3806. #ifndef NO_NONCE_CHECK
  3807. /* Convert the nonce from the client to a number and check it. */
  3808. /* Server side nonce check is valuable in all situations but one: if the
  3809. * server restarts frequently,
  3810. * but the client should not see that, so the server should accept nonces
  3811. * from
  3812. * previous starts. */
  3813. if (ah->nonce == NULL) {
  3814. return 0;
  3815. }
  3816. s = NULL;
  3817. nonce = strtoul(ah->nonce, &s, 10);
  3818. if ((s == NULL) || (*s != 0)) {
  3819. return 0;
  3820. }
  3821. nonce ^= (uintptr_t)(conn->ctx);
  3822. if (nonce < conn->ctx->start_time) {
  3823. /* nonce is from a previous start of the server and no longer valid
  3824. * (replay attack?) */
  3825. return 0;
  3826. }
  3827. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  3828. return 0;
  3829. }
  3830. #endif
  3831. /* CGI needs it as REMOTE_USER */
  3832. if (ah->user != NULL) {
  3833. conn->request_info.remote_user = mg_strdup(ah->user);
  3834. } else {
  3835. return 0;
  3836. }
  3837. return 1;
  3838. }
  3839. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  3840. {
  3841. char *eof;
  3842. size_t len;
  3843. char *memend;
  3844. if (!filep)
  3845. return NULL;
  3846. if (filep->membuf != NULL && *p != NULL) {
  3847. memend = (char *)&filep->membuf[filep->size];
  3848. /* Search for \n from p till the end of stream */
  3849. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  3850. if (eof != NULL) {
  3851. eof += 1; /* Include \n */
  3852. } else {
  3853. eof = memend; /* Copy remaining data */
  3854. }
  3855. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  3856. memcpy(buf, *p, len);
  3857. buf[len] = '\0';
  3858. *p += len;
  3859. return len ? eof : NULL;
  3860. } else if (filep->fp != NULL) {
  3861. return fgets(buf, (int)size, filep->fp);
  3862. } else {
  3863. return NULL;
  3864. }
  3865. }
  3866. struct read_auth_file_struct {
  3867. struct mg_connection *conn;
  3868. struct ah ah;
  3869. char *domain;
  3870. char buf[256 + 256 + 40];
  3871. char *f_user;
  3872. char *f_domain;
  3873. char *f_ha1;
  3874. };
  3875. static int read_auth_file(struct file *filep,
  3876. struct read_auth_file_struct *workdata)
  3877. {
  3878. char *p;
  3879. int is_authorized = 0;
  3880. struct file fp;
  3881. size_t l;
  3882. if (!filep || !workdata)
  3883. return 0;
  3884. /* Loop over passwords file */
  3885. p = (char *)filep->membuf;
  3886. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  3887. l = strlen(workdata->buf);
  3888. while (l > 0) {
  3889. if (isspace(workdata->buf[l - 1]) ||
  3890. iscntrl(workdata->buf[l - 1])) {
  3891. l--;
  3892. workdata->buf[l] = 0;
  3893. } else
  3894. break;
  3895. }
  3896. if (l < 1)
  3897. continue;
  3898. workdata->f_user = workdata->buf;
  3899. if (workdata->f_user[0] == ':') {
  3900. /* user names may not contain a ':' and may not be empty,
  3901. * so lines starting with ':' may be used for a special purpose */
  3902. if (workdata->f_user[1] == '#') {
  3903. /* :# is a comment */
  3904. continue;
  3905. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  3906. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  3907. is_authorized = read_auth_file(&fp, workdata);
  3908. mg_fclose(&fp);
  3909. } else {
  3910. mg_cry(workdata->conn,
  3911. "%s: cannot open authorization file: %s",
  3912. __func__,
  3913. workdata->buf);
  3914. }
  3915. continue;
  3916. }
  3917. /* everything is invalid for the moment (might change in the
  3918. * future) */
  3919. mg_cry(workdata->conn,
  3920. "%s: syntax error in authorization file: %s",
  3921. __func__,
  3922. workdata->buf);
  3923. continue;
  3924. }
  3925. workdata->f_domain = strchr(workdata->f_user, ':');
  3926. if (workdata->f_domain == NULL) {
  3927. mg_cry(workdata->conn,
  3928. "%s: syntax error in authorization file: %s",
  3929. __func__,
  3930. workdata->buf);
  3931. continue;
  3932. }
  3933. *(workdata->f_domain) = 0;
  3934. (workdata->f_domain)++;
  3935. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  3936. if (workdata->f_ha1 == NULL) {
  3937. mg_cry(workdata->conn,
  3938. "%s: syntax error in authorization file: %s",
  3939. __func__,
  3940. workdata->buf);
  3941. continue;
  3942. }
  3943. *(workdata->f_ha1) = 0;
  3944. (workdata->f_ha1)++;
  3945. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  3946. !strcmp(workdata->domain, workdata->f_domain)) {
  3947. return check_password(workdata->conn->request_info.request_method,
  3948. workdata->f_ha1,
  3949. workdata->ah.uri,
  3950. workdata->ah.nonce,
  3951. workdata->ah.nc,
  3952. workdata->ah.cnonce,
  3953. workdata->ah.qop,
  3954. workdata->ah.response);
  3955. }
  3956. }
  3957. return is_authorized;
  3958. }
  3959. /* Authorize against the opened passwords file. Return 1 if authorized. */
  3960. static int authorize(struct mg_connection *conn, struct file *filep)
  3961. {
  3962. struct read_auth_file_struct workdata;
  3963. char buf[MG_BUF_LEN];
  3964. if (!conn || !conn->ctx)
  3965. return 0;
  3966. memset(&workdata, 0, sizeof(workdata));
  3967. workdata.conn = conn;
  3968. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  3969. return 0;
  3970. }
  3971. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  3972. return read_auth_file(filep, &workdata);
  3973. }
  3974. /* Return 1 if request is authorised, 0 otherwise. */
  3975. static int check_authorization(struct mg_connection *conn, const char *path)
  3976. {
  3977. char fname[PATH_MAX];
  3978. struct vec uri_vec, filename_vec;
  3979. const char *list;
  3980. struct file file = STRUCT_FILE_INITIALIZER;
  3981. int authorized = 1;
  3982. if (!conn || !conn->ctx)
  3983. return 0;
  3984. list = conn->ctx->config[PROTECT_URI];
  3985. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  3986. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  3987. mg_snprintf(conn,
  3988. fname,
  3989. sizeof(fname),
  3990. "%.*s",
  3991. (int)filename_vec.len,
  3992. filename_vec.ptr);
  3993. if (!mg_fopen(conn, fname, "r", &file)) {
  3994. mg_cry(conn,
  3995. "%s: cannot open %s: %s",
  3996. __func__,
  3997. fname,
  3998. strerror(errno));
  3999. }
  4000. break;
  4001. }
  4002. }
  4003. if (!is_file_opened(&file)) {
  4004. open_auth_file(conn, path, &file);
  4005. }
  4006. if (is_file_opened(&file)) {
  4007. authorized = authorize(conn, &file);
  4008. mg_fclose(&file);
  4009. }
  4010. return authorized;
  4011. }
  4012. static void send_authorization_request(struct mg_connection *conn)
  4013. {
  4014. char date[64];
  4015. time_t curtime = time(NULL);
  4016. if (conn && conn->ctx) {
  4017. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  4018. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4019. nonce += conn->ctx->nonce_count;
  4020. ++conn->ctx->nonce_count;
  4021. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4022. nonce ^= (uintptr_t)(conn->ctx);
  4023. conn->status_code = 401;
  4024. conn->must_close = 1;
  4025. gmt_time_string(date, sizeof(date), &curtime);
  4026. mg_printf(conn,
  4027. "HTTP/1.1 401 Unauthorized\r\n"
  4028. "Date: %s\r\n"
  4029. "Connection: %s\r\n"
  4030. "Content-Length: 0\r\n"
  4031. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4032. "nonce=\"%lu\"\r\n\r\n",
  4033. date,
  4034. suggest_connection_header(conn),
  4035. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4036. nonce);
  4037. }
  4038. }
  4039. static int is_authorized_for_put(struct mg_connection *conn)
  4040. {
  4041. if (conn) {
  4042. struct file file = STRUCT_FILE_INITIALIZER;
  4043. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4044. int ret = 0;
  4045. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4046. ret = authorize(conn, &file);
  4047. mg_fclose(&file);
  4048. }
  4049. return ret;
  4050. }
  4051. return 0;
  4052. }
  4053. int mg_modify_passwords_file(const char *fname,
  4054. const char *domain,
  4055. const char *user,
  4056. const char *pass)
  4057. {
  4058. int found, i;
  4059. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4060. FILE *fp, *fp2;
  4061. found = 0;
  4062. fp = fp2 = NULL;
  4063. /* Regard empty password as no password - remove user record. */
  4064. if (pass != NULL && pass[0] == '\0') {
  4065. pass = NULL;
  4066. }
  4067. /* Other arguments must not be empty */
  4068. if (fname == NULL || domain == NULL || user == NULL)
  4069. return 0;
  4070. /* Using the given file format, user name and domain must not contain ':'
  4071. */
  4072. if (strchr(user, ':') != NULL)
  4073. return 0;
  4074. if (strchr(domain, ':') != NULL)
  4075. return 0;
  4076. /* Do not allow control characters like newline in user name and domain.
  4077. * Do not allow excessively long names either. */
  4078. for (i = 0; i < 255 && user[i] != 0; i++) {
  4079. if (iscntrl(user[i]))
  4080. return 0;
  4081. }
  4082. if (user[i])
  4083. return 0;
  4084. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4085. if (iscntrl(domain[i]))
  4086. return 0;
  4087. }
  4088. if (domain[i])
  4089. return 0;
  4090. /* Create a temporary file name */
  4091. (void)snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  4092. tmp[sizeof(tmp) - 1] = 0;
  4093. /* Create the file if does not exist */
  4094. if ((fp = fopen(fname, "a+")) != NULL) {
  4095. (void)fclose(fp);
  4096. }
  4097. /* Open the given file and temporary file */
  4098. if ((fp = fopen(fname, "r")) == NULL) {
  4099. return 0;
  4100. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4101. fclose(fp);
  4102. return 0;
  4103. }
  4104. /* Copy the stuff to temporary file */
  4105. while (fgets(line, sizeof(line), fp) != NULL) {
  4106. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4107. continue;
  4108. }
  4109. u[255] = 0;
  4110. d[255] = 0;
  4111. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4112. found++;
  4113. if (pass != NULL) {
  4114. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4115. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4116. }
  4117. } else {
  4118. fprintf(fp2, "%s", line);
  4119. }
  4120. }
  4121. /* If new user, just add it */
  4122. if (!found && pass != NULL) {
  4123. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4124. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4125. }
  4126. /* Close files */
  4127. fclose(fp);
  4128. fclose(fp2);
  4129. /* Put the temp file in place of real file */
  4130. IGNORE_UNUSED_RESULT(remove(fname));
  4131. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4132. return 1;
  4133. }
  4134. static int is_valid_port(unsigned int port) { return port < 0xffff; }
  4135. static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4136. {
  4137. struct addrinfo hints, *res, *ressave;
  4138. int ret = 0;
  4139. memset(&hints, 0, sizeof(struct addrinfo));
  4140. hints.ai_family = af;
  4141. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4142. /* bad src string or bad address family */
  4143. return 0;
  4144. }
  4145. ressave = res;
  4146. while (res) {
  4147. if (dstlen >= res->ai_addrlen) {
  4148. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4149. ret = 1;
  4150. }
  4151. res = res->ai_next;
  4152. }
  4153. freeaddrinfo(ressave);
  4154. return ret;
  4155. }
  4156. static SOCKET conn2(struct mg_context *ctx /* may be null */,
  4157. const char *host,
  4158. int port,
  4159. int use_ssl,
  4160. char *ebuf,
  4161. size_t ebuf_len)
  4162. {
  4163. union usa sa;
  4164. SOCKET sock = INVALID_SOCKET;
  4165. memset(&sa, 0, sizeof(sa));
  4166. if (ebuf_len > 0) {
  4167. *ebuf = 0;
  4168. }
  4169. if (host == NULL) {
  4170. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  4171. return INVALID_SOCKET;
  4172. }
  4173. if (port < 0 || !is_valid_port((unsigned)port)) {
  4174. snprintf(ebuf, ebuf_len, "%s", "invalid port");
  4175. return INVALID_SOCKET;
  4176. }
  4177. if (use_ssl && (SSLv23_client_method == NULL)) {
  4178. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  4179. return INVALID_SOCKET;
  4180. }
  4181. if (mg_inet_pton(AF_INET, host, &sa.sin, sizeof(sa.sin))) {
  4182. sa.sin.sin_port = htons((uint16_t)port);
  4183. #ifdef USE_IPV6
  4184. } else if (mg_inet_pton(AF_INET6, host, &sa.sin6, sizeof(sa.sin6))) {
  4185. sa.sin6.sin6_port = htons((uint16_t)port);
  4186. #endif
  4187. } else {
  4188. snprintf(ebuf, ebuf_len, "%s", "host not found");
  4189. return INVALID_SOCKET;
  4190. }
  4191. sock = socket(PF_INET, SOCK_STREAM, 0);
  4192. if (sock == INVALID_SOCKET) {
  4193. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  4194. return INVALID_SOCKET;
  4195. }
  4196. set_close_on_exec(sock, fc(ctx));
  4197. /* TODO(mid): IPV6 */
  4198. if (connect(sock, (struct sockaddr *)&sa.sin, sizeof(sa.sin)) != 0) {
  4199. snprintf(
  4200. ebuf, ebuf_len, "connect(%s:%d): %s", host, port, strerror(ERRNO));
  4201. closesocket(sock);
  4202. sock = INVALID_SOCKET;
  4203. }
  4204. return sock;
  4205. }
  4206. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  4207. {
  4208. static const char *dont_escape = "._-$,;~()";
  4209. static const char *hex = "0123456789abcdef";
  4210. char *pos = dst;
  4211. const char *end = dst + dst_len - 1;
  4212. for (; *src != '\0' && pos < end; src++, pos++) {
  4213. if (isalnum(*(const unsigned char *)src) ||
  4214. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4215. *pos = *src;
  4216. } else if (pos + 2 < end) {
  4217. pos[0] = '%';
  4218. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4219. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4220. pos += 2;
  4221. } else {
  4222. break;
  4223. }
  4224. }
  4225. *pos = '\0';
  4226. return (*src == '\0') ? (int)(pos - dst) : -1;
  4227. }
  4228. static void print_dir_entry(struct de *de)
  4229. {
  4230. char size[64], mod[64], href[PATH_MAX];
  4231. struct tm *tm;
  4232. if (de->file.is_directory) {
  4233. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  4234. } else {
  4235. /* We use (signed) cast below because MSVC 6 compiler cannot
  4236. * convert unsigned __int64 to double. Sigh. */
  4237. if (de->file.size < 1024) {
  4238. mg_snprintf(de->conn, size, sizeof(size), "%d", (int)de->file.size);
  4239. } else if (de->file.size < 0x100000) {
  4240. mg_snprintf(de->conn,
  4241. size,
  4242. sizeof(size),
  4243. "%.1fk",
  4244. (double)de->file.size / 1024.0);
  4245. } else if (de->file.size < 0x40000000) {
  4246. mg_snprintf(de->conn,
  4247. size,
  4248. sizeof(size),
  4249. "%.1fM",
  4250. (double)de->file.size / 1048576);
  4251. } else {
  4252. mg_snprintf(de->conn,
  4253. size,
  4254. sizeof(size),
  4255. "%.1fG",
  4256. (double)de->file.size / 1073741824);
  4257. }
  4258. }
  4259. tm = localtime(&de->file.modification_time);
  4260. if (tm != NULL) {
  4261. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4262. } else {
  4263. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4264. mod[sizeof(mod) - 1] = '\0';
  4265. }
  4266. mg_url_encode(de->file_name, href, sizeof(href));
  4267. de->conn->num_bytes_sent +=
  4268. mg_printf(de->conn,
  4269. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4270. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4271. de->conn->request_info.uri,
  4272. href,
  4273. de->file.is_directory ? "/" : "",
  4274. de->file_name,
  4275. de->file.is_directory ? "/" : "",
  4276. mod,
  4277. size);
  4278. }
  4279. /* This function is called from send_directory() and used for
  4280. * sorting directory entries by size, or name, or modification time.
  4281. * On windows, __cdecl specification is needed in case if project is built
  4282. * with __stdcall convention. qsort always requires __cdels callback. */
  4283. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  4284. {
  4285. if (p1 && p2) {
  4286. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4287. const char *query_string = a->conn->request_info.query_string;
  4288. int cmp_result = 0;
  4289. if (query_string == NULL) {
  4290. query_string = "na";
  4291. }
  4292. if (a->file.is_directory && !b->file.is_directory) {
  4293. return -1; /* Always put directories on top */
  4294. } else if (!a->file.is_directory && b->file.is_directory) {
  4295. return 1; /* Always put directories on top */
  4296. } else if (*query_string == 'n') {
  4297. cmp_result = strcmp(a->file_name, b->file_name);
  4298. } else if (*query_string == 's') {
  4299. cmp_result = a->file.size == b->file.size
  4300. ? 0
  4301. : a->file.size > b->file.size ? 1 : -1;
  4302. } else if (*query_string == 'd') {
  4303. cmp_result =
  4304. a->file.modification_time == b->file.modification_time
  4305. ? 0
  4306. : a->file.modification_time > b->file.modification_time
  4307. ? 1
  4308. : -1;
  4309. }
  4310. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4311. }
  4312. return 0;
  4313. }
  4314. static int must_hide_file(struct mg_connection *conn, const char *path)
  4315. {
  4316. if (conn && conn->ctx) {
  4317. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4318. const char *pattern = conn->ctx->config[HIDE_FILES];
  4319. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  4320. (pattern != NULL &&
  4321. match_prefix(pattern, strlen(pattern), path) > 0);
  4322. }
  4323. return 0;
  4324. }
  4325. static int scan_directory(struct mg_connection *conn,
  4326. const char *dir,
  4327. void *data,
  4328. void (*cb)(struct de *, void *))
  4329. {
  4330. char path[PATH_MAX];
  4331. struct dirent *dp;
  4332. DIR *dirp;
  4333. struct de de;
  4334. if ((dirp = opendir(dir)) == NULL) {
  4335. return 0;
  4336. } else {
  4337. de.conn = conn;
  4338. while ((dp = readdir(dirp)) != NULL) {
  4339. /* Do not show current dir and hidden files */
  4340. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  4341. must_hide_file(conn, dp->d_name)) {
  4342. continue;
  4343. }
  4344. mg_snprintf(
  4345. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4346. /* If we don't memset stat structure to zero, mtime will have
  4347. * garbage and strftime() will segfault later on in
  4348. * print_dir_entry(). memset is required only if mg_stat()
  4349. * fails. For more details, see
  4350. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4351. memset(&de.file, 0, sizeof(de.file));
  4352. if (!mg_stat(conn, path, &de.file)) {
  4353. mg_cry(conn,
  4354. "%s: mg_stat(%s) failed: %s",
  4355. __func__,
  4356. path,
  4357. strerror(ERRNO));
  4358. }
  4359. de.file_name = dp->d_name;
  4360. cb(&de, data);
  4361. }
  4362. (void)closedir(dirp);
  4363. }
  4364. return 1;
  4365. }
  4366. static int remove_directory(struct mg_connection *conn, const char *dir)
  4367. {
  4368. char path[PATH_MAX];
  4369. struct dirent *dp;
  4370. DIR *dirp;
  4371. struct de de;
  4372. if ((dirp = opendir(dir)) == NULL) {
  4373. return 0;
  4374. } else {
  4375. de.conn = conn;
  4376. while ((dp = readdir(dirp)) != NULL) {
  4377. /* Do not show current dir (but show hidden files as they will
  4378. * also be removed) */
  4379. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4380. continue;
  4381. }
  4382. mg_snprintf(
  4383. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4384. /* If we don't memset stat structure to zero, mtime will have
  4385. * garbage and strftime() will segfault later on in
  4386. * print_dir_entry(). memset is required only if mg_stat()
  4387. * fails. For more details, see
  4388. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4389. memset(&de.file, 0, sizeof(de.file));
  4390. if (!mg_stat(conn, path, &de.file)) {
  4391. mg_cry(conn,
  4392. "%s: mg_stat(%s) failed: %s",
  4393. __func__,
  4394. path,
  4395. strerror(ERRNO));
  4396. }
  4397. if (de.file.modification_time) {
  4398. if (de.file.is_directory) {
  4399. remove_directory(conn, path);
  4400. } else {
  4401. mg_remove(path);
  4402. }
  4403. }
  4404. }
  4405. (void)closedir(dirp);
  4406. IGNORE_UNUSED_RESULT(rmdir(dir));
  4407. }
  4408. return 1;
  4409. }
  4410. struct dir_scan_data {
  4411. struct de *entries;
  4412. unsigned int num_entries;
  4413. unsigned int arr_size;
  4414. };
  4415. /* Behaves like realloc(), but frees original pointer on failure */
  4416. static void *realloc2(void *ptr, size_t size)
  4417. {
  4418. void *new_ptr = mg_realloc(ptr, size);
  4419. if (new_ptr == NULL) {
  4420. mg_free(ptr);
  4421. }
  4422. return new_ptr;
  4423. }
  4424. static void dir_scan_callback(struct de *de, void *data)
  4425. {
  4426. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  4427. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  4428. dsd->arr_size *= 2;
  4429. dsd->entries = (struct de *)realloc2(
  4430. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  4431. }
  4432. if (dsd->entries == NULL) {
  4433. /* TODO(lsm, low): propagate an error to the caller */
  4434. dsd->num_entries = 0;
  4435. } else {
  4436. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  4437. dsd->entries[dsd->num_entries].file = de->file;
  4438. dsd->entries[dsd->num_entries].conn = de->conn;
  4439. dsd->num_entries++;
  4440. }
  4441. }
  4442. static void handle_directory_request(struct mg_connection *conn,
  4443. const char *dir)
  4444. {
  4445. unsigned int i;
  4446. int sort_direction;
  4447. struct dir_scan_data data = {NULL, 0, 128};
  4448. char date[64];
  4449. time_t curtime = time(NULL);
  4450. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  4451. send_http_error(conn,
  4452. 500,
  4453. "Error: Cannot open directory\nopendir(%s): %s",
  4454. dir,
  4455. strerror(ERRNO));
  4456. return;
  4457. }
  4458. gmt_time_string(date, sizeof(date), &curtime);
  4459. if (!conn)
  4460. return;
  4461. sort_direction = conn->request_info.query_string != NULL &&
  4462. conn->request_info.query_string[1] == 'd'
  4463. ? 'a'
  4464. : 'd';
  4465. conn->must_close = 1;
  4466. mg_printf(conn,
  4467. "HTTP/1.1 200 OK\r\n"
  4468. "Date: %s\r\n"
  4469. "Connection: close\r\n"
  4470. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  4471. date);
  4472. conn->num_bytes_sent +=
  4473. mg_printf(conn,
  4474. "<html><head><title>Index of %s</title>"
  4475. "<style>th {text-align: left;}</style></head>"
  4476. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  4477. "<tr><th><a href=\"?n%c\">Name</a></th>"
  4478. "<th><a href=\"?d%c\">Modified</a></th>"
  4479. "<th><a href=\"?s%c\">Size</a></th></tr>"
  4480. "<tr><td colspan=\"3\"><hr></td></tr>",
  4481. conn->request_info.uri,
  4482. conn->request_info.uri,
  4483. sort_direction,
  4484. sort_direction,
  4485. sort_direction);
  4486. /* Print first entry - link to a parent directory */
  4487. conn->num_bytes_sent +=
  4488. mg_printf(conn,
  4489. "<tr><td><a href=\"%s%s\">%s</a></td>"
  4490. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4491. conn->request_info.uri,
  4492. "..",
  4493. "Parent directory",
  4494. "-",
  4495. "-");
  4496. /* Sort and print directory entries */
  4497. if (data.entries != NULL) {
  4498. qsort(data.entries,
  4499. (size_t)data.num_entries,
  4500. sizeof(data.entries[0]),
  4501. compare_dir_entries);
  4502. for (i = 0; i < data.num_entries; i++) {
  4503. print_dir_entry(&data.entries[i]);
  4504. mg_free(data.entries[i].file_name);
  4505. }
  4506. mg_free(data.entries);
  4507. }
  4508. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  4509. conn->status_code = 200;
  4510. }
  4511. /* Send len bytes from the opened file to the client. */
  4512. static void send_file_data(struct mg_connection *conn,
  4513. struct file *filep,
  4514. int64_t offset,
  4515. int64_t len)
  4516. {
  4517. char buf[MG_BUF_LEN];
  4518. int to_read, num_read, num_written;
  4519. int64_t size;
  4520. if (!filep || !conn) {
  4521. return;
  4522. }
  4523. /* Sanity check the offset */
  4524. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  4525. offset = offset < 0 ? 0 : offset > size ? size : offset;
  4526. if (len > 0 && filep->membuf != NULL && size > 0) {
  4527. if (len > size - offset) {
  4528. len = size - offset;
  4529. }
  4530. mg_write(conn, filep->membuf + offset, (size_t)len);
  4531. } else if (len > 0 && filep->fp != NULL) {
  4532. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  4533. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  4534. }
  4535. while (len > 0) {
  4536. /* Calculate how much to read from the file in the buffer */
  4537. to_read = sizeof(buf);
  4538. if ((int64_t)to_read > len) {
  4539. to_read = (int)len;
  4540. }
  4541. /* Read from file, exit the loop on error */
  4542. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp)) <=
  4543. 0) {
  4544. break;
  4545. }
  4546. /* Send read bytes to the client, exit the loop on error */
  4547. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  4548. num_read) {
  4549. break;
  4550. }
  4551. /* Both read and were successful, adjust counters */
  4552. conn->num_bytes_sent += num_written;
  4553. len -= num_written;
  4554. }
  4555. }
  4556. }
  4557. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  4558. {
  4559. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  4560. }
  4561. static void construct_etag(char *buf, size_t buf_len, const struct file *filep)
  4562. {
  4563. if (filep)
  4564. snprintf(buf,
  4565. buf_len,
  4566. "\"%lx.%" INT64_FMT "\"",
  4567. (unsigned long)filep->modification_time,
  4568. filep->size);
  4569. }
  4570. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  4571. {
  4572. if (filep != NULL && filep->fp != NULL) {
  4573. #ifdef _WIN32
  4574. (void)conn; /* Unused. */
  4575. #else
  4576. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  4577. mg_cry(conn,
  4578. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4579. __func__,
  4580. strerror(ERRNO));
  4581. }
  4582. #endif
  4583. }
  4584. }
  4585. static void handle_static_file_request(struct mg_connection *conn,
  4586. const char *path,
  4587. struct file *filep)
  4588. {
  4589. char date[64], lm[64], etag[64], range[64];
  4590. const char *msg = "OK", *hdr;
  4591. time_t curtime = time(NULL);
  4592. int64_t cl, r1, r2;
  4593. struct vec mime_vec;
  4594. int n;
  4595. char gz_path[PATH_MAX];
  4596. const char *encoding = "";
  4597. const char *cors1, *cors2, *cors3;
  4598. if (!conn || !conn->ctx || !filep)
  4599. return;
  4600. get_mime_type(conn->ctx, path, &mime_vec);
  4601. if (filep->size > INT64_MAX) {
  4602. send_http_error(conn,
  4603. 500,
  4604. "Error: File size is too large to send\n%" INT64_FMT,
  4605. filep->size);
  4606. }
  4607. cl = (int64_t)filep->size;
  4608. conn->status_code = 200;
  4609. range[0] = '\0';
  4610. /* if this file is in fact a pre-gzipped file, rewrite its filename
  4611. * it's important to rewrite the filename after resolving
  4612. * the mime type from it, to preserve the actual file's type */
  4613. if (filep->gzipped) {
  4614. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  4615. path = gz_path;
  4616. encoding = "Content-Encoding: gzip\r\n";
  4617. }
  4618. if (!mg_fopen(conn, path, "rb", filep)) {
  4619. send_http_error(conn,
  4620. 500,
  4621. "Error: Cannot open file\nfopen(%s): %s",
  4622. path,
  4623. strerror(ERRNO));
  4624. return;
  4625. }
  4626. fclose_on_exec(filep, conn);
  4627. /* If Range: header specified, act accordingly */
  4628. r1 = r2 = 0;
  4629. hdr = mg_get_header(conn, "Range");
  4630. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  4631. r2 >= 0) {
  4632. /* actually, range requests don't play well with a pre-gzipped
  4633. * file (since the range is specified in the uncompressed space) */
  4634. if (filep->gzipped) {
  4635. send_http_error(
  4636. conn,
  4637. 501,
  4638. "%s",
  4639. "Error: Range requests in gzipped files are not supported");
  4640. mg_fclose(filep);
  4641. return;
  4642. }
  4643. conn->status_code = 206;
  4644. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  4645. mg_snprintf(conn,
  4646. range,
  4647. sizeof(range),
  4648. "Content-Range: bytes "
  4649. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  4650. r1,
  4651. r1 + cl - 1,
  4652. filep->size);
  4653. msg = "Partial Content";
  4654. }
  4655. hdr = mg_get_header(conn, "Origin");
  4656. if (hdr) {
  4657. /* Cross-origin resource sharing (CORS), see
  4658. * http://www.html5rocks.com/en/tutorials/cors/,
  4659. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  4660. * preflight is not supported for files. */
  4661. cors1 = "Access-Control-Allow-Origin: ";
  4662. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4663. cors3 = "\r\n";
  4664. } else {
  4665. cors1 = cors2 = cors3 = "";
  4666. }
  4667. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  4668. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  4669. gmt_time_string(date, sizeof(date), &curtime);
  4670. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  4671. construct_etag(etag, sizeof(etag), filep);
  4672. (void)mg_printf(conn,
  4673. "HTTP/1.1 %d %s\r\n"
  4674. "%s%s%s"
  4675. "Date: %s\r\n"
  4676. "Last-Modified: %s\r\n"
  4677. "Etag: %s\r\n"
  4678. "Content-Type: %.*s\r\n"
  4679. "Content-Length: %" INT64_FMT "\r\n"
  4680. "Connection: %s\r\n"
  4681. "Accept-Ranges: bytes\r\n"
  4682. "%s%s\r\n",
  4683. conn->status_code,
  4684. msg,
  4685. cors1,
  4686. cors2,
  4687. cors3,
  4688. date,
  4689. lm,
  4690. etag,
  4691. (int)mime_vec.len,
  4692. mime_vec.ptr,
  4693. cl,
  4694. suggest_connection_header(conn),
  4695. range,
  4696. encoding);
  4697. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  4698. send_file_data(conn, filep, r1, cl);
  4699. }
  4700. mg_fclose(filep);
  4701. }
  4702. void mg_send_file(struct mg_connection *conn, const char *path)
  4703. {
  4704. struct file file = STRUCT_FILE_INITIALIZER;
  4705. if (mg_stat(conn, path, &file)) {
  4706. if (file.is_directory) {
  4707. if (!conn)
  4708. return;
  4709. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  4710. "yes")) {
  4711. handle_directory_request(conn, path);
  4712. } else {
  4713. send_http_error(
  4714. conn, 403, "%s", "Error: Directory listing denied");
  4715. }
  4716. } else {
  4717. handle_static_file_request(conn, path, &file);
  4718. }
  4719. } else {
  4720. send_http_error(conn, 404, "%s", "Error: File not found");
  4721. }
  4722. }
  4723. /* Parse HTTP headers from the given buffer, advance buffer to the point
  4724. * where parsing stopped. */
  4725. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  4726. {
  4727. int i;
  4728. if (!ri)
  4729. return;
  4730. ri->num_headers = 0;
  4731. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  4732. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  4733. ri->http_headers[i].value = skip(buf, "\r\n");
  4734. if (ri->http_headers[i].name[0] == '\0') {
  4735. break;
  4736. }
  4737. ri->num_headers = i + 1;
  4738. }
  4739. }
  4740. static int is_valid_http_method(const char *method)
  4741. {
  4742. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  4743. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  4744. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  4745. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  4746. !strcmp(method, "MKCOL");
  4747. /* TRACE method is not supported for security reasons */
  4748. }
  4749. /* Parse HTTP request, fill in mg_request_info structure.
  4750. * This function modifies the buffer by NUL-terminating
  4751. * HTTP request components, header names and header values. */
  4752. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  4753. {
  4754. int is_request, request_length = get_request_len(buf, len);
  4755. if (request_length > 0) {
  4756. if (!ri)
  4757. return 0;
  4758. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  4759. * remote_port */
  4760. ri->remote_user = ri->request_method = ri->uri = ri->http_version =
  4761. NULL;
  4762. ri->num_headers = 0;
  4763. buf[request_length - 1] = '\0';
  4764. /* RFC says that all initial whitespaces should be ingored */
  4765. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  4766. buf++;
  4767. }
  4768. ri->request_method = skip(&buf, " ");
  4769. ri->uri = skip(&buf, " ");
  4770. ri->http_version = skip(&buf, "\r\n");
  4771. /* HTTP message could be either HTTP request or HTTP response, e.g.
  4772. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  4773. is_request = is_valid_http_method(ri->request_method);
  4774. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  4775. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  4776. request_length = -1;
  4777. } else {
  4778. if (is_request) {
  4779. ri->http_version += 5;
  4780. }
  4781. parse_http_headers(&buf, ri);
  4782. }
  4783. }
  4784. return request_length;
  4785. }
  4786. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  4787. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  4788. * buffer (which marks the end of HTTP request). Buffer buf may already
  4789. * have some data. The length of the data is stored in nread.
  4790. * Upon every read operation, increase nread by the number of bytes read. */
  4791. static int read_request(
  4792. FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
  4793. {
  4794. int request_len, n = 0;
  4795. struct timespec last_action_time = {0, 0};
  4796. double request_timeout;
  4797. if (!conn)
  4798. return 0;
  4799. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4800. /* value of request_timeout is in seconds, config in milliseconds */
  4801. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4802. } else {
  4803. request_timeout = -1.0;
  4804. }
  4805. request_len = get_request_len(buf, *nread);
  4806. while (
  4807. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  4808. (request_len == 0) &&
  4809. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  4810. request_timeout) ||
  4811. (request_timeout < 0)) &&
  4812. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout)) >
  4813. 0)) {
  4814. *nread += n;
  4815. /* assert(*nread <= bufsiz); */
  4816. if (*nread > bufsiz)
  4817. return -2;
  4818. request_len = get_request_len(buf, *nread);
  4819. if (request_timeout > 0.0) {
  4820. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  4821. }
  4822. }
  4823. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  4824. }
  4825. /* For given directory path, substitute it to valid index file.
  4826. * Return 1 if index file has been found, 0 if not found.
  4827. * If the file is found, it's stats is returned in stp. */
  4828. static int substitute_index_file(struct mg_connection *conn,
  4829. char *path,
  4830. size_t path_len,
  4831. struct file *filep)
  4832. {
  4833. if (conn && conn->ctx) {
  4834. const char *list = conn->ctx->config[INDEX_FILES];
  4835. struct file file = STRUCT_FILE_INITIALIZER;
  4836. struct vec filename_vec;
  4837. size_t n = strlen(path);
  4838. int found = 0;
  4839. /* The 'path' given to us points to the directory. Remove all trailing
  4840. * directory separator characters from the end of the path, and
  4841. * then append single directory separator character. */
  4842. while (n > 0 && path[n - 1] == '/') {
  4843. n--;
  4844. }
  4845. path[n] = '/';
  4846. /* Traverse index files list. For each entry, append it to the given
  4847. * path and see if the file exists. If it exists, break the loop */
  4848. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  4849. /* Ignore too long entries that may overflow path buffer */
  4850. if (filename_vec.len > path_len - (n + 2))
  4851. continue;
  4852. /* Prepare full path to the index file */
  4853. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  4854. /* Does it exist? */
  4855. if (mg_stat(conn, path, &file)) {
  4856. /* Yes it does, break the loop */
  4857. *filep = file;
  4858. found = 1;
  4859. break;
  4860. }
  4861. }
  4862. /* If no index file exists, restore directory path */
  4863. if (!found) {
  4864. path[n] = '\0';
  4865. }
  4866. return found;
  4867. }
  4868. return 0;
  4869. }
  4870. /* Return True if we should reply 304 Not Modified. */
  4871. static int is_not_modified(const struct mg_connection *conn,
  4872. const struct file *filep)
  4873. {
  4874. char etag[64];
  4875. const char *ims = mg_get_header(conn, "If-Modified-Since");
  4876. const char *inm = mg_get_header(conn, "If-None-Match");
  4877. construct_etag(etag, sizeof(etag), filep);
  4878. if (!filep)
  4879. return 0;
  4880. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  4881. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  4882. }
  4883. static int
  4884. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  4885. {
  4886. const char *expect, *body;
  4887. char buf[MG_BUF_LEN];
  4888. int to_read, nread, success = 0;
  4889. int64_t buffered_len;
  4890. double timeout = -1.0;
  4891. if (!conn) {
  4892. return 0;
  4893. }
  4894. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4895. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4896. }
  4897. expect = mg_get_header(conn, "Expect");
  4898. /* assert(fp != NULL); */
  4899. if (!fp) {
  4900. send_http_error(conn, 500, "%s", "Error: NULL File");
  4901. return 0;
  4902. }
  4903. if (conn->content_len == -1 && !conn->is_chunked) {
  4904. /* Content length is not specified by the client. */
  4905. send_http_error(
  4906. conn, 411, "%s", "Error: Client did not specify content length");
  4907. } else if ((expect != NULL) &&
  4908. (mg_strcasecmp(expect, "100-continue") != 0)) {
  4909. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  4910. send_http_error(
  4911. conn, 417, "Error: Can not fulfill expectation %s", expect);
  4912. } else {
  4913. if (expect != NULL) {
  4914. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  4915. conn->status_code = 100;
  4916. } else {
  4917. conn->status_code = 200;
  4918. }
  4919. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  4920. conn->consumed_content;
  4921. /* assert(buffered_len >= 0); */
  4922. /* assert(conn->consumed_content == 0); */
  4923. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  4924. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  4925. return 0;
  4926. }
  4927. if (buffered_len > 0) {
  4928. if ((int64_t)buffered_len > conn->content_len) {
  4929. buffered_len = (int)conn->content_len;
  4930. }
  4931. body = conn->buf + conn->request_len + conn->consumed_content;
  4932. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  4933. conn->consumed_content += buffered_len;
  4934. }
  4935. nread = 0;
  4936. while (conn->consumed_content < conn->content_len) {
  4937. to_read = sizeof(buf);
  4938. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  4939. to_read = (int)(conn->content_len - conn->consumed_content);
  4940. }
  4941. nread = pull(NULL, conn, buf, to_read, timeout);
  4942. if (nread <= 0 ||
  4943. push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  4944. break;
  4945. }
  4946. conn->consumed_content += nread;
  4947. }
  4948. if (conn->consumed_content == conn->content_len) {
  4949. success = nread >= 0;
  4950. }
  4951. /* Each error code path in this function must send an error */
  4952. if (!success) {
  4953. /* NOTE: Maybe some data has already been sent. */
  4954. /* TODO (low): If some data has been sent, a correct error
  4955. * reply can no longer be sent, so just close the connection */
  4956. send_http_error(conn, 500, "%s", "");
  4957. }
  4958. }
  4959. return success;
  4960. }
  4961. #if !defined(NO_CGI)
  4962. /* This structure helps to create an environment for the spawned CGI program.
  4963. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  4964. * last element must be NULL.
  4965. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  4966. * strings must reside in a contiguous buffer. The end of the buffer is
  4967. * marked by two '\0' characters.
  4968. * We satisfy both worlds: we create an envp array (which is vars), all
  4969. * entries are actually pointers inside buf. */
  4970. struct cgi_env_block {
  4971. struct mg_connection *conn;
  4972. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  4973. unsigned int len; /* Space taken */
  4974. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  4975. unsigned int nvars; /* Number of variables */
  4976. };
  4977. static char *addenv(struct cgi_env_block *block,
  4978. PRINTF_FORMAT_STRING(const char *fmt),
  4979. ...) PRINTF_ARGS(2, 3);
  4980. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  4981. * pointer into the vars array. */
  4982. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  4983. {
  4984. int n, space;
  4985. char *added;
  4986. va_list ap;
  4987. if (!block)
  4988. return NULL;
  4989. /* Calculate how much space is left in the buffer */
  4990. space = (int)(sizeof(block->buf) - block->len) - 2;
  4991. /* assert(space >= 0); */
  4992. if (space < 0)
  4993. return NULL;
  4994. /* Make a pointer to the free space int the buffer */
  4995. added = block->buf + block->len;
  4996. /* Copy VARIABLE=VALUE\0 string into the free space */
  4997. va_start(ap, fmt);
  4998. n = mg_vsnprintf(block->conn, added, (size_t)space, fmt, ap);
  4999. va_end(ap);
  5000. /* Make sure we do not overflow buffer and the envp array */
  5001. if (n > 0 && n + 1 < space && block->nvars + 2 < ARRAY_SIZE(block->vars)) {
  5002. /* Append a pointer to the added string into the envp array */
  5003. block->vars[block->nvars++] = added;
  5004. /* Bump up used length counter. Include \0 terminator */
  5005. block->len += (unsigned int)(n) + 1;
  5006. } else {
  5007. mg_cry(block->conn,
  5008. "%s: CGI env buffer truncated for [%s]",
  5009. __func__,
  5010. fmt);
  5011. }
  5012. return added;
  5013. }
  5014. static void prepare_cgi_environment(struct mg_connection *conn,
  5015. const char *prog,
  5016. struct cgi_env_block *blk)
  5017. {
  5018. const char *s;
  5019. struct vec var_vec;
  5020. char *p, src_addr[IP_ADDR_STR_LEN];
  5021. int i;
  5022. if (conn == NULL || blk == NULL)
  5023. return;
  5024. blk->len = blk->nvars = 0;
  5025. blk->conn = conn;
  5026. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5027. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5028. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5029. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5030. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5031. /* Prepare the environment block */
  5032. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5033. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5034. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5035. /* TODO(lsm, high): fix this for IPv6 case */
  5036. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5037. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5038. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  5039. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5040. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  5041. /* SCRIPT_NAME */
  5042. addenv(blk,
  5043. "SCRIPT_NAME=%.*s",
  5044. (int)strlen(conn->request_info.uri) -
  5045. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5046. conn->request_info.uri);
  5047. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  5048. if (conn->path_info == NULL) {
  5049. addenv(blk, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5050. } else {
  5051. addenv(blk,
  5052. "PATH_TRANSLATED=%s%s",
  5053. conn->ctx->config[DOCUMENT_ROOT],
  5054. conn->path_info);
  5055. }
  5056. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5057. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  5058. addenv(blk, "CONTENT_TYPE=%s", s);
  5059. if (conn->request_info.query_string != NULL)
  5060. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  5061. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  5062. addenv(blk, "CONTENT_LENGTH=%s", s);
  5063. if ((s = getenv("PATH")) != NULL)
  5064. addenv(blk, "PATH=%s", s);
  5065. if (conn->path_info != NULL) {
  5066. addenv(blk, "PATH_INFO=%s", conn->path_info);
  5067. }
  5068. if (conn->status_code > 0) {
  5069. /* CGI error handler should show the status code */
  5070. addenv(blk, "STATUS=%d", conn->status_code);
  5071. }
  5072. #if defined(_WIN32)
  5073. if ((s = getenv("COMSPEC")) != NULL) {
  5074. addenv(blk, "COMSPEC=%s", s);
  5075. }
  5076. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5077. addenv(blk, "SYSTEMROOT=%s", s);
  5078. }
  5079. if ((s = getenv("SystemDrive")) != NULL) {
  5080. addenv(blk, "SystemDrive=%s", s);
  5081. }
  5082. if ((s = getenv("ProgramFiles")) != NULL) {
  5083. addenv(blk, "ProgramFiles=%s", s);
  5084. }
  5085. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5086. addenv(blk, "ProgramFiles(x86)=%s", s);
  5087. }
  5088. #else
  5089. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  5090. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  5091. #endif /* _WIN32 */
  5092. if ((s = getenv("PERLLIB")) != NULL)
  5093. addenv(blk, "PERLLIB=%s", s);
  5094. if (conn->request_info.remote_user != NULL) {
  5095. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  5096. addenv(blk, "%s", "AUTH_TYPE=Digest");
  5097. }
  5098. /* Add all headers as HTTP_* variables */
  5099. for (i = 0; i < conn->request_info.num_headers; i++) {
  5100. p = addenv(blk,
  5101. "HTTP_%s=%s",
  5102. conn->request_info.http_headers[i].name,
  5103. conn->request_info.http_headers[i].value);
  5104. /* Convert variable name into uppercase, and change - to _ */
  5105. for (; *p != '=' && *p != '\0'; p++) {
  5106. if (*p == '-')
  5107. *p = '_';
  5108. *p = (char)toupper(*(unsigned char *)p);
  5109. }
  5110. }
  5111. /* Add user-specified variables */
  5112. s = conn->ctx->config[CGI_ENVIRONMENT];
  5113. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5114. addenv(blk, "%.*s", (int)var_vec.len, var_vec.ptr);
  5115. }
  5116. blk->vars[blk->nvars++] = NULL;
  5117. blk->buf[blk->len++] = '\0';
  5118. /* assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); */
  5119. /* assert(blk->len > 0); */
  5120. /* assert(blk->len < (int) sizeof(blk->buf)); */
  5121. if ((blk->nvars >= (int)ARRAY_SIZE(blk->vars)) || (blk->len <= 0) ||
  5122. (blk->len >= (int)sizeof(blk->buf)))
  5123. return;
  5124. }
  5125. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  5126. {
  5127. char *buf;
  5128. size_t buflen;
  5129. int headers_len, data_len, i, fdin[2] = {0, 0}, fdout[2] = {0, 0};
  5130. const char *status, *status_text, *connection_state;
  5131. char *pbuf, dir[PATH_MAX], *p;
  5132. struct mg_request_info ri;
  5133. struct cgi_env_block blk;
  5134. FILE *in = NULL, *out = NULL;
  5135. struct file fout = STRUCT_FILE_INITIALIZER;
  5136. pid_t pid = (pid_t)-1;
  5137. if (conn == NULL)
  5138. return;
  5139. buf = NULL;
  5140. buflen = 16384;
  5141. prepare_cgi_environment(conn, prog, &blk);
  5142. /* CGI must be executed in its own directory. 'dir' must point to the
  5143. * directory containing executable program, 'p' must point to the
  5144. * executable program name relative to 'dir'. */
  5145. (void)mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  5146. if ((p = strrchr(dir, '/')) != NULL) {
  5147. *p++ = '\0';
  5148. } else {
  5149. dir[0] = '.', dir[1] = '\0';
  5150. p = (char *)prog;
  5151. }
  5152. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  5153. send_http_error(
  5154. conn, 500, "Error: Cannot create CGI pipe: %s", strerror(ERRNO));
  5155. goto done;
  5156. }
  5157. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  5158. if (pid == (pid_t)-1) {
  5159. send_http_error(conn,
  5160. 500,
  5161. "Error: Cannot spawn CGI process [%s]: %s",
  5162. prog,
  5163. strerror(ERRNO));
  5164. goto done;
  5165. }
  5166. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5167. set_close_on_exec((SOCKET)fdin[0], conn);
  5168. set_close_on_exec((SOCKET)fdin[1], conn);
  5169. set_close_on_exec((SOCKET)fdout[0], conn);
  5170. set_close_on_exec((SOCKET)fdout[1], conn);
  5171. /* Parent closes only one side of the pipes.
  5172. * If we don't mark them as closed, close() attempt before
  5173. * return from this function throws an exception on Windows.
  5174. * Windows does not like when closed descriptor is closed again. */
  5175. (void)close(fdin[0]);
  5176. (void)close(fdout[1]);
  5177. fdin[0] = fdout[1] = -1;
  5178. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5179. send_http_error(conn,
  5180. 500,
  5181. "Error: CGI can not open fdin\nfopen: %s",
  5182. strerror(ERRNO));
  5183. goto done;
  5184. }
  5185. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5186. send_http_error(conn,
  5187. 500,
  5188. "Error: CGI can not open fdout\nfopen: %s",
  5189. strerror(ERRNO));
  5190. goto done;
  5191. }
  5192. setbuf(in, NULL);
  5193. setbuf(out, NULL);
  5194. fout.fp = out;
  5195. /* Send POST or PUT data to the CGI process if needed */
  5196. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5197. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5198. /* This is a POST/PUT request */
  5199. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  5200. /* Error sending the body data */
  5201. goto done;
  5202. }
  5203. }
  5204. /* Close so child gets an EOF. */
  5205. fclose(in);
  5206. in = NULL;
  5207. fdin[1] = -1;
  5208. /* Now read CGI reply into a buffer. We need to set correct
  5209. * status code, thus we need to see all HTTP headers first.
  5210. * Do not send anything back to client, until we buffer in all
  5211. * HTTP headers. */
  5212. data_len = 0;
  5213. buf = (char *)mg_malloc(buflen);
  5214. if (buf == NULL) {
  5215. send_http_error(conn,
  5216. 500,
  5217. "Error: Not enough memory for CGI buffer (%u bytes)",
  5218. (unsigned int)buflen);
  5219. goto done;
  5220. }
  5221. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  5222. if (headers_len <= 0) {
  5223. send_http_error(conn,
  5224. 500,
  5225. "Error: CGI program sent malformed or too big "
  5226. "(>%u bytes) HTTP headers: [%.*s]",
  5227. (unsigned)buflen,
  5228. data_len,
  5229. buf);
  5230. goto done;
  5231. }
  5232. pbuf = buf;
  5233. buf[headers_len - 1] = '\0';
  5234. parse_http_headers(&pbuf, &ri);
  5235. /* Make up and send the status line */
  5236. status_text = "OK";
  5237. if ((status = get_header(&ri, "Status")) != NULL) {
  5238. conn->status_code = atoi(status);
  5239. status_text = status;
  5240. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  5241. status_text++;
  5242. }
  5243. } else if (get_header(&ri, "Location") != NULL) {
  5244. conn->status_code = 302;
  5245. } else {
  5246. conn->status_code = 200;
  5247. }
  5248. connection_state = get_header(&ri, "Connection");
  5249. if (connection_state == NULL ||
  5250. mg_strcasecmp(connection_state, "keep-alive")) {
  5251. conn->must_close = 1;
  5252. }
  5253. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  5254. /* Send headers */
  5255. for (i = 0; i < ri.num_headers; i++) {
  5256. mg_printf(conn,
  5257. "%s: %s\r\n",
  5258. ri.http_headers[i].name,
  5259. ri.http_headers[i].value);
  5260. }
  5261. mg_write(conn, "\r\n", 2);
  5262. /* Send chunk of data that may have been read after the headers */
  5263. conn->num_bytes_sent +=
  5264. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  5265. /* Read the rest of CGI output and send to the client */
  5266. send_file_data(conn, &fout, 0, INT64_MAX);
  5267. done:
  5268. if (pid != (pid_t)-1) {
  5269. kill(pid, SIGKILL);
  5270. #if !defined(_WIN32)
  5271. {
  5272. int st;
  5273. while (waitpid(pid, &st, 0) != -1)
  5274. ; /* clean zombies */
  5275. }
  5276. #endif
  5277. }
  5278. if (fdin[0] != -1) {
  5279. close(fdin[0]);
  5280. }
  5281. if (fdout[1] != -1) {
  5282. close(fdout[1]);
  5283. }
  5284. if (in != NULL) {
  5285. fclose(in);
  5286. } else if (fdin[1] != -1) {
  5287. close(fdin[1]);
  5288. }
  5289. if (out != NULL) {
  5290. fclose(out);
  5291. } else if (fdout[0] != -1) {
  5292. close(fdout[0]);
  5293. }
  5294. if (buf != NULL) {
  5295. mg_free(buf);
  5296. }
  5297. }
  5298. #endif /* !NO_CGI */
  5299. /* For a given PUT path, create all intermediate subdirectories.
  5300. * Return 0 if the path itself is a directory.
  5301. * Return 1 if the path leads to a file.
  5302. * Return -1 for if the path is too long.
  5303. * Return -2 if path can not be created.
  5304. */
  5305. static int put_dir(struct mg_connection *conn, const char *path)
  5306. {
  5307. char buf[PATH_MAX];
  5308. const char *s, *p;
  5309. struct file file = STRUCT_FILE_INITIALIZER;
  5310. size_t len;
  5311. int res = 1;
  5312. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5313. len = (size_t)(p - path);
  5314. if (len >= sizeof(buf)) {
  5315. /* path too long */
  5316. res = -1;
  5317. break;
  5318. }
  5319. memcpy(buf, path, len);
  5320. buf[len] = '\0';
  5321. /* Try to create intermediate directory */
  5322. DEBUG_TRACE("mkdir(%s)", buf);
  5323. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5324. /* path does not exixt and can not be created */
  5325. res = -2;
  5326. break;
  5327. }
  5328. /* Is path itself a directory? */
  5329. if (p[1] == '\0') {
  5330. res = 0;
  5331. }
  5332. }
  5333. return res;
  5334. }
  5335. static void mkcol(struct mg_connection *conn, const char *path)
  5336. {
  5337. int rc, body_len;
  5338. struct de de;
  5339. char date[64];
  5340. time_t curtime = time(NULL);
  5341. if (conn == NULL)
  5342. return;
  5343. /* TODO (mid): Check the send_http_error situations in this function */
  5344. memset(&de.file, 0, sizeof(de.file));
  5345. if (!mg_stat(conn, path, &de.file)) {
  5346. mg_cry(conn,
  5347. "%s: mg_stat(%s) failed: %s",
  5348. __func__,
  5349. path,
  5350. strerror(ERRNO));
  5351. }
  5352. if (de.file.modification_time) {
  5353. send_http_error(
  5354. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5355. return;
  5356. }
  5357. body_len = conn->data_len - conn->request_len;
  5358. if (body_len > 0) {
  5359. send_http_error(
  5360. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5361. return;
  5362. }
  5363. rc = mg_mkdir(path, 0755);
  5364. if (rc == 0) {
  5365. conn->status_code = 201;
  5366. gmt_time_string(date, sizeof(date), &curtime);
  5367. mg_printf(conn,
  5368. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  5369. "0\r\nConnection: %s\r\n\r\n",
  5370. conn->status_code,
  5371. date,
  5372. suggest_connection_header(conn));
  5373. } else if (rc == -1) {
  5374. if (errno == EEXIST)
  5375. send_http_error(
  5376. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  5377. else if (errno == EACCES)
  5378. send_http_error(
  5379. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5380. else if (errno == ENOENT)
  5381. send_http_error(
  5382. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5383. else
  5384. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  5385. }
  5386. }
  5387. static void put_file(struct mg_connection *conn, const char *path)
  5388. {
  5389. struct file file = STRUCT_FILE_INITIALIZER;
  5390. const char *range;
  5391. int64_t r1, r2;
  5392. int rc;
  5393. char date[64];
  5394. time_t curtime = time(NULL);
  5395. if (conn == NULL)
  5396. return;
  5397. if (mg_stat(conn, path, &file)) {
  5398. /* File already exists */
  5399. conn->status_code = 200;
  5400. if (file.is_directory) {
  5401. /* This is an already existing directory,
  5402. * so there is nothing to do for the server. */
  5403. rc = 0;
  5404. } else {
  5405. /* File exists and is not a directory. */
  5406. /* Can it be replaced? */
  5407. if (file.modification_time == 0) {
  5408. /* This is an "in-memory" file, that can not be replaced */
  5409. send_http_error(
  5410. conn,
  5411. 405,
  5412. "Error: Put not possible\nReplacing %s is not supported",
  5413. path);
  5414. return;
  5415. }
  5416. /* Check if the server may write this file */
  5417. if (access(path, W_OK) == 0) {
  5418. /* Access granted */
  5419. conn->status_code = 200;
  5420. rc = 1;
  5421. } else {
  5422. send_http_error(
  5423. conn,
  5424. 403,
  5425. "Error: Put not possible\nReplacing %s is not allowed",
  5426. path);
  5427. return;
  5428. }
  5429. }
  5430. } else {
  5431. /* File should be created */
  5432. conn->status_code = 201;
  5433. rc = put_dir(conn, path);
  5434. }
  5435. if (rc == 0) {
  5436. /* put_dir returns 0 if path is a directory */
  5437. gmt_time_string(date, sizeof(date), &curtime);
  5438. mg_printf(conn,
  5439. "HTTP/1.1 %d %s\r\n"
  5440. "Date: %s\r\n"
  5441. "Content-Length: 0\r\n"
  5442. "Connection: %s\r\n\r\n",
  5443. conn->status_code,
  5444. mg_get_response_code_text(conn->status_code, NULL),
  5445. date,
  5446. suggest_connection_header(conn));
  5447. /* Request to create a directory has been fulfilled successfully.
  5448. * No need to put a file. */
  5449. return;
  5450. }
  5451. if (rc == -1) {
  5452. /* put_dir returns -1 if the path is too long */
  5453. send_http_error(conn,
  5454. 414,
  5455. "Error: Path too long\nput_dir(%s): %s",
  5456. path,
  5457. strerror(ERRNO));
  5458. return;
  5459. }
  5460. if (rc == -2) {
  5461. /* put_dir returns -2 if the directory can not be created */
  5462. send_http_error(conn,
  5463. 500,
  5464. "Error: Can not create directory\nput_dir(%s): %s",
  5465. path,
  5466. strerror(ERRNO));
  5467. return;
  5468. }
  5469. /* A file should be created or overwritten. */
  5470. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  5471. mg_fclose(&file);
  5472. send_http_error(conn,
  5473. 500,
  5474. "Error: Can not create file\nfopen(%s): %s",
  5475. path,
  5476. strerror(ERRNO));
  5477. return;
  5478. }
  5479. fclose_on_exec(&file, conn);
  5480. range = mg_get_header(conn, "Content-Range");
  5481. r1 = r2 = 0;
  5482. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  5483. conn->status_code = 206; /* Partial content */
  5484. fseeko(file.fp, r1, SEEK_SET);
  5485. }
  5486. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  5487. /* forward_body_data failed.
  5488. * The error code has already been sent to the client,
  5489. * and conn->status_code is already set. */
  5490. return;
  5491. }
  5492. gmt_time_string(date, sizeof(date), &curtime);
  5493. mg_printf(conn,
  5494. "HTTP/1.1 %d %s\r\n"
  5495. "Date: %s\r\n"
  5496. "Content-Length: 0\r\n"
  5497. "Connection: %s\r\n\r\n",
  5498. conn->status_code,
  5499. mg_get_response_code_text(conn->status_code, NULL),
  5500. date,
  5501. suggest_connection_header(conn));
  5502. mg_fclose(&file);
  5503. }
  5504. static void delete_file(struct mg_connection *conn, const char *path)
  5505. {
  5506. struct de de;
  5507. memset(&de.file, 0, sizeof(de.file));
  5508. if (!mg_stat(conn, path, &de.file)) {
  5509. /* mg_stat returns 0 if the file does not exist */
  5510. send_http_error(
  5511. conn, 404, "Error: Cannot delete file\nFile %s not found", path);
  5512. return;
  5513. }
  5514. if (de.file.modification_time == 0) {
  5515. /* mg_stat returns != 0 and modification_time == 0
  5516. * if the file is cached in memory */
  5517. send_http_error(
  5518. conn,
  5519. 405,
  5520. "Error: Delete not possible\nDeleting %s is not supported",
  5521. path);
  5522. return;
  5523. }
  5524. if (de.file.is_directory) {
  5525. remove_directory(conn, path);
  5526. /* TODO (mid): remove_dir does not return success of the operation */
  5527. /* Assume delete is successful: Return 204 without content. */
  5528. send_http_error(conn, 204, "%s", "");
  5529. return;
  5530. }
  5531. /* This is an existing file (not a directory).
  5532. * Check if write permission is granted. */
  5533. if (access(path, W_OK) != 0) {
  5534. /* File is read only */
  5535. send_http_error(
  5536. conn,
  5537. 403,
  5538. "Error: Delete not possible\nDeleting %s is not allowed",
  5539. path);
  5540. return;
  5541. }
  5542. /* Try to delete it. */
  5543. if (mg_remove(path) == 0) {
  5544. /* Delete was successful: Return 204 without content. */
  5545. send_http_error(conn, 204, "%s", "");
  5546. } else {
  5547. /* Delete not successful (file locked). */
  5548. send_http_error(conn,
  5549. 423,
  5550. "Error: Cannot delete file\nremove(%s): %s",
  5551. path,
  5552. strerror(ERRNO));
  5553. }
  5554. }
  5555. static void
  5556. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  5557. static void do_ssi_include(struct mg_connection *conn,
  5558. const char *ssi,
  5559. char *tag,
  5560. int include_level)
  5561. {
  5562. char file_name[MG_BUF_LEN], path[512], *p;
  5563. struct file file = STRUCT_FILE_INITIALIZER;
  5564. size_t len;
  5565. if (conn == NULL)
  5566. return;
  5567. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  5568. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  5569. * always < MG_BUF_LEN. */
  5570. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  5571. /* File name is relative to the webserver root */
  5572. file_name[511] = 0;
  5573. (void)mg_snprintf(conn,
  5574. path,
  5575. sizeof(path),
  5576. "%s%c%s",
  5577. conn->ctx->config[DOCUMENT_ROOT],
  5578. '/',
  5579. file_name);
  5580. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  5581. /* File name is relative to the webserver working directory
  5582. * or it is absolute system path */
  5583. file_name[511] = 0;
  5584. (void)mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  5585. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  5586. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  5587. /* File name is relative to the currect document */
  5588. file_name[511] = 0;
  5589. (void)mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  5590. if ((p = strrchr(path, '/')) != NULL) {
  5591. p[1] = '\0';
  5592. }
  5593. len = strlen(path);
  5594. (void)mg_snprintf(
  5595. conn, path + len, sizeof(path) - len, "%s", file_name);
  5596. } else {
  5597. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  5598. return;
  5599. }
  5600. if (!mg_fopen(conn, path, "rb", &file)) {
  5601. mg_cry(conn,
  5602. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  5603. tag,
  5604. path,
  5605. strerror(ERRNO));
  5606. } else {
  5607. fclose_on_exec(&file, conn);
  5608. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  5609. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  5610. path) > 0) {
  5611. send_ssi_file(conn, path, &file, include_level + 1);
  5612. } else {
  5613. send_file_data(conn, &file, 0, INT64_MAX);
  5614. }
  5615. mg_fclose(&file);
  5616. }
  5617. }
  5618. #if !defined(NO_POPEN)
  5619. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  5620. {
  5621. char cmd[1024] = "";
  5622. struct file file = STRUCT_FILE_INITIALIZER;
  5623. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  5624. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  5625. } else {
  5626. cmd[1023] = 0;
  5627. if ((file.fp = popen(cmd, "r")) == NULL) {
  5628. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  5629. } else {
  5630. send_file_data(conn, &file, 0, INT64_MAX);
  5631. pclose(file.fp);
  5632. }
  5633. }
  5634. }
  5635. #endif /* !NO_POPEN */
  5636. static int mg_fgetc(struct file *filep, int offset)
  5637. {
  5638. if (filep == NULL)
  5639. return EOF;
  5640. if (filep->membuf != NULL && offset >= 0 &&
  5641. ((unsigned int)(offset)) < filep->size) {
  5642. return ((unsigned char *)filep->membuf)[offset];
  5643. } else if (filep->fp != NULL) {
  5644. return fgetc(filep->fp);
  5645. } else {
  5646. return EOF;
  5647. }
  5648. }
  5649. static void send_ssi_file(struct mg_connection *conn,
  5650. const char *path,
  5651. struct file *filep,
  5652. int include_level)
  5653. {
  5654. char buf[MG_BUF_LEN];
  5655. int ch, offset, len, in_ssi_tag;
  5656. if (include_level > 10) {
  5657. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  5658. return;
  5659. }
  5660. in_ssi_tag = len = offset = 0;
  5661. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  5662. if (in_ssi_tag && ch == '>') {
  5663. in_ssi_tag = 0;
  5664. buf[len++] = (char)ch;
  5665. buf[len] = '\0';
  5666. /* assert(len <= (int) sizeof(buf)); */
  5667. if (len > (int)sizeof(buf))
  5668. break;
  5669. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  5670. /* Not an SSI tag, pass it */
  5671. (void)mg_write(conn, buf, (size_t)len);
  5672. } else {
  5673. if (!memcmp(buf + 5, "include", 7)) {
  5674. do_ssi_include(conn, path, buf + 12, include_level);
  5675. #if !defined(NO_POPEN)
  5676. } else if (!memcmp(buf + 5, "exec", 4)) {
  5677. do_ssi_exec(conn, buf + 9);
  5678. #endif /* !NO_POPEN */
  5679. } else {
  5680. mg_cry(conn,
  5681. "%s: unknown SSI "
  5682. "command: \"%s\"",
  5683. path,
  5684. buf);
  5685. }
  5686. }
  5687. len = 0;
  5688. } else if (in_ssi_tag) {
  5689. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  5690. /* Not an SSI tag */
  5691. in_ssi_tag = 0;
  5692. } else if (len == (int)sizeof(buf) - 2) {
  5693. mg_cry(conn, "%s: SSI tag is too large", path);
  5694. len = 0;
  5695. }
  5696. buf[len++] = (char)(ch & 0xff);
  5697. } else if (ch == '<') {
  5698. in_ssi_tag = 1;
  5699. if (len > 0) {
  5700. mg_write(conn, buf, (size_t)len);
  5701. }
  5702. len = 0;
  5703. buf[len++] = (char)(ch & 0xff);
  5704. } else {
  5705. buf[len++] = (char)(ch & 0xff);
  5706. if (len == (int)sizeof(buf)) {
  5707. mg_write(conn, buf, (size_t)len);
  5708. len = 0;
  5709. }
  5710. }
  5711. }
  5712. /* Send the rest of buffered data */
  5713. if (len > 0) {
  5714. mg_write(conn, buf, (size_t)len);
  5715. }
  5716. }
  5717. static void handle_ssi_file_request(struct mg_connection *conn,
  5718. const char *path,
  5719. struct file *filep)
  5720. {
  5721. char date[64];
  5722. time_t curtime = time(NULL);
  5723. const char *cors1, *cors2, *cors3;
  5724. if (!conn)
  5725. return;
  5726. if (mg_get_header(conn, "Origin")) {
  5727. /* Cross-origin resource sharing (CORS). */
  5728. cors1 = "Access-Control-Allow-Origin: ";
  5729. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5730. cors3 = "\r\n";
  5731. } else {
  5732. cors1 = cors2 = cors3 = "";
  5733. }
  5734. if (!mg_fopen(conn, path, "rb", filep)) {
  5735. /* File exists (precondition for calling this function),
  5736. * but can not be opened by the server. */
  5737. send_http_error(conn,
  5738. 500,
  5739. "Error: Cannot read file\nfopen(%s): %s",
  5740. path,
  5741. strerror(ERRNO));
  5742. } else {
  5743. conn->must_close = 1;
  5744. gmt_time_string(date, sizeof(date), &curtime);
  5745. fclose_on_exec(filep, conn);
  5746. mg_printf(conn,
  5747. "HTTP/1.1 200 OK\r\n"
  5748. "%s%s%s"
  5749. "Date: %s\r\n"
  5750. "Content-Type: text/html\r\n"
  5751. "Connection: %s\r\n\r\n",
  5752. cors1,
  5753. cors2,
  5754. cors3,
  5755. date,
  5756. suggest_connection_header(conn));
  5757. send_ssi_file(conn, path, filep, 0);
  5758. mg_fclose(filep);
  5759. }
  5760. }
  5761. static void send_options(struct mg_connection *conn)
  5762. {
  5763. char date[64];
  5764. time_t curtime = time(NULL);
  5765. if (!conn)
  5766. return;
  5767. conn->status_code = 200;
  5768. conn->must_close = 1;
  5769. gmt_time_string(date, sizeof(date), &curtime);
  5770. mg_printf(conn,
  5771. "HTTP/1.1 200 OK\r\n"
  5772. "Date: %s\r\n"
  5773. "Connection: %s\r\n"
  5774. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  5775. "PROPFIND, MKCOL\r\n"
  5776. "DAV: 1\r\n\r\n",
  5777. date,
  5778. suggest_connection_header(conn));
  5779. }
  5780. /* Writes PROPFIND properties for a collection element */
  5781. static void
  5782. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  5783. {
  5784. char mtime[64];
  5785. if (!filep || !conn)
  5786. return;
  5787. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  5788. conn->num_bytes_sent +=
  5789. mg_printf(conn,
  5790. "<d:response>"
  5791. "<d:href>%s</d:href>"
  5792. "<d:propstat>"
  5793. "<d:prop>"
  5794. "<d:resourcetype>%s</d:resourcetype>"
  5795. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  5796. "<d:getlastmodified>%s</d:getlastmodified>"
  5797. "</d:prop>"
  5798. "<d:status>HTTP/1.1 200 OK</d:status>"
  5799. "</d:propstat>"
  5800. "</d:response>\n",
  5801. uri,
  5802. filep->is_directory ? "<d:collection/>" : "",
  5803. filep->size,
  5804. mtime);
  5805. }
  5806. static void print_dav_dir_entry(struct de *de, void *data)
  5807. {
  5808. char href[PATH_MAX];
  5809. char href_encoded[PATH_MAX];
  5810. struct mg_connection *conn = (struct mg_connection *)data;
  5811. if (!de || !conn)
  5812. return;
  5813. mg_snprintf(conn,
  5814. href,
  5815. sizeof(href),
  5816. "%s%s",
  5817. conn->request_info.uri,
  5818. de->file_name);
  5819. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  5820. print_props(conn, href_encoded, &de->file);
  5821. }
  5822. static void handle_propfind(struct mg_connection *conn,
  5823. const char *path,
  5824. struct file *filep)
  5825. {
  5826. const char *depth = mg_get_header(conn, "Depth");
  5827. char date[64];
  5828. time_t curtime = time(NULL);
  5829. gmt_time_string(date, sizeof(date), &curtime);
  5830. if (!conn)
  5831. return;
  5832. conn->must_close = 1;
  5833. conn->status_code = 207;
  5834. mg_printf(conn,
  5835. "HTTP/1.1 207 Multi-Status\r\n"
  5836. "Date: %s\r\n"
  5837. "Connection: %s\r\n"
  5838. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  5839. date,
  5840. suggest_connection_header(conn));
  5841. conn->num_bytes_sent +=
  5842. mg_printf(conn,
  5843. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  5844. "<d:multistatus xmlns:d='DAV:'>\n");
  5845. /* Print properties for the requested resource itself */
  5846. print_props(conn, conn->request_info.uri, filep);
  5847. /* If it is a directory, print directory entries too if Depth is not 0 */
  5848. if (filep && conn->ctx && filep->is_directory &&
  5849. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  5850. (depth == NULL || strcmp(depth, "0") != 0)) {
  5851. scan_directory(conn, path, conn, &print_dav_dir_entry);
  5852. }
  5853. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  5854. }
  5855. void mg_lock_connection(struct mg_connection *conn)
  5856. {
  5857. if (conn)
  5858. (void)pthread_mutex_lock(&conn->mutex);
  5859. }
  5860. void mg_unlock_connection(struct mg_connection *conn)
  5861. {
  5862. if (conn)
  5863. (void)pthread_mutex_unlock(&conn->mutex);
  5864. }
  5865. void mg_lock_context(struct mg_context *ctx)
  5866. {
  5867. if (ctx)
  5868. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  5869. }
  5870. void mg_unlock_context(struct mg_context *ctx)
  5871. {
  5872. if (ctx)
  5873. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  5874. }
  5875. #if defined(USE_TIMERS)
  5876. #include "timer.inl"
  5877. #endif /* USE_TIMERS */
  5878. #ifdef USE_LUA
  5879. #include "mod_lua.inl"
  5880. #endif /* USE_LUA */
  5881. #if defined(USE_WEBSOCKET)
  5882. /* START OF SHA-1 code
  5883. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  5884. #define SHA1HANDSOFF
  5885. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  5886. *
  5887. * #if defined(__sun)
  5888. * #include "solarisfixes.h"
  5889. * #endif
  5890. */
  5891. static int is_big_endian(void)
  5892. {
  5893. static const int n = 1;
  5894. return ((char *)&n)[0] == 0;
  5895. }
  5896. union char64long16 {
  5897. unsigned char c[64];
  5898. uint32_t l[16];
  5899. };
  5900. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5901. static uint32_t blk0(union char64long16 *block, int i)
  5902. {
  5903. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  5904. if (!is_big_endian()) {
  5905. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5906. (rol(block->l[i], 8) & 0x00FF00FF);
  5907. }
  5908. return block->l[i];
  5909. }
  5910. #define blk(i) \
  5911. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5912. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5913. 1))
  5914. #define R0(v, w, x, y, z, i) \
  5915. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5916. w = rol(w, 30);
  5917. #define R1(v, w, x, y, z, i) \
  5918. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5919. w = rol(w, 30);
  5920. #define R2(v, w, x, y, z, i) \
  5921. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5922. w = rol(w, 30);
  5923. #define R3(v, w, x, y, z, i) \
  5924. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5925. w = rol(w, 30);
  5926. #define R4(v, w, x, y, z, i) \
  5927. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5928. w = rol(w, 30);
  5929. typedef struct {
  5930. uint32_t state[5];
  5931. uint32_t count[2];
  5932. unsigned char buffer[64];
  5933. } SHA1_CTX;
  5934. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  5935. {
  5936. uint32_t a, b, c, d, e;
  5937. union char64long16 block[1];
  5938. memcpy(block, buffer, 64);
  5939. a = state[0];
  5940. b = state[1];
  5941. c = state[2];
  5942. d = state[3];
  5943. e = state[4];
  5944. R0(a, b, c, d, e, 0);
  5945. R0(e, a, b, c, d, 1);
  5946. R0(d, e, a, b, c, 2);
  5947. R0(c, d, e, a, b, 3);
  5948. R0(b, c, d, e, a, 4);
  5949. R0(a, b, c, d, e, 5);
  5950. R0(e, a, b, c, d, 6);
  5951. R0(d, e, a, b, c, 7);
  5952. R0(c, d, e, a, b, 8);
  5953. R0(b, c, d, e, a, 9);
  5954. R0(a, b, c, d, e, 10);
  5955. R0(e, a, b, c, d, 11);
  5956. R0(d, e, a, b, c, 12);
  5957. R0(c, d, e, a, b, 13);
  5958. R0(b, c, d, e, a, 14);
  5959. R0(a, b, c, d, e, 15);
  5960. R1(e, a, b, c, d, 16);
  5961. R1(d, e, a, b, c, 17);
  5962. R1(c, d, e, a, b, 18);
  5963. R1(b, c, d, e, a, 19);
  5964. R2(a, b, c, d, e, 20);
  5965. R2(e, a, b, c, d, 21);
  5966. R2(d, e, a, b, c, 22);
  5967. R2(c, d, e, a, b, 23);
  5968. R2(b, c, d, e, a, 24);
  5969. R2(a, b, c, d, e, 25);
  5970. R2(e, a, b, c, d, 26);
  5971. R2(d, e, a, b, c, 27);
  5972. R2(c, d, e, a, b, 28);
  5973. R2(b, c, d, e, a, 29);
  5974. R2(a, b, c, d, e, 30);
  5975. R2(e, a, b, c, d, 31);
  5976. R2(d, e, a, b, c, 32);
  5977. R2(c, d, e, a, b, 33);
  5978. R2(b, c, d, e, a, 34);
  5979. R2(a, b, c, d, e, 35);
  5980. R2(e, a, b, c, d, 36);
  5981. R2(d, e, a, b, c, 37);
  5982. R2(c, d, e, a, b, 38);
  5983. R2(b, c, d, e, a, 39);
  5984. R3(a, b, c, d, e, 40);
  5985. R3(e, a, b, c, d, 41);
  5986. R3(d, e, a, b, c, 42);
  5987. R3(c, d, e, a, b, 43);
  5988. R3(b, c, d, e, a, 44);
  5989. R3(a, b, c, d, e, 45);
  5990. R3(e, a, b, c, d, 46);
  5991. R3(d, e, a, b, c, 47);
  5992. R3(c, d, e, a, b, 48);
  5993. R3(b, c, d, e, a, 49);
  5994. R3(a, b, c, d, e, 50);
  5995. R3(e, a, b, c, d, 51);
  5996. R3(d, e, a, b, c, 52);
  5997. R3(c, d, e, a, b, 53);
  5998. R3(b, c, d, e, a, 54);
  5999. R3(a, b, c, d, e, 55);
  6000. R3(e, a, b, c, d, 56);
  6001. R3(d, e, a, b, c, 57);
  6002. R3(c, d, e, a, b, 58);
  6003. R3(b, c, d, e, a, 59);
  6004. R4(a, b, c, d, e, 60);
  6005. R4(e, a, b, c, d, 61);
  6006. R4(d, e, a, b, c, 62);
  6007. R4(c, d, e, a, b, 63);
  6008. R4(b, c, d, e, a, 64);
  6009. R4(a, b, c, d, e, 65);
  6010. R4(e, a, b, c, d, 66);
  6011. R4(d, e, a, b, c, 67);
  6012. R4(c, d, e, a, b, 68);
  6013. R4(b, c, d, e, a, 69);
  6014. R4(a, b, c, d, e, 70);
  6015. R4(e, a, b, c, d, 71);
  6016. R4(d, e, a, b, c, 72);
  6017. R4(c, d, e, a, b, 73);
  6018. R4(b, c, d, e, a, 74);
  6019. R4(a, b, c, d, e, 75);
  6020. R4(e, a, b, c, d, 76);
  6021. R4(d, e, a, b, c, 77);
  6022. R4(c, d, e, a, b, 78);
  6023. R4(b, c, d, e, a, 79);
  6024. state[0] += a;
  6025. state[1] += b;
  6026. state[2] += c;
  6027. state[3] += d;
  6028. state[4] += e;
  6029. a = b = c = d = e = 0;
  6030. memset(block, '\0', sizeof(block));
  6031. }
  6032. static void SHA1Init(SHA1_CTX *context)
  6033. {
  6034. context->state[0] = 0x67452301;
  6035. context->state[1] = 0xEFCDAB89;
  6036. context->state[2] = 0x98BADCFE;
  6037. context->state[3] = 0x10325476;
  6038. context->state[4] = 0xC3D2E1F0;
  6039. context->count[0] = context->count[1] = 0;
  6040. }
  6041. static void
  6042. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6043. {
  6044. uint32_t i, j;
  6045. j = context->count[0];
  6046. if ((context->count[0] += len << 3) < j)
  6047. context->count[1]++;
  6048. context->count[1] += (len >> 29);
  6049. j = (j >> 3) & 63;
  6050. if ((j + len) > 63) {
  6051. memcpy(&context->buffer[j], data, (i = 64 - j));
  6052. SHA1Transform(context->state, context->buffer);
  6053. for (; i + 63 < len; i += 64) {
  6054. SHA1Transform(context->state, &data[i]);
  6055. }
  6056. j = 0;
  6057. } else
  6058. i = 0;
  6059. memcpy(&context->buffer[j], &data[i], len - i);
  6060. }
  6061. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6062. {
  6063. unsigned i;
  6064. unsigned char finalcount[8], c;
  6065. for (i = 0; i < 8; i++) {
  6066. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  6067. ((3 - (i & 3)) * 8)) &
  6068. 255);
  6069. }
  6070. c = 0200;
  6071. SHA1Update(context, &c, 1);
  6072. while ((context->count[0] & 504) != 448) {
  6073. c = 0000;
  6074. SHA1Update(context, &c, 1);
  6075. }
  6076. SHA1Update(context, finalcount, 8);
  6077. for (i = 0; i < 20; i++) {
  6078. digest[i] =
  6079. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  6080. 255);
  6081. }
  6082. memset(context, '\0', sizeof(*context));
  6083. memset(&finalcount, '\0', sizeof(finalcount));
  6084. }
  6085. /* END OF SHA1 CODE */
  6086. static void send_websocket_handshake(struct mg_connection *conn)
  6087. {
  6088. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  6089. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  6090. SHA1_CTX sha_ctx;
  6091. mg_snprintf(conn,
  6092. buf,
  6093. sizeof(buf),
  6094. "%s%s",
  6095. mg_get_header(conn, "Sec-WebSocket-Key"),
  6096. magic);
  6097. SHA1Init(&sha_ctx);
  6098. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  6099. SHA1Final((unsigned char *)sha, &sha_ctx);
  6100. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  6101. mg_printf(conn,
  6102. "%s%s%s",
  6103. "HTTP/1.1 101 Switching Protocols\r\n"
  6104. "Upgrade: websocket\r\n"
  6105. "Connection: Upgrade\r\n"
  6106. "Sec-WebSocket-Accept: ",
  6107. b64_sha,
  6108. "\r\n\r\n");
  6109. }
  6110. static void read_websocket(struct mg_connection *conn,
  6111. mg_websocket_data_handler ws_data_handler,
  6112. void *callback_data)
  6113. {
  6114. /* Pointer to the beginning of the portion of the incoming websocket
  6115. * message queue.
  6116. * The original websocket upgrade request is never removed, so the queue
  6117. * begins after it. */
  6118. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  6119. int n, error, exit_by_callback;
  6120. /* body_len is the length of the entire queue in bytes
  6121. * len is the length of the current message
  6122. * data_len is the length of the current message's data payload
  6123. * header_len is the length of the current message's header */
  6124. size_t i, len, mask_len, data_len, header_len, body_len;
  6125. /* "The masking key is a 32-bit value chosen at random by the client."
  6126. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  6127. */
  6128. unsigned char mask[4];
  6129. /* data points to the place where the message is stored when passed to the
  6130. * websocket_data callback. This is either mem on the stack, or a
  6131. * dynamically allocated buffer if it is too large. */
  6132. char mem[4096];
  6133. char *data = mem;
  6134. unsigned char mop; /* mask flag and opcode */
  6135. double timeout = -1.0;
  6136. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  6137. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  6138. }
  6139. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  6140. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6141. }
  6142. mg_set_thread_name("wsock");
  6143. /* Loop continuously, reading messages from the socket, invoking the
  6144. * callback, and waiting repeatedly until an error occurs. */
  6145. while (!conn->ctx->stop_flag) {
  6146. header_len = 0;
  6147. assert(conn->data_len >= conn->request_len);
  6148. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  6149. len = buf[1] & 127;
  6150. mask_len = buf[1] & 128 ? 4 : 0;
  6151. if (len < 126 && body_len >= mask_len) {
  6152. data_len = len;
  6153. header_len = 2 + mask_len;
  6154. } else if (len == 126 && body_len >= 4 + mask_len) {
  6155. header_len = 4 + mask_len;
  6156. data_len = ((((int)buf[2]) << 8) + buf[3]);
  6157. } else if (body_len >= 10 + mask_len) {
  6158. header_len = 10 + mask_len;
  6159. data_len = (((uint64_t)ntohl(*(uint32_t *)&buf[2])) << 32) +
  6160. ntohl(*(uint32_t *)&buf[6]);
  6161. }
  6162. }
  6163. if (header_len > 0 && body_len >= header_len) {
  6164. /* Allocate space to hold websocket payload */
  6165. data = mem;
  6166. if (data_len > sizeof(mem)) {
  6167. data = (char *)mg_malloc(data_len);
  6168. if (data == NULL) {
  6169. /* Allocation failed, exit the loop and then close the
  6170. * connection */
  6171. mg_cry(conn, "websocket out of memory; closing connection");
  6172. break;
  6173. }
  6174. }
  6175. /* Copy the mask before we shift the queue and destroy it */
  6176. if (mask_len > 0) {
  6177. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  6178. } else {
  6179. memset(mask, 0, sizeof(mask));
  6180. }
  6181. /* Read frame payload from the first message in the queue into
  6182. * data and advance the queue by moving the memory in place. */
  6183. assert(body_len >= header_len);
  6184. if (data_len + header_len > body_len) {
  6185. mop = buf[0]; /* current mask and opcode */
  6186. /* Overflow case */
  6187. len = body_len - header_len;
  6188. memcpy(data, buf + header_len, len);
  6189. error = 0;
  6190. while (len < data_len) {
  6191. n = pull(
  6192. NULL, conn, data + len, (int)(data_len - len), timeout);
  6193. if (n <= 0) {
  6194. error = 1;
  6195. break;
  6196. }
  6197. len += n;
  6198. }
  6199. if (error) {
  6200. mg_cry(conn, "Websocket pull failed; closing connection");
  6201. break;
  6202. }
  6203. conn->data_len = conn->request_len;
  6204. } else {
  6205. mop = buf[0]; /* current mask and opcode, overwritten by
  6206. * memmove() */
  6207. /* Length of the message being read at the front of the
  6208. * queue */
  6209. len = data_len + header_len;
  6210. /* Copy the data payload into the data pointer for the
  6211. * callback */
  6212. memcpy(data, buf + header_len, data_len);
  6213. /* Move the queue forward len bytes */
  6214. memmove(buf, buf + len, body_len - len);
  6215. /* Mark the queue as advanced */
  6216. conn->data_len -= (int)len;
  6217. }
  6218. /* Apply mask if necessary */
  6219. if (mask_len > 0) {
  6220. for (i = 0; i < data_len; ++i) {
  6221. data[i] ^= mask[i & 3];
  6222. }
  6223. }
  6224. /* Exit the loop if callback signals to exit (server side),
  6225. * or "connection close" opcode received (client side). */
  6226. exit_by_callback = 0;
  6227. if ((ws_data_handler != NULL) &&
  6228. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  6229. exit_by_callback = 1;
  6230. }
  6231. if (data != mem) {
  6232. mg_free(data);
  6233. }
  6234. if (exit_by_callback ||
  6235. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  6236. /* Opcode == 8, connection close */
  6237. break;
  6238. }
  6239. /* Not breaking the loop, process next websocket frame. */
  6240. } else {
  6241. /* Read from the socket into the next available location in the
  6242. * message queue. */
  6243. if ((n = pull(NULL,
  6244. conn,
  6245. conn->buf + conn->data_len,
  6246. conn->buf_size - conn->data_len,
  6247. timeout)) <= 0) {
  6248. /* Error, no bytes read */
  6249. break;
  6250. }
  6251. conn->data_len += n;
  6252. }
  6253. }
  6254. mg_set_thread_name("worker");
  6255. }
  6256. int mg_websocket_write(struct mg_connection *conn,
  6257. int opcode,
  6258. const char *data,
  6259. size_t dataLen)
  6260. {
  6261. unsigned char header[10];
  6262. size_t headerLen = 1;
  6263. int retval = -1;
  6264. header[0] = 0x80 + (opcode & 0xF);
  6265. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  6266. if (dataLen < 126) {
  6267. /* inline 7-bit length field */
  6268. header[1] = (unsigned char)dataLen;
  6269. headerLen = 2;
  6270. } else if (dataLen <= 0xFFFF) {
  6271. /* 16-bit length field */
  6272. header[1] = 126;
  6273. *(uint16_t *)(header + 2) = htons((uint16_t)dataLen);
  6274. headerLen = 4;
  6275. } else {
  6276. /* 64-bit length field */
  6277. header[1] = 127;
  6278. *(uint32_t *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  6279. *(uint32_t *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  6280. headerLen = 10;
  6281. }
  6282. /* Note that POSIX/Winsock's send() is threadsafe
  6283. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  6284. * but mongoose's mg_printf/mg_write is not (because of the loop in
  6285. * push(), although that is only a problem if the packet is large or
  6286. * outgoing buffer is full). */
  6287. (void)mg_lock_connection(conn);
  6288. retval = mg_write(conn, header, headerLen);
  6289. retval = mg_write(conn, data, dataLen);
  6290. mg_unlock_connection(conn);
  6291. return retval;
  6292. }
  6293. static void
  6294. handle_websocket_request(struct mg_connection *conn,
  6295. const char *path,
  6296. int is_callback_resource,
  6297. mg_websocket_connect_handler ws_connect_handler,
  6298. mg_websocket_ready_handler ws_ready_handler,
  6299. mg_websocket_data_handler ws_data_handler,
  6300. mg_websocket_close_handler ws_close_handler,
  6301. void *cbData)
  6302. {
  6303. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  6304. int lua_websock = 0;
  6305. #if !defined(USE_LUA)
  6306. (void)path;
  6307. #endif
  6308. /* Step 1: Check websocket protocol version. */
  6309. if (version == NULL || strcmp(version, "13") != 0) {
  6310. /* Reject wrong versions */
  6311. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  6312. return;
  6313. }
  6314. /* Step 2: If a callback is responsible, call it. */
  6315. if (is_callback_resource) {
  6316. if (ws_connect_handler != NULL &&
  6317. ws_connect_handler(conn, cbData) != 0) {
  6318. /* C callback has returned non-zero, do not proceed with handshake.
  6319. */
  6320. /* Note that C callbacks are no longer called when Lua is
  6321. * responsible, so C can no longer filter callbacks for Lua. */
  6322. return;
  6323. }
  6324. }
  6325. #if defined(USE_LUA)
  6326. /* Step 3: No callback. Check if Lua is responsible. */
  6327. else {
  6328. /* Step 3.1: Check if Lua is responsible. */
  6329. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  6330. lua_websock = match_prefix(
  6331. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  6332. strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  6333. path);
  6334. }
  6335. if (lua_websock) {
  6336. /* Step 3.2: Lua is responsible: call it. */
  6337. conn->lua_websocket_state = lua_websocket_new(path, conn);
  6338. if (!conn->lua_websocket_state) {
  6339. /* Lua rejected the new client */
  6340. return;
  6341. }
  6342. }
  6343. }
  6344. #endif
  6345. /* Step 4: Check if there is a responsible websocket handler. */
  6346. if (!is_callback_resource && !lua_websock) {
  6347. /* There is no callback, an Lua is not responsible either. */
  6348. /* Reply with a 404 Not Found or with nothing at all?
  6349. * TODO (mid): check the websocket standards, how to reply to
  6350. * requests to invalid websocket addresses. */
  6351. send_http_error(conn, 404, "%s", "Not found");
  6352. return;
  6353. }
  6354. /* Step 5: The websocket connection has been accepted */
  6355. send_websocket_handshake(conn);
  6356. /* Step 6: Call the ready handler */
  6357. if (is_callback_resource) {
  6358. if (ws_ready_handler != NULL) {
  6359. ws_ready_handler(conn, cbData);
  6360. }
  6361. #if defined(USE_LUA)
  6362. } else if (lua_websock) {
  6363. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  6364. /* the ready handler returned false */
  6365. return;
  6366. }
  6367. #endif
  6368. }
  6369. /* Step 7: Enter the read loop */
  6370. if (is_callback_resource) {
  6371. read_websocket(conn, ws_data_handler, cbData);
  6372. #if defined(USE_LUA)
  6373. } else if (lua_websock) {
  6374. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  6375. #endif
  6376. }
  6377. /* Step 8: Call the close handler */
  6378. if (ws_close_handler) {
  6379. ws_close_handler(conn, cbData);
  6380. }
  6381. }
  6382. static int is_websocket_protocol(const struct mg_connection *conn)
  6383. {
  6384. const char *host, *upgrade, *connection, *version, *key;
  6385. upgrade = mg_get_header(conn, "Upgrade");
  6386. if (upgrade == NULL)
  6387. return 0; /* fail early, don't waste time checking other header fields
  6388. */
  6389. if (!mg_strcasestr(upgrade, "websocket"))
  6390. return 0;
  6391. connection = mg_get_header(conn, "Connection");
  6392. if (connection == NULL)
  6393. return 0;
  6394. if (!mg_strcasestr(connection, "upgrade"))
  6395. return 0;
  6396. host = mg_get_header(conn, "Host");
  6397. key = mg_get_header(conn, "Sec-WebSocket-Key");
  6398. version = mg_get_header(conn, "Sec-WebSocket-Version");
  6399. return host != NULL && key != NULL && version != NULL;
  6400. }
  6401. #endif /* !USE_WEBSOCKET */
  6402. static int isbyte(int n) { return n >= 0 && n <= 255; }
  6403. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  6404. {
  6405. int n, a, b, c, d, slash = 32, len = 0;
  6406. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  6407. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  6408. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  6409. slash < 33) {
  6410. len = n;
  6411. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) |
  6412. (uint32_t)d;
  6413. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  6414. }
  6415. return len;
  6416. }
  6417. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  6418. {
  6419. int throttle = 0;
  6420. struct vec vec, val;
  6421. uint32_t net, mask;
  6422. char mult;
  6423. double v;
  6424. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  6425. mult = ',';
  6426. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  6427. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  6428. mult != ',')) {
  6429. continue;
  6430. }
  6431. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  6432. : 1;
  6433. if (vec.len == 1 && vec.ptr[0] == '*') {
  6434. throttle = (int)v;
  6435. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  6436. if ((remote_ip & mask) == net) {
  6437. throttle = (int)v;
  6438. }
  6439. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  6440. throttle = (int)v;
  6441. }
  6442. }
  6443. return throttle;
  6444. }
  6445. static uint32_t get_remote_ip(const struct mg_connection *conn)
  6446. {
  6447. if (!conn)
  6448. return 0;
  6449. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  6450. }
  6451. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  6452. {
  6453. /* TODO (mid): set a timeout */
  6454. const char *content_type_header, *boundary_start, *sc;
  6455. char *s;
  6456. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX], fname[1024],
  6457. boundary[100];
  6458. FILE *fp;
  6459. int bl, n, i, headers_len, boundary_len, eof, len = 0,
  6460. num_uploaded_files = 0;
  6461. struct mg_request_info part_request_info;
  6462. /* Request looks like this:
  6463. *
  6464. * POST /upload HTTP/1.1
  6465. * Host: 127.0.0.1:8080
  6466. * Content-Length: 244894
  6467. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  6468. *
  6469. * ------WebKitFormBoundaryRVr
  6470. * Content-Disposition: form-data; name="file"; filename="accum.png"
  6471. * Content-Type: image/png
  6472. *
  6473. * <89>PNG
  6474. * <PNG DATA>
  6475. * ------WebKitFormBoundaryRVr */
  6476. /* Extract boundary string from the Content-Type header */
  6477. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  6478. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  6479. NULL ||
  6480. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  6481. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  6482. boundary[0] == '\0') {
  6483. return num_uploaded_files;
  6484. }
  6485. boundary[99] = 0;
  6486. boundary_len = (int)strlen(boundary);
  6487. bl = boundary_len + 4; /* \r\n--<boundary> */
  6488. for (;;) {
  6489. /* Pull in headers */
  6490. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  6491. if (len < 0 || len > (int)sizeof(buf))
  6492. break;
  6493. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  6494. len += n;
  6495. /* assert(len <= (int) sizeof(buf)); */
  6496. if (len > (int)sizeof(buf))
  6497. break;
  6498. }
  6499. if ((headers_len = get_request_len(buf, len)) <= 0) {
  6500. break;
  6501. }
  6502. /* terminate header */
  6503. buf[headers_len - 1] = 0;
  6504. /* Scan for the boundary string and skip it */
  6505. if (buf[0] == '-' && buf[1] == '-' &&
  6506. !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  6507. s = &buf[bl];
  6508. } else {
  6509. s = &buf[2];
  6510. }
  6511. /* Get headers for this part of the multipart message */
  6512. memset(&part_request_info, 0, sizeof(part_request_info));
  6513. parse_http_headers(&s, &part_request_info);
  6514. /* assert(&buf[headers_len-1] == s); */
  6515. if (&buf[headers_len - 1] != s)
  6516. break;
  6517. /* Fetch file name. */
  6518. sc = get_header(&part_request_info, "Content-Disposition");
  6519. if (!sc) {
  6520. /* invalid part of a multipart message */
  6521. break;
  6522. }
  6523. sc = strstr(sc, "filename");
  6524. if (!sc) {
  6525. /* no filename set */
  6526. break;
  6527. }
  6528. sc += 8; /* skip "filename" */
  6529. fname[0] = '\0';
  6530. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  6531. fname[1023] = 0;
  6532. /* Give up if the headers are not what we expect */
  6533. if (fname[0] == '\0') {
  6534. break;
  6535. }
  6536. /* Construct destination file name. Do not allow paths to have
  6537. * slashes. */
  6538. if ((s = strrchr(fname, '/')) == NULL &&
  6539. (s = strrchr(fname, '\\')) == NULL) {
  6540. s = fname;
  6541. } else {
  6542. s++;
  6543. }
  6544. /* There data is written to a temporary file first. */
  6545. /* Different users should use a different destination_dir. */
  6546. snprintf(path, sizeof(path) - 1, "%s/%s", destination_dir, s);
  6547. strcpy(tmp_path, path);
  6548. strcat(tmp_path, "~");
  6549. /* We open the file with exclusive lock held. This guarantee us
  6550. * there is no other thread can save into the same file
  6551. * simultaneously. */
  6552. fp = NULL;
  6553. /* Open file in binary mode. */
  6554. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  6555. break;
  6556. }
  6557. /* Move data to the beginning of the buffer */
  6558. /* part_request_info is no longer valid after this operation */
  6559. /* assert(len >= headers_len); */
  6560. if (len < headers_len)
  6561. break;
  6562. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  6563. len -= headers_len;
  6564. /* Read POST data, write into file until boundary is found. */
  6565. eof = n = 0;
  6566. do {
  6567. len += n;
  6568. for (i = 0; i < len - bl; i++) {
  6569. if (!memcmp(&buf[i], "\r\n--", 4) &&
  6570. !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  6571. /* Found boundary, that's the end of file data. */
  6572. fwrite(buf, 1, (size_t)i, fp);
  6573. eof = 1;
  6574. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  6575. len -= i + bl;
  6576. break;
  6577. }
  6578. }
  6579. if (!eof && len > bl) {
  6580. fwrite(buf, 1, (size_t)(len - bl), fp);
  6581. memmove(buf, &buf[len - bl], (size_t)bl);
  6582. len = bl;
  6583. }
  6584. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  6585. } while (!eof && (n > 0));
  6586. fclose(fp);
  6587. if (eof) {
  6588. remove(path);
  6589. rename(tmp_path, path);
  6590. num_uploaded_files++;
  6591. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  6592. conn->ctx->callbacks.upload(conn, path);
  6593. }
  6594. } else {
  6595. remove(tmp_path);
  6596. }
  6597. }
  6598. return num_uploaded_files;
  6599. }
  6600. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  6601. {
  6602. unsigned int i;
  6603. int idx = -1;
  6604. if (ctx)
  6605. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  6606. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  6607. }
  6608. return idx;
  6609. }
  6610. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  6611. {
  6612. char host[1025];
  6613. const char *host_header;
  6614. size_t hostlen;
  6615. host_header = mg_get_header(conn, "Host");
  6616. hostlen = sizeof(host);
  6617. if (host_header != NULL) {
  6618. char *pos;
  6619. mg_strlcpy(host, host_header, hostlen);
  6620. host[hostlen - 1] = '\0';
  6621. pos = strchr(host, ':');
  6622. if (pos != NULL) {
  6623. *pos = '\0';
  6624. }
  6625. } else {
  6626. /* Cannot get host from the Host: header.
  6627. * Fallback to our IP address. */
  6628. if (conn)
  6629. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  6630. }
  6631. /* Send host, port, uri and (if it exists) ?query_string */
  6632. if (conn)
  6633. mg_printf(conn,
  6634. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  6635. host,
  6636. (int)ntohs(
  6637. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  6638. conn->request_info.uri,
  6639. (conn->request_info.query_string == NULL) ? "" : "?",
  6640. (conn->request_info.query_string == NULL)
  6641. ? ""
  6642. : conn->request_info.query_string);
  6643. }
  6644. static void
  6645. mg_set_request_handler_type(struct mg_context *ctx,
  6646. const char *uri,
  6647. int is_websocket_handler,
  6648. int is_delete_request,
  6649. mg_request_handler handler,
  6650. mg_websocket_connect_handler connect_handler,
  6651. mg_websocket_ready_handler ready_handler,
  6652. mg_websocket_data_handler data_handler,
  6653. mg_websocket_close_handler close_handler,
  6654. void *cbdata)
  6655. {
  6656. struct mg_request_handler_info *tmp_rh, **lastref;
  6657. size_t urilen = strlen(uri);
  6658. if (is_websocket_handler) {
  6659. /* assert(handler == NULL); */
  6660. /* assert(is_delete_request || connect_handler!=NULL ||
  6661. * ready_handler!=NULL || data_handler!=NULL ||
  6662. * close_handler!=NULL);
  6663. */
  6664. if (handler != NULL)
  6665. return;
  6666. if (!is_delete_request && connect_handler == NULL &&
  6667. ready_handler == NULL && data_handler == NULL &&
  6668. close_handler == NULL)
  6669. return;
  6670. } else {
  6671. /* assert(connect_handler==NULL && ready_handler==NULL &&
  6672. * data_handler==NULL && close_handler==NULL); */
  6673. /* assert(is_delete_request || (handler!=NULL));
  6674. */
  6675. if (connect_handler != NULL || ready_handler != NULL ||
  6676. data_handler != NULL || close_handler != NULL)
  6677. return;
  6678. if (!is_delete_request && (handler == NULL))
  6679. return;
  6680. }
  6681. if (!ctx)
  6682. return;
  6683. mg_lock_context(ctx);
  6684. /* first try to find an existing handler */
  6685. lastref = &(ctx->request_handlers);
  6686. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  6687. tmp_rh = tmp_rh->next) {
  6688. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  6689. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6690. if (!is_delete_request) {
  6691. /* update existing handler */
  6692. if (!is_websocket_handler) {
  6693. tmp_rh->handler = handler;
  6694. } else {
  6695. tmp_rh->connect_handler = connect_handler;
  6696. tmp_rh->ready_handler = ready_handler;
  6697. tmp_rh->data_handler = data_handler;
  6698. tmp_rh->close_handler = close_handler;
  6699. }
  6700. tmp_rh->cbdata = cbdata;
  6701. } else {
  6702. /* remove existing handler */
  6703. *lastref = tmp_rh->next;
  6704. mg_free(tmp_rh->uri);
  6705. mg_free(tmp_rh);
  6706. }
  6707. mg_unlock_context(ctx);
  6708. return;
  6709. }
  6710. }
  6711. lastref = &(tmp_rh->next);
  6712. }
  6713. if (is_delete_request) {
  6714. /* no handler to set, this was a remove request to a non-existing
  6715. * handler */
  6716. mg_unlock_context(ctx);
  6717. return;
  6718. }
  6719. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  6720. sizeof(struct mg_request_handler_info), 1);
  6721. if (tmp_rh == NULL) {
  6722. mg_unlock_context(ctx);
  6723. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6724. return;
  6725. }
  6726. tmp_rh->uri = mg_strdup(uri);
  6727. if (!tmp_rh->uri) {
  6728. mg_unlock_context(ctx);
  6729. mg_free(tmp_rh);
  6730. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6731. return;
  6732. }
  6733. tmp_rh->uri_len = urilen;
  6734. if (!is_websocket_handler) {
  6735. tmp_rh->handler = handler;
  6736. } else {
  6737. tmp_rh->connect_handler = connect_handler;
  6738. tmp_rh->ready_handler = ready_handler;
  6739. tmp_rh->data_handler = data_handler;
  6740. tmp_rh->close_handler = close_handler;
  6741. }
  6742. tmp_rh->cbdata = cbdata;
  6743. tmp_rh->is_websocket_handler = is_websocket_handler;
  6744. tmp_rh->next = NULL;
  6745. *lastref = tmp_rh;
  6746. mg_unlock_context(ctx);
  6747. }
  6748. void mg_set_request_handler(struct mg_context *ctx,
  6749. const char *uri,
  6750. mg_request_handler handler,
  6751. void *cbdata)
  6752. {
  6753. mg_set_request_handler_type(
  6754. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  6755. }
  6756. void mg_set_websocket_handler(struct mg_context *ctx,
  6757. const char *uri,
  6758. mg_websocket_connect_handler connect_handler,
  6759. mg_websocket_ready_handler ready_handler,
  6760. mg_websocket_data_handler data_handler,
  6761. mg_websocket_close_handler close_handler,
  6762. void *cbdata)
  6763. {
  6764. int is_delete_request = (connect_handler == NULL) &&
  6765. (ready_handler == NULL) && (data_handler == NULL) &&
  6766. (close_handler == NULL);
  6767. mg_set_request_handler_type(ctx,
  6768. uri,
  6769. 1,
  6770. is_delete_request,
  6771. NULL,
  6772. connect_handler,
  6773. ready_handler,
  6774. data_handler,
  6775. close_handler,
  6776. cbdata);
  6777. }
  6778. static int get_request_handler(struct mg_connection *conn,
  6779. int is_websocket_request,
  6780. mg_request_handler *handler,
  6781. mg_websocket_connect_handler *connect_handler,
  6782. mg_websocket_ready_handler *ready_handler,
  6783. mg_websocket_data_handler *data_handler,
  6784. mg_websocket_close_handler *close_handler,
  6785. void **cbdata)
  6786. {
  6787. const struct mg_request_info *request_info = mg_get_request_info(conn);
  6788. if (request_info) {
  6789. const char *uri = request_info->uri;
  6790. size_t urilen = strlen(uri);
  6791. struct mg_request_handler_info *tmp_rh;
  6792. if (!conn || !conn->ctx)
  6793. return 0;
  6794. mg_lock_context(conn->ctx);
  6795. /* first try for an exact match */
  6796. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6797. tmp_rh = tmp_rh->next) {
  6798. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6799. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6800. if (is_websocket_request) {
  6801. *connect_handler = tmp_rh->connect_handler;
  6802. *ready_handler = tmp_rh->ready_handler;
  6803. *data_handler = tmp_rh->data_handler;
  6804. *close_handler = tmp_rh->close_handler;
  6805. } else {
  6806. *handler = tmp_rh->handler;
  6807. }
  6808. *cbdata = tmp_rh->cbdata;
  6809. mg_unlock_context(conn->ctx);
  6810. return 1;
  6811. }
  6812. }
  6813. }
  6814. /* next try for a partial match, we will accept uri/something */
  6815. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6816. tmp_rh = tmp_rh->next) {
  6817. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6818. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  6819. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  6820. if (is_websocket_request) {
  6821. *connect_handler = tmp_rh->connect_handler;
  6822. *ready_handler = tmp_rh->ready_handler;
  6823. *data_handler = tmp_rh->data_handler;
  6824. *close_handler = tmp_rh->close_handler;
  6825. } else {
  6826. *handler = tmp_rh->handler;
  6827. }
  6828. *cbdata = tmp_rh->cbdata;
  6829. mg_unlock_context(conn->ctx);
  6830. return 1;
  6831. }
  6832. }
  6833. }
  6834. /* finally try for pattern match */
  6835. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6836. tmp_rh = tmp_rh->next) {
  6837. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6838. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  6839. if (is_websocket_request) {
  6840. *connect_handler = tmp_rh->connect_handler;
  6841. *ready_handler = tmp_rh->ready_handler;
  6842. *data_handler = tmp_rh->data_handler;
  6843. *close_handler = tmp_rh->close_handler;
  6844. } else {
  6845. *handler = tmp_rh->handler;
  6846. }
  6847. *cbdata = tmp_rh->cbdata;
  6848. mg_unlock_context(conn->ctx);
  6849. return 1;
  6850. }
  6851. }
  6852. }
  6853. mg_unlock_context(conn->ctx);
  6854. }
  6855. return 0; /* none found */
  6856. }
  6857. #if defined(USE_WEBSOCKET)
  6858. static int
  6859. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  6860. void *cbdata)
  6861. {
  6862. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6863. if (pcallbacks->websocket_connect) {
  6864. return pcallbacks->websocket_connect(conn);
  6865. }
  6866. /* No handler set - assume "OK" */
  6867. return 0;
  6868. }
  6869. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  6870. void *cbdata)
  6871. {
  6872. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6873. if (pcallbacks->websocket_ready) {
  6874. pcallbacks->websocket_ready(conn);
  6875. }
  6876. }
  6877. static int deprecated_websocket_data_wrapper(
  6878. struct mg_connection *conn, int bits, char *data, size_t len, void *cbdata)
  6879. {
  6880. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6881. if (pcallbacks->websocket_data) {
  6882. return pcallbacks->websocket_data(conn, bits, data, len);
  6883. }
  6884. /* No handler set - assume "OK" */
  6885. return 1;
  6886. }
  6887. #endif
  6888. /* This is the heart of the Civetweb's logic.
  6889. * This function is called when the request is read, parsed and validated,
  6890. * and Civetweb must decide what action to take: serve a file, or
  6891. * a directory, or call embedded function, etcetera. */
  6892. static void handle_request(struct mg_connection *conn)
  6893. {
  6894. if (conn) {
  6895. struct mg_request_info *ri = &conn->request_info;
  6896. char path[PATH_MAX];
  6897. int uri_len, ssl_index, is_script_resource, is_websocket_request,
  6898. is_put_or_delete_request, is_callback_resource;
  6899. int i;
  6900. struct file file = STRUCT_FILE_INITIALIZER;
  6901. time_t curtime = time(NULL);
  6902. mg_request_handler callback_handler = NULL;
  6903. mg_websocket_connect_handler ws_connect_handler = NULL;
  6904. mg_websocket_ready_handler ws_ready_handler = NULL;
  6905. mg_websocket_data_handler ws_data_handler = NULL;
  6906. mg_websocket_close_handler ws_close_handler = NULL;
  6907. void *callback_data = NULL;
  6908. #if !defined(NO_FILES)
  6909. char date[64];
  6910. #endif
  6911. path[0] = 0;
  6912. if (!ri)
  6913. return;
  6914. /* 1. get the request url */
  6915. /* 1.1. split into url and query string */
  6916. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  6917. *((char *)conn->request_info.query_string++) = '\0';
  6918. }
  6919. uri_len = (int)strlen(ri->uri);
  6920. /* 1.2. decode url (if config says so) */
  6921. if (should_decode_url(conn)) {
  6922. mg_url_decode(ri->uri, uri_len, (char *)ri->uri, uri_len + 1, 0);
  6923. }
  6924. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  6925. * possible */
  6926. remove_double_dots_and_double_slashes((char *)ri->uri);
  6927. /* step 1. completed, the url is known now */
  6928. DEBUG_TRACE("URL: %s", ri->uri);
  6929. /* 2. do a https redirect, if required */
  6930. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  6931. ssl_index = get_first_ssl_listener_index(conn->ctx);
  6932. if (ssl_index >= 0) {
  6933. redirect_to_https_port(conn, ssl_index);
  6934. } else {
  6935. /* A http to https forward port has been specified,
  6936. * but no https port to forward to. */
  6937. send_http_error(conn,
  6938. 503,
  6939. "%s",
  6940. "Error: SSL forward not configured properly");
  6941. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  6942. }
  6943. return;
  6944. }
  6945. /* 3. if this ip has limited speed, set it for this connection */
  6946. conn->throttle = set_throttle(
  6947. conn->ctx->config[THROTTLE], get_remote_ip(conn), ri->uri);
  6948. /* 4. call a "handle everything" callback, if registered */
  6949. if (conn->ctx->callbacks.begin_request != NULL) {
  6950. /* Note that since V1.7 the "begin_request" function is called
  6951. * before an authorization check. If an authorization check is
  6952. * required, use a request_handler instead. */
  6953. i = conn->ctx->callbacks.begin_request(conn);
  6954. switch (i) {
  6955. case 1:
  6956. /* callback already processed the request */
  6957. return;
  6958. case 0:
  6959. /* civetweb should process the request */
  6960. break;
  6961. default:
  6962. /* unspecified - may change with the next version */
  6963. return;
  6964. }
  6965. }
  6966. /* request not yet handled by a handler or redirect, so the request
  6967. * is processed here */
  6968. /* 5. interpret the url to find out how the request must be handled */
  6969. /* 5.1. first test, if the request targets the regular http(s)://
  6970. * protocol namespace or the websocket ws(s):// protocol namespace. */
  6971. is_websocket_request = is_websocket_protocol(conn);
  6972. /* 5.2. check if the request will be handled by a callback */
  6973. if (get_request_handler(conn,
  6974. is_websocket_request,
  6975. &callback_handler,
  6976. &ws_connect_handler,
  6977. &ws_ready_handler,
  6978. &ws_data_handler,
  6979. &ws_close_handler,
  6980. &callback_data)) {
  6981. /* 5.2.1. A callback will handle this request. All requests handled
  6982. * by a callback have to be considered as requests to a script
  6983. * resource. */
  6984. is_callback_resource = 1;
  6985. is_script_resource = 1;
  6986. is_put_or_delete_request = is_put_or_delete_method(conn);
  6987. } else {
  6988. no_callback_resource:
  6989. /* 5.2.2. No callback is responsible for this request. The URI
  6990. * addresses a file based resource (static content or Lua/cgi
  6991. * scripts in the file system). */
  6992. is_callback_resource = 0;
  6993. interpret_uri(conn,
  6994. path,
  6995. sizeof(path),
  6996. &file,
  6997. &is_script_resource,
  6998. &is_websocket_request,
  6999. &is_put_or_delete_request);
  7000. }
  7001. /* 6. authorization check */
  7002. if (is_put_or_delete_request && !is_script_resource &&
  7003. !is_callback_resource) {
  7004. /* 6.1. this request is a PUT/DELETE to a real file */
  7005. /* 6.1.1. thus, the server must have real files */
  7006. #if defined(NO_FILES)
  7007. if (1) {
  7008. #else
  7009. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7010. #endif
  7011. /* This server does not have any real files, thus the
  7012. * PUT/DELETE methods are not valid. */
  7013. send_http_error(conn,
  7014. 405,
  7015. "%s method not allowed",
  7016. conn->request_info.request_method);
  7017. return;
  7018. }
  7019. /* 6.1.2. Check if put authorization for static files is available.
  7020. */
  7021. if (!is_authorized_for_put(conn)) {
  7022. send_authorization_request(conn);
  7023. return;
  7024. }
  7025. } else {
  7026. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  7027. * or it is a PUT or DELETE request to a resource that does not
  7028. * correspond to a file. Check authorization. */
  7029. if (!check_authorization(conn, path)) {
  7030. send_authorization_request(conn);
  7031. return;
  7032. }
  7033. }
  7034. /* request is authorized or does not need authorization */
  7035. /* 7. check if there are request handlers for this uri */
  7036. if (is_callback_resource) {
  7037. if (!is_websocket_request) {
  7038. if (callback_handler(conn, callback_data)) {
  7039. /* Do nothing, callback has served the request */
  7040. discard_unread_request_data(conn);
  7041. } else {
  7042. /* TODO (high): what if the handler did NOT handle the
  7043. * request */
  7044. /* The last version did handle this as a file request, but
  7045. * since a file request is not always a script resource,
  7046. * the authorization check might be different */
  7047. interpret_uri(conn,
  7048. path,
  7049. sizeof(path),
  7050. &file,
  7051. &is_script_resource,
  7052. &is_websocket_request,
  7053. &is_put_or_delete_request);
  7054. callback_handler = NULL;
  7055. /* TODO (very low): goto is deprecatedm but for the moment,
  7056. * a goto is
  7057. * simpler than some curious loop. */
  7058. /* The situation "callback does not handle the request"
  7059. * needs to be reconsidered anyway. */
  7060. goto no_callback_resource;
  7061. }
  7062. } else {
  7063. #if defined(USE_WEBSOCKET)
  7064. handle_websocket_request(conn,
  7065. path,
  7066. is_callback_resource,
  7067. ws_connect_handler,
  7068. ws_ready_handler,
  7069. ws_data_handler,
  7070. ws_close_handler,
  7071. callback_data);
  7072. #endif
  7073. }
  7074. return;
  7075. }
  7076. /* 8. handle websocket requests */
  7077. #if defined(USE_WEBSOCKET)
  7078. if (is_websocket_request) {
  7079. handle_websocket_request(
  7080. conn,
  7081. path,
  7082. !is_script_resource /* could be deprecated global callback */,
  7083. deprecated_websocket_connect_wrapper,
  7084. deprecated_websocket_ready_wrapper,
  7085. deprecated_websocket_data_wrapper,
  7086. NULL,
  7087. &conn->ctx->callbacks);
  7088. return;
  7089. } else
  7090. #endif
  7091. #if defined(NO_FILES)
  7092. /* 9a. In case the server uses only callbacks, this uri is unknown.
  7093. * Then, all request handling ends here. */
  7094. send_http_error(conn, 404, "%s", "Not Found");
  7095. #else
  7096. /* 9b. This request is either for a static file or resource handled
  7097. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  7098. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7099. send_http_error(conn, 404, "%s", "Not Found");
  7100. return;
  7101. }
  7102. /* 10. File is handled by a script. */
  7103. if (is_script_resource) {
  7104. handle_file_based_request(conn, path, &file);
  7105. return;
  7106. }
  7107. /* 11. Handle put/delete/mkcol requests */
  7108. if (is_put_or_delete_request) {
  7109. /* 11.1. PUT method */
  7110. if (!strcmp(ri->request_method, "PUT")) {
  7111. put_file(conn, path);
  7112. return;
  7113. }
  7114. /* 11.2. DELETE method */
  7115. if (!strcmp(ri->request_method, "DELETE")) {
  7116. delete_file(conn, path);
  7117. return;
  7118. }
  7119. /* 11.3. MKCOL method */
  7120. if (!strcmp(ri->request_method, "MKCOL")) {
  7121. mkcol(conn, path);
  7122. return;
  7123. }
  7124. /* 11.4. should never reach this point */
  7125. send_http_error(conn,
  7126. 405,
  7127. "%s method not allowed",
  7128. conn->request_info.request_method);
  7129. return;
  7130. }
  7131. /* 11. File does not exist, or it was configured that it should be
  7132. * hidden */
  7133. if (((file.membuf == NULL) && (file.modification_time == (time_t)0)) ||
  7134. (must_hide_file(conn, path))) {
  7135. send_http_error(conn, 404, "%s", "Not found");
  7136. return;
  7137. }
  7138. /* 12. Directories uris should end with a slash */
  7139. if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  7140. gmt_time_string(date, sizeof(date), &curtime);
  7141. mg_printf(conn,
  7142. "HTTP/1.1 301 Moved Permanently\r\n"
  7143. "Location: %s/\r\n"
  7144. "Date: %s\r\n"
  7145. "Content-Length: 0\r\n"
  7146. "Connection: %s\r\n\r\n",
  7147. ri->uri,
  7148. date,
  7149. suggest_connection_header(conn));
  7150. return;
  7151. }
  7152. /* 13. Handle other methods than GET/HEAD */
  7153. /* 13.1. Handle PROPFIND */
  7154. if (!strcmp(ri->request_method, "PROPFIND")) {
  7155. handle_propfind(conn, path, &file);
  7156. return;
  7157. }
  7158. /* 13.2. Handle OPTIONS for files */
  7159. if (!strcmp(ri->request_method, "OPTIONS")) {
  7160. /* This standard handler is only used for real files.
  7161. * Scripts should support the OPTIONS method themselves, to allow a
  7162. * maximum flexibility.
  7163. * Lua and CGI scripts may fully support CORS this way (including
  7164. * preflights). */
  7165. send_options(conn);
  7166. return;
  7167. }
  7168. /* 13.3. everything but GET and HEAD (e.g. POST) */
  7169. if (0 != strcmp(ri->request_method, "GET") &&
  7170. 0 != strcmp(ri->request_method, "HEAD")) {
  7171. send_http_error(conn,
  7172. 405,
  7173. "%s method not allowed",
  7174. conn->request_info.request_method);
  7175. return;
  7176. }
  7177. /* 14. directories */
  7178. if (file.is_directory) {
  7179. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  7180. /* 14.1. use a substitute file */
  7181. /* TODO (high): substitute index may be a script resource.
  7182. * define what should be possible in this case. */
  7183. } else {
  7184. /* 14.2. no substitute file */
  7185. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7186. "yes")) {
  7187. handle_directory_request(conn, path);
  7188. } else {
  7189. send_http_error(
  7190. conn, 403, "%s", "Error: Directory listing denied");
  7191. }
  7192. return;
  7193. }
  7194. }
  7195. handle_file_based_request(conn, path, &file);
  7196. #endif /* !defined(NO_FILES) */
  7197. #if 0
  7198. /* Perform redirect and auth checks before calling begin_request()
  7199. * handler.
  7200. * Otherwise, begin_request() would need to perform auth checks and
  7201. * redirects. */
  7202. #endif
  7203. }
  7204. return;
  7205. }
  7206. static void handle_file_based_request(struct mg_connection *conn,
  7207. const char *path,
  7208. struct file *file)
  7209. {
  7210. if (!conn || !conn->ctx)
  7211. return;
  7212. if (0) {
  7213. #ifdef USE_LUA
  7214. } else if (match_prefix(
  7215. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  7216. strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  7217. path) > 0) {
  7218. /* Lua server page: an SSI like page containing mostly plain html code
  7219. * plus some tags with server generated contents. */
  7220. handle_lsp_request(conn, path, file, NULL);
  7221. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  7222. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  7223. path) > 0) {
  7224. /* Lua in-server module script: a CGI like script used to generate the
  7225. * entire reply. */
  7226. mg_exec_lua_script(conn, path, NULL);
  7227. #endif
  7228. #if !defined(NO_CGI)
  7229. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  7230. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  7231. path) > 0) {
  7232. /* CGI scripts may support all HTTP methods */
  7233. handle_cgi_request(conn, path);
  7234. #endif /* !NO_CGI */
  7235. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7236. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7237. path) > 0) {
  7238. handle_ssi_file_request(conn, path, file);
  7239. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  7240. /* Send 304 "Not Modified" - this must not send any body data */
  7241. send_http_error(conn, 304, "%s", "");
  7242. } else {
  7243. handle_static_file_request(conn, path, file);
  7244. }
  7245. }
  7246. static void close_all_listening_sockets(struct mg_context *ctx)
  7247. {
  7248. unsigned int i;
  7249. if (!ctx)
  7250. return;
  7251. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7252. closesocket(ctx->listening_sockets[i].sock);
  7253. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  7254. }
  7255. mg_free(ctx->listening_sockets);
  7256. ctx->listening_sockets = NULL;
  7257. mg_free(ctx->listening_ports);
  7258. ctx->listening_ports = NULL;
  7259. }
  7260. /* Valid listening port specification is: [ip_address:]port[s]
  7261. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  7262. * Examples for IPv6: [::]:80, [::1]:80,
  7263. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  7264. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  7265. static int parse_port_string(const struct vec *vec, struct socket *so)
  7266. {
  7267. unsigned int a, b, c, d, port;
  7268. int ch, len;
  7269. #if defined(USE_IPV6)
  7270. char buf[100] = {0};
  7271. #endif
  7272. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  7273. * Also, all-zeroes in the socket address means binding to all addresses
  7274. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  7275. memset(so, 0, sizeof(*so));
  7276. so->lsa.sin.sin_family = AF_INET;
  7277. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  7278. 5) {
  7279. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  7280. so->lsa.sin.sin_addr.s_addr =
  7281. htonl((a << 24) | (b << 16) | (c << 8) | d);
  7282. so->lsa.sin.sin_port = htons((uint16_t)port);
  7283. #if defined(USE_IPV6)
  7284. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  7285. mg_inet_pton(
  7286. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  7287. /* IPv6 address, examples: see above */
  7288. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  7289. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  7290. #endif
  7291. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  7292. /* If only port is specified, bind to IPv4, INADDR_ANY */
  7293. so->lsa.sin.sin_port = htons((uint16_t)port);
  7294. } else {
  7295. /* Parsing failure. Make port invalid. */
  7296. port = 0;
  7297. len = 0;
  7298. }
  7299. /* sscanf and the option splitting code ensure the following condition */
  7300. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  7301. return 0;
  7302. }
  7303. ch = vec->ptr[len]; /* Next character after the port number */
  7304. so->is_ssl = (ch == 's');
  7305. so->ssl_redir = (ch == 'r');
  7306. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  7307. return is_valid_port(port) &&
  7308. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  7309. }
  7310. static int set_ports_option(struct mg_context *ctx)
  7311. {
  7312. if (ctx) {
  7313. const char *list = ctx->config[LISTENING_PORTS];
  7314. int on = 1, success = 1;
  7315. #if defined(USE_IPV6)
  7316. int off = 0;
  7317. #endif
  7318. struct vec vec;
  7319. struct socket so, *ptr;
  7320. in_port_t *portPtr;
  7321. union usa usa;
  7322. socklen_t len;
  7323. memset(&so, 0, sizeof(so));
  7324. memset(&usa, 0, sizeof(usa));
  7325. len = sizeof(usa);
  7326. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  7327. if (!parse_port_string(&vec, &so)) {
  7328. mg_cry(fc(ctx),
  7329. "%s: %.*s: invalid port spec. Expecting list of: %s",
  7330. __func__,
  7331. (int)vec.len,
  7332. vec.ptr,
  7333. "[IP_ADDRESS:]PORT[s|r]");
  7334. success = 0;
  7335. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  7336. mg_cry(
  7337. fc(ctx),
  7338. "Cannot add SSL socket, is -ssl_certificate option set?");
  7339. success = 0;
  7340. } else if ((so.sock =
  7341. socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  7342. INVALID_SOCKET ||
  7343. #ifdef _WIN32
  7344. /* Windows SO_REUSEADDR lets many procs binds to a
  7345. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  7346. * if someone already has the socket -- DTL */
  7347. setsockopt(so.sock,
  7348. SOL_SOCKET,
  7349. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  7350. * Windows might need a few seconds before
  7351. * the same port can be used again in the
  7352. * same process, so a short Sleep may be
  7353. * required between mg_stop and mg_start.
  7354. */
  7355. SO_EXCLUSIVEADDRUSE,
  7356. (SOCK_OPT_TYPE)&on,
  7357. sizeof(on)) != 0 ||
  7358. #else
  7359. setsockopt(so.sock,
  7360. SOL_SOCKET,
  7361. SO_REUSEADDR,
  7362. (SOCK_OPT_TYPE)&on,
  7363. sizeof(on)) != 0 ||
  7364. #endif
  7365. #if defined(USE_IPV6)
  7366. (so.lsa.sa.sa_family == AF_INET6 &&
  7367. setsockopt(so.sock,
  7368. IPPROTO_IPV6,
  7369. IPV6_V6ONLY,
  7370. (void *)&off,
  7371. sizeof(off)) != 0) ||
  7372. #endif
  7373. bind(so.sock,
  7374. &so.lsa.sa,
  7375. so.lsa.sa.sa_family == AF_INET
  7376. ? sizeof(so.lsa.sin)
  7377. : sizeof(so.lsa.sa)) != 0 ||
  7378. listen(so.sock, SOMAXCONN) != 0 ||
  7379. getsockname(so.sock, &(usa.sa), &len) != 0) {
  7380. /* TODO(mid): rewrite this IF above */
  7381. mg_cry(fc(ctx),
  7382. "%s: cannot bind to %.*s: %d (%s)",
  7383. __func__,
  7384. (int)vec.len,
  7385. vec.ptr,
  7386. (int)ERRNO,
  7387. strerror(errno));
  7388. if (so.sock != INVALID_SOCKET) {
  7389. closesocket(so.sock);
  7390. so.sock = INVALID_SOCKET;
  7391. }
  7392. success = 0;
  7393. } else if ((ptr = (struct socket *)mg_realloc(
  7394. ctx->listening_sockets,
  7395. (ctx->num_listening_sockets + 1) *
  7396. sizeof(ctx->listening_sockets[0]))) == NULL) {
  7397. closesocket(so.sock);
  7398. so.sock = INVALID_SOCKET;
  7399. success = 0;
  7400. } else if ((portPtr = (in_port_t *)mg_realloc(
  7401. ctx->listening_ports,
  7402. (ctx->num_listening_sockets + 1) *
  7403. sizeof(ctx->listening_ports[0]))) == NULL) {
  7404. closesocket(so.sock);
  7405. so.sock = INVALID_SOCKET;
  7406. mg_free(ptr);
  7407. success = 0;
  7408. } else {
  7409. set_close_on_exec(so.sock, fc(ctx));
  7410. ctx->listening_sockets = ptr;
  7411. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  7412. ctx->listening_ports = portPtr;
  7413. ctx->listening_ports[ctx->num_listening_sockets] =
  7414. ntohs(usa.sin.sin_port);
  7415. ctx->num_listening_sockets++;
  7416. }
  7417. }
  7418. if (!success) {
  7419. close_all_listening_sockets(ctx);
  7420. }
  7421. return success;
  7422. }
  7423. return 0;
  7424. }
  7425. static const char *header_val(const struct mg_connection *conn,
  7426. const char *header)
  7427. {
  7428. const char *header_value;
  7429. if ((header_value = mg_get_header(conn, header)) == NULL) {
  7430. return "-";
  7431. } else {
  7432. return header_value;
  7433. }
  7434. }
  7435. static void log_access(const struct mg_connection *conn)
  7436. {
  7437. const struct mg_request_info *ri;
  7438. FILE *fp;
  7439. char date[64], src_addr[IP_ADDR_STR_LEN];
  7440. struct tm *tm;
  7441. const char *referer;
  7442. const char *user_agent;
  7443. char buf[4096];
  7444. if (!conn || !conn->ctx)
  7445. return;
  7446. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  7447. ? NULL
  7448. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  7449. if (fp == NULL && conn->ctx->callbacks.log_message == NULL)
  7450. return;
  7451. tm = localtime(&conn->conn_birth_time);
  7452. if (tm != NULL) {
  7453. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  7454. } else {
  7455. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  7456. date[sizeof(date) - 1] = '\0';
  7457. }
  7458. ri = &conn->request_info;
  7459. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7460. referer = header_val(conn, "Referer");
  7461. user_agent = header_val(conn, "User-Agent");
  7462. snprintf(buf,
  7463. sizeof(buf),
  7464. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  7465. src_addr,
  7466. ri->remote_user == NULL ? "-" : ri->remote_user,
  7467. date,
  7468. ri->request_method ? ri->request_method : "-",
  7469. ri->uri ? ri->uri : "-",
  7470. ri->http_version,
  7471. conn->status_code,
  7472. conn->num_bytes_sent,
  7473. referer,
  7474. user_agent);
  7475. if (conn->ctx->callbacks.log_access) {
  7476. conn->ctx->callbacks.log_access(conn, buf);
  7477. }
  7478. if (fp) {
  7479. flockfile(fp);
  7480. fprintf(fp, "%s", buf);
  7481. fputc('\n', fp);
  7482. fflush(fp);
  7483. funlockfile(fp);
  7484. fclose(fp);
  7485. }
  7486. }
  7487. /* Verify given socket address against the ACL.
  7488. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  7489. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  7490. {
  7491. int allowed, flag;
  7492. uint32_t net, mask;
  7493. struct vec vec;
  7494. if (ctx) {
  7495. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  7496. /* If any ACL is set, deny by default */
  7497. allowed = list == NULL ? '+' : '-';
  7498. while ((list = next_option(list, &vec, NULL)) != NULL) {
  7499. flag = vec.ptr[0];
  7500. if ((flag != '+' && flag != '-') ||
  7501. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  7502. mg_cry(
  7503. fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  7504. return -1;
  7505. }
  7506. if (net == (remote_ip & mask)) {
  7507. allowed = flag;
  7508. }
  7509. }
  7510. return allowed == '+';
  7511. }
  7512. return -1;
  7513. }
  7514. #if !defined(_WIN32)
  7515. static int set_uid_option(struct mg_context *ctx)
  7516. {
  7517. struct passwd *pw;
  7518. if (ctx) {
  7519. const char *uid = ctx->config[RUN_AS_USER];
  7520. int success = 0;
  7521. if (uid == NULL) {
  7522. success = 1;
  7523. } else {
  7524. if ((pw = getpwnam(uid)) == NULL) {
  7525. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  7526. } else if (setgid(pw->pw_gid) == -1) {
  7527. mg_cry(fc(ctx),
  7528. "%s: setgid(%s): %s",
  7529. __func__,
  7530. uid,
  7531. strerror(errno));
  7532. } else if (setgroups(0, NULL)) {
  7533. mg_cry(
  7534. fc(ctx), "%s: setgroups(): %s", __func__, strerror(errno));
  7535. } else if (setuid(pw->pw_uid) == -1) {
  7536. mg_cry(fc(ctx),
  7537. "%s: setuid(%s): %s",
  7538. __func__,
  7539. uid,
  7540. strerror(errno));
  7541. } else {
  7542. success = 1;
  7543. }
  7544. }
  7545. return success;
  7546. }
  7547. return 0;
  7548. }
  7549. #endif /* !_WIN32 */
  7550. #if !defined(NO_SSL)
  7551. static pthread_mutex_t *ssl_mutexes;
  7552. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  7553. {
  7554. if (!conn)
  7555. return 0;
  7556. return (conn->ssl = SSL_new(s)) != NULL &&
  7557. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  7558. func(conn->ssl) == 1;
  7559. }
  7560. /* Return OpenSSL error message (from CRYPTO lib) */
  7561. static const char *ssl_error(void)
  7562. {
  7563. unsigned long err;
  7564. err = ERR_get_error();
  7565. return err == 0 ? "" : ERR_error_string(err, NULL);
  7566. }
  7567. static void
  7568. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  7569. {
  7570. (void)line;
  7571. (void)file;
  7572. if (mode & 1) {
  7573. /* 1 is CRYPTO_LOCK */
  7574. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  7575. } else {
  7576. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  7577. }
  7578. }
  7579. static unsigned long ssl_id_callback(void)
  7580. {
  7581. return (unsigned long)pthread_self();
  7582. }
  7583. #if !defined(NO_SSL_DL)
  7584. static void *
  7585. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  7586. {
  7587. union {
  7588. void *p;
  7589. void (*fp)(void);
  7590. } u;
  7591. void *dll_handle;
  7592. struct ssl_func *fp;
  7593. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  7594. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  7595. return NULL;
  7596. }
  7597. for (fp = sw; fp->name != NULL; fp++) {
  7598. #ifdef _WIN32
  7599. /* GetProcAddress() returns pointer to function */
  7600. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  7601. #else
  7602. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  7603. * pointers to function pointers. We need to use a union to make a
  7604. * cast. */
  7605. u.p = dlsym(dll_handle, fp->name);
  7606. #endif /* _WIN32 */
  7607. if (u.fp == NULL) {
  7608. mg_cry(fc(ctx),
  7609. "%s: %s: cannot find %s",
  7610. __func__,
  7611. dll_name,
  7612. fp->name);
  7613. dlclose(dll_handle);
  7614. return NULL;
  7615. } else {
  7616. fp->ptr = u.fp;
  7617. }
  7618. }
  7619. return dll_handle;
  7620. }
  7621. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  7622. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  7623. #endif /* NO_SSL_DL */
  7624. #if defined(SSL_ALREADY_INITIALIZED)
  7625. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  7626. #else
  7627. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  7628. #endif
  7629. static int initialize_ssl(struct mg_context *ctx)
  7630. {
  7631. int i;
  7632. size_t size;
  7633. #if !defined(NO_SSL_DL)
  7634. if (!cryptolib_dll_handle) {
  7635. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  7636. if (!cryptolib_dll_handle) {
  7637. return 0;
  7638. }
  7639. }
  7640. #endif /* NO_SSL_DL */
  7641. if (mg_atomic_inc(&cryptolib_users) > 1)
  7642. return 1;
  7643. /* Initialize locking callbacks, needed for thread safety.
  7644. * http://www.openssl.org/support/faq.html#PROG1
  7645. */
  7646. i = CRYPTO_num_locks();
  7647. if (i < 0)
  7648. i = 0;
  7649. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  7650. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  7651. mg_cry(
  7652. fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  7653. return 0;
  7654. }
  7655. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7656. pthread_mutex_init(&ssl_mutexes[i], NULL);
  7657. }
  7658. CRYPTO_set_locking_callback(&ssl_locking_callback);
  7659. CRYPTO_set_id_callback(&ssl_id_callback);
  7660. return 1;
  7661. }
  7662. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  7663. static int set_ssl_option(struct mg_context *ctx)
  7664. {
  7665. const char *pem;
  7666. int callback_ret;
  7667. /* If PEM file is not specified and the init_ssl callback
  7668. * is not specified, skip SSL initialization. */
  7669. if (!ctx)
  7670. return 0;
  7671. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  7672. ctx->callbacks.init_ssl == NULL) {
  7673. return 1;
  7674. }
  7675. if (!initialize_ssl(ctx)) {
  7676. return 0;
  7677. }
  7678. #if !defined(NO_SSL_DL)
  7679. if (!ssllib_dll_handle) {
  7680. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  7681. if (!ssllib_dll_handle) {
  7682. return 0;
  7683. }
  7684. }
  7685. #endif /* NO_SSL_DL */
  7686. /* Initialize SSL library */
  7687. SSL_library_init();
  7688. SSL_load_error_strings();
  7689. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  7690. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  7691. return 0;
  7692. }
  7693. /* If a callback has been specified, call it. */
  7694. callback_ret =
  7695. (ctx->callbacks.init_ssl == NULL)
  7696. ? 0
  7697. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  7698. /* If callback returns 0, civetweb sets up the SSL certificate.
  7699. * If it returns 1, civetweb assumes the calback already did this.
  7700. * If it returns -1, initializing ssl fails. */
  7701. if (callback_ret < 0) {
  7702. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  7703. return 0;
  7704. }
  7705. if (callback_ret == 0) {
  7706. if (pem != NULL) {
  7707. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  7708. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  7709. mg_cry(fc(ctx),
  7710. "%s: cannot open %s: %s",
  7711. __func__,
  7712. pem,
  7713. ssl_error());
  7714. return 0;
  7715. }
  7716. }
  7717. }
  7718. if (pem != NULL) {
  7719. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  7720. }
  7721. return 1;
  7722. }
  7723. static void uninitialize_ssl(struct mg_context *ctx)
  7724. {
  7725. int i;
  7726. (void)ctx;
  7727. if (mg_atomic_dec(&cryptolib_users) == 0) {
  7728. CRYPTO_set_locking_callback(NULL);
  7729. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7730. pthread_mutex_destroy(&ssl_mutexes[i]);
  7731. }
  7732. CRYPTO_set_locking_callback(NULL);
  7733. CRYPTO_set_id_callback(NULL);
  7734. }
  7735. }
  7736. #endif /* !NO_SSL */
  7737. static int set_gpass_option(struct mg_context *ctx)
  7738. {
  7739. if (ctx) {
  7740. struct file file = STRUCT_FILE_INITIALIZER;
  7741. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  7742. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  7743. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  7744. return 0;
  7745. }
  7746. return 1;
  7747. }
  7748. return 0;
  7749. }
  7750. static int set_acl_option(struct mg_context *ctx)
  7751. {
  7752. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  7753. }
  7754. static void reset_per_request_attributes(struct mg_connection *conn)
  7755. {
  7756. if (!conn)
  7757. return;
  7758. conn->path_info = NULL;
  7759. conn->num_bytes_sent = conn->consumed_content = 0;
  7760. conn->status_code = -1;
  7761. conn->is_chunked = 0;
  7762. conn->must_close = conn->request_len = conn->throttle = 0;
  7763. conn->request_info.content_length = -1;
  7764. conn->request_info.remote_user = NULL;
  7765. conn->request_info.request_method = NULL;
  7766. conn->request_info.uri = NULL;
  7767. conn->request_info.http_version = NULL;
  7768. conn->request_info.num_headers = 0;
  7769. conn->data_len = 0;
  7770. conn->chunk_remainder = 0;
  7771. }
  7772. static int set_sock_timeout(SOCKET sock, int milliseconds)
  7773. {
  7774. int r1, r2;
  7775. #ifdef _WIN32
  7776. DWORD t = (DWORD)milliseconds;
  7777. #else
  7778. #if defined(TCP_USER_TIMEOUT)
  7779. unsigned int uto = (unsigned int)milliseconds;
  7780. #endif
  7781. struct timeval t;
  7782. t.tv_sec = milliseconds / 1000;
  7783. t.tv_usec = (milliseconds * 1000) % 1000000;
  7784. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  7785. * max. time waiting for the acknowledged of TCP data before the connection
  7786. * will be forcefully closed and ETIMEDOUT is returned to the application.
  7787. * If this option is not set, the default timeout of 20-30 minutes is used.
  7788. */
  7789. /* #define TCP_USER_TIMEOUT (18) */
  7790. #if defined(TCP_USER_TIMEOUT)
  7791. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  7792. #endif
  7793. #endif
  7794. r1 =
  7795. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  7796. r2 =
  7797. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  7798. return r1 || r2;
  7799. }
  7800. static void close_socket_gracefully(struct mg_connection *conn)
  7801. {
  7802. #if defined(_WIN32)
  7803. char buf[MG_BUF_LEN];
  7804. int n;
  7805. #endif
  7806. struct linger linger;
  7807. if (!conn) {
  7808. return;
  7809. }
  7810. /* Set linger option to avoid socket hanging out after close. This prevent
  7811. * ephemeral port exhaust problem under high QPS. */
  7812. linger.l_onoff = 1;
  7813. linger.l_linger = 1;
  7814. if (setsockopt(conn->client.sock,
  7815. SOL_SOCKET,
  7816. SO_LINGER,
  7817. (char *)&linger,
  7818. sizeof(linger)) != 0) {
  7819. mg_cry(conn,
  7820. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  7821. __func__,
  7822. strerror(ERRNO));
  7823. }
  7824. /* Send FIN to the client */
  7825. shutdown(conn->client.sock, SHUT_WR);
  7826. set_non_blocking_mode(conn->client.sock);
  7827. #if defined(_WIN32)
  7828. /* Read and discard pending incoming data. If we do not do that and close
  7829. * the socket, the data in the send buffer may be discarded. This
  7830. * behaviour is seen on Windows, when client keeps sending data
  7831. * when server decides to close the connection; then when client
  7832. * does recv() it gets no data back. */
  7833. do {
  7834. n = pull(
  7835. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  7836. } while (n > 0);
  7837. #endif
  7838. /* Now we know that our FIN is ACK-ed, safe to close */
  7839. closesocket(conn->client.sock);
  7840. conn->client.sock = INVALID_SOCKET;
  7841. }
  7842. static void close_connection(struct mg_connection *conn)
  7843. {
  7844. if (!conn || !conn->ctx)
  7845. return;
  7846. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  7847. if (conn->lua_websocket_state) {
  7848. lua_websocket_close(conn, conn->lua_websocket_state);
  7849. conn->lua_websocket_state = NULL;
  7850. }
  7851. #endif
  7852. /* call the connection_close callback if assigned */
  7853. if ((conn->ctx->callbacks.connection_close != NULL) &&
  7854. (conn->ctx->context_type == 1)) {
  7855. conn->ctx->callbacks.connection_close(conn);
  7856. }
  7857. mg_lock_connection(conn);
  7858. conn->must_close = 1;
  7859. #ifndef NO_SSL
  7860. if (conn->ssl != NULL) {
  7861. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  7862. SSL_shutdown(conn->ssl);
  7863. SSL_free(conn->ssl);
  7864. conn->ssl = NULL;
  7865. }
  7866. #endif
  7867. if (conn->client.sock != INVALID_SOCKET) {
  7868. close_socket_gracefully(conn);
  7869. conn->client.sock = INVALID_SOCKET;
  7870. }
  7871. mg_unlock_connection(conn);
  7872. }
  7873. void mg_close_connection(struct mg_connection *conn)
  7874. {
  7875. struct mg_context *client_ctx = NULL;
  7876. unsigned int i;
  7877. if (conn == NULL)
  7878. return;
  7879. if (conn->ctx->context_type == 2) {
  7880. client_ctx = conn->ctx;
  7881. /* client context: loops must end */
  7882. conn->ctx->stop_flag = 1;
  7883. }
  7884. #ifndef NO_SSL
  7885. if (conn->client_ssl_ctx != NULL) {
  7886. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  7887. }
  7888. #endif
  7889. close_connection(conn);
  7890. if (client_ctx != NULL) {
  7891. /* join worker thread and free context */
  7892. for (i = 0; i < client_ctx->workerthreadcount; i++) {
  7893. mg_join_thread(client_ctx->workerthreadids[i]);
  7894. }
  7895. mg_free(client_ctx->workerthreadids);
  7896. mg_free(client_ctx);
  7897. }
  7898. (void)pthread_mutex_destroy(&conn->mutex);
  7899. mg_free(conn);
  7900. }
  7901. struct mg_connection *mg_connect_client(
  7902. const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len)
  7903. {
  7904. static struct mg_context fake_ctx;
  7905. struct mg_connection *conn = NULL;
  7906. SOCKET sock;
  7907. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf, ebuf_len)) ==
  7908. INVALID_SOCKET) {
  7909. } else if ((conn = (struct mg_connection *)mg_calloc(
  7910. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  7911. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  7912. closesocket(sock);
  7913. #ifndef NO_SSL
  7914. } else if (use_ssl &&
  7915. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  7916. NULL) {
  7917. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  7918. closesocket(sock);
  7919. mg_free(conn);
  7920. conn = NULL;
  7921. #endif /* NO_SSL */
  7922. } else {
  7923. socklen_t len = sizeof(struct sockaddr);
  7924. conn->buf_size = MAX_REQUEST_SIZE;
  7925. conn->buf = (char *)(conn + 1);
  7926. conn->ctx = &fake_ctx;
  7927. conn->client.sock = sock;
  7928. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  7929. mg_cry(conn,
  7930. "%s: getsockname() failed: %s",
  7931. __func__,
  7932. strerror(ERRNO));
  7933. }
  7934. conn->client.is_ssl = use_ssl ? 1 : 0;
  7935. (void)pthread_mutex_init(&conn->mutex, NULL);
  7936. #ifndef NO_SSL
  7937. if (use_ssl) {
  7938. /* SSL_CTX_set_verify call is needed to switch off server
  7939. * certificate checking, which is off by default in OpenSSL and on
  7940. * in yaSSL. */
  7941. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  7942. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  7943. }
  7944. #endif
  7945. }
  7946. return conn;
  7947. }
  7948. static int is_valid_uri(const char *uri)
  7949. {
  7950. /* Conform to
  7951. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  7952. * URI can be an asterisk (*) or should start with slash. */
  7953. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  7954. }
  7955. static int
  7956. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  7957. {
  7958. const char *cl;
  7959. if (ebuf_len > 0) {
  7960. ebuf[0] = '\0';
  7961. }
  7962. *err = 0;
  7963. reset_per_request_attributes(conn);
  7964. if (!conn) {
  7965. snprintf(ebuf, ebuf_len, "%s", "Internal error");
  7966. *err = 500;
  7967. return 0;
  7968. }
  7969. /* Set the time the request was received. This value should be used for
  7970. * timeouts. */
  7971. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  7972. conn->request_len =
  7973. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  7974. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  7975. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  7976. snprintf(ebuf, ebuf_len, "%s", "Invalid request size");
  7977. *err = 500;
  7978. return 0;
  7979. }
  7980. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  7981. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  7982. *err = 413;
  7983. return 0;
  7984. } else if (conn->request_len <= 0) {
  7985. if (conn->data_len > 0) {
  7986. snprintf(ebuf, ebuf_len, "%s", "Client sent malformed request");
  7987. *err = 400;
  7988. } else {
  7989. /* Server did not send anything -> just close the connection */
  7990. conn->must_close = 1;
  7991. snprintf(ebuf, ebuf_len, "%s", "Client did not send a request");
  7992. *err = 0;
  7993. }
  7994. return 0;
  7995. } else if (parse_http_message(
  7996. conn->buf, conn->buf_size, &conn->request_info) <= 0) {
  7997. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  7998. *err = 400;
  7999. return 0;
  8000. } else {
  8001. /* Message is a valid request or response */
  8002. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  8003. /* Request/response has content length set */
  8004. char *endptr = NULL;
  8005. conn->content_len = strtoll(cl, &endptr, 10);
  8006. if (endptr == cl) {
  8007. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  8008. *err = 411;
  8009. return 0;
  8010. }
  8011. /* Publish the content length back to the request info. */
  8012. conn->request_info.content_length = conn->content_len;
  8013. } else if ((cl = get_header(&conn->request_info,
  8014. "Transfer-encoding")) != NULL &&
  8015. strcmp(cl, "chunked") == 0) {
  8016. conn->is_chunked = 1;
  8017. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  8018. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  8019. /* POST or PUT request without content length set */
  8020. conn->content_len = -1;
  8021. } else if (!mg_strncasecmp(
  8022. conn->request_info.request_method, "HTTP/", 5)) {
  8023. /* Response without content length set */
  8024. conn->content_len = -1;
  8025. } else {
  8026. /* Other request */
  8027. conn->content_len = 0;
  8028. }
  8029. }
  8030. return 1;
  8031. }
  8032. int mg_get_response(struct mg_connection *conn,
  8033. char *ebuf,
  8034. size_t ebuf_len,
  8035. int timeout)
  8036. {
  8037. if (conn) {
  8038. /* Implementation of API function for HTTP clients */
  8039. int err, ret;
  8040. struct mg_context *octx = conn->ctx;
  8041. struct mg_context rctx = *(conn->ctx);
  8042. char txt[32];
  8043. if (timeout >= 0) {
  8044. snprintf(txt, sizeof(txt), "%i", timeout);
  8045. rctx.config[REQUEST_TIMEOUT] = txt;
  8046. set_sock_timeout(conn->client.sock, timeout);
  8047. } else {
  8048. rctx.config[REQUEST_TIMEOUT] = NULL;
  8049. }
  8050. conn->ctx = &rctx;
  8051. ret = getreq(conn, ebuf, ebuf_len, &err);
  8052. conn->ctx = octx;
  8053. /* TODO (mid): Define proper return values - maybe return length?
  8054. * For the first test use <0 for error and >0 for OK */
  8055. return (ret == 0) ? -1 : +1;
  8056. }
  8057. return -1;
  8058. }
  8059. struct mg_connection *mg_download(const char *host,
  8060. int port,
  8061. int use_ssl,
  8062. char *ebuf,
  8063. size_t ebuf_len,
  8064. const char *fmt,
  8065. ...)
  8066. {
  8067. struct mg_connection *conn;
  8068. va_list ap;
  8069. int i;
  8070. int reqerr;
  8071. va_start(ap, fmt);
  8072. ebuf[0] = '\0';
  8073. /* open a connection */
  8074. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  8075. if (conn != NULL) {
  8076. i = mg_vprintf(conn, fmt, ap);
  8077. if (i <= 0) {
  8078. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  8079. } else {
  8080. getreq(conn, ebuf, ebuf_len, &reqerr);
  8081. }
  8082. }
  8083. /* if an error occured, close the connection */
  8084. if (ebuf[0] != '\0' && conn != NULL) {
  8085. mg_close_connection(conn);
  8086. conn = NULL;
  8087. }
  8088. va_end(ap);
  8089. return conn;
  8090. }
  8091. struct websocket_client_thread_data {
  8092. struct mg_connection *conn;
  8093. mg_websocket_data_handler data_handler;
  8094. mg_websocket_close_handler close_handler;
  8095. void *callback_data;
  8096. };
  8097. #if defined(USE_WEBSOCKET)
  8098. #ifdef _WIN32
  8099. static unsigned __stdcall websocket_client_thread(void *data)
  8100. #else
  8101. static void *websocket_client_thread(void *data)
  8102. #endif
  8103. {
  8104. struct websocket_client_thread_data *cdata =
  8105. (struct websocket_client_thread_data *)data;
  8106. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  8107. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  8108. if (cdata->close_handler != NULL) {
  8109. cdata->close_handler(cdata->conn, cdata->callback_data);
  8110. }
  8111. mg_free((void *)cdata);
  8112. #ifdef _WIN32
  8113. return 0;
  8114. #else
  8115. return NULL;
  8116. #endif
  8117. }
  8118. #endif
  8119. struct mg_connection *
  8120. mg_connect_websocket_client(const char *host,
  8121. int port,
  8122. int use_ssl,
  8123. char *error_buffer,
  8124. size_t error_buffer_size,
  8125. const char *path,
  8126. const char *origin,
  8127. mg_websocket_data_handler data_func,
  8128. mg_websocket_close_handler close_func,
  8129. void *user_data)
  8130. {
  8131. struct mg_connection *conn = NULL;
  8132. #if defined(USE_WEBSOCKET)
  8133. struct mg_context *newctx = NULL;
  8134. struct websocket_client_thread_data *thread_data;
  8135. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  8136. static const char *handshake_req;
  8137. if (origin != NULL) {
  8138. handshake_req = "GET %s HTTP/1.1\r\n"
  8139. "Host: %s\r\n"
  8140. "Upgrade: websocket\r\n"
  8141. "Connection: Upgrade\r\n"
  8142. "Sec-WebSocket-Key: %s\r\n"
  8143. "Sec-WebSocket-Version: 13\r\n"
  8144. "Origin: %s\r\n"
  8145. "\r\n";
  8146. } else {
  8147. handshake_req = "GET %s HTTP/1.1\r\n"
  8148. "Host: %s\r\n"
  8149. "Upgrade: websocket\r\n"
  8150. "Connection: Upgrade\r\n"
  8151. "Sec-WebSocket-Key: %s\r\n"
  8152. "Sec-WebSocket-Version: 13\r\n"
  8153. "\r\n";
  8154. }
  8155. /* Establish the client connection and request upgrade */
  8156. conn = mg_download(host,
  8157. port,
  8158. use_ssl,
  8159. error_buffer,
  8160. error_buffer_size,
  8161. handshake_req,
  8162. path,
  8163. host,
  8164. magic,
  8165. origin);
  8166. /* Connection object will be null if something goes wrong */
  8167. if (conn == NULL || (strcmp(conn->request_info.uri, "101") != 0)) {
  8168. if (!*error_buffer) {
  8169. /* if there is a connection, but it did not return 101,
  8170. * error_buffer is not yet set */
  8171. mg_snprintf(conn,
  8172. error_buffer,
  8173. error_buffer_size,
  8174. "Unexpected server reply");
  8175. }
  8176. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  8177. if (conn != NULL) {
  8178. mg_free(conn);
  8179. conn = NULL;
  8180. }
  8181. return conn;
  8182. }
  8183. /* For client connections, mg_context is fake. Since we need to set a
  8184. * callback function, we need to create a copy and modify it. */
  8185. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  8186. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  8187. newctx->user_data = user_data;
  8188. newctx->context_type = 2; /* client context type */
  8189. newctx->workerthreadcount = 1; /* one worker thread will be created */
  8190. newctx->workerthreadids =
  8191. (pthread_t *)mg_calloc(newctx->workerthreadcount, sizeof(pthread_t));
  8192. conn->ctx = newctx;
  8193. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  8194. sizeof(struct websocket_client_thread_data), 1);
  8195. thread_data->conn = conn;
  8196. thread_data->data_handler = data_func;
  8197. thread_data->close_handler = close_func;
  8198. thread_data->callback_data = NULL;
  8199. /* Start a thread to read the websocket client connection
  8200. * This thread will automatically stop when mg_disconnect is
  8201. * called on the client connection */
  8202. if (mg_start_thread_with_id(websocket_client_thread,
  8203. (void *)thread_data,
  8204. newctx->workerthreadids) != 0) {
  8205. mg_free((void *)thread_data);
  8206. mg_free((void *)newctx->workerthreadids);
  8207. mg_free((void *)newctx);
  8208. mg_free((void *)conn);
  8209. conn = NULL;
  8210. DEBUG_TRACE("%s",
  8211. "Websocket client connect thread could not be started\r\n");
  8212. }
  8213. #else
  8214. /* Appease "unused parameter" warnings */
  8215. (void)host;
  8216. (void)port;
  8217. (void)use_ssl;
  8218. (void)error_buffer;
  8219. (void)error_buffer_size;
  8220. (void)path;
  8221. (void)origin;
  8222. (void)user_data;
  8223. (void)data_func;
  8224. (void)close_func;
  8225. #endif
  8226. return conn;
  8227. }
  8228. static void process_new_connection(struct mg_connection *conn)
  8229. {
  8230. if (conn && conn->ctx) {
  8231. struct mg_request_info *ri = &conn->request_info;
  8232. int keep_alive_enabled, keep_alive, discard_len;
  8233. char ebuf[100];
  8234. int reqerr;
  8235. keep_alive_enabled =
  8236. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  8237. /* Important: on new connection, reset the receiving buffer. Credit
  8238. * goes to crule42. */
  8239. conn->data_len = 0;
  8240. do {
  8241. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  8242. /* The request sent by the client could not be understood by
  8243. * the server, or it was incomplete or a timeout. Send an
  8244. * error message and close the connection. */
  8245. if (reqerr > 0) {
  8246. /*assert(ebuf[0] != '\0');*/
  8247. send_http_error(conn, reqerr, "%s", ebuf);
  8248. }
  8249. } else if (!is_valid_uri(conn->request_info.uri)) {
  8250. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  8251. send_http_error(conn, 400, "%s", ebuf);
  8252. } else if (strcmp(ri->http_version, "1.0") &&
  8253. strcmp(ri->http_version, "1.1")) {
  8254. snprintf(ebuf,
  8255. sizeof(ebuf),
  8256. "Bad HTTP version: [%s]",
  8257. ri->http_version);
  8258. send_http_error(conn, 505, "%s", ebuf);
  8259. }
  8260. if (ebuf[0] == '\0') {
  8261. handle_request(conn);
  8262. if (conn->ctx->callbacks.end_request != NULL) {
  8263. conn->ctx->callbacks.end_request(conn, conn->status_code);
  8264. }
  8265. log_access(conn);
  8266. } else {
  8267. conn->must_close = 1;
  8268. }
  8269. if (ri->remote_user != NULL) {
  8270. mg_free((void *)ri->remote_user);
  8271. /* Important! When having connections with and without auth
  8272. * would cause double free and then crash */
  8273. ri->remote_user = NULL;
  8274. }
  8275. /* NOTE(lsm): order is important here. should_keep_alive() call is
  8276. * using parsed request, which will be invalid after memmove's
  8277. * below.
  8278. * Therefore, memorize should_keep_alive() result now for later use
  8279. * in loop exit condition. */
  8280. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  8281. conn->content_len >= 0 && should_keep_alive(conn);
  8282. /* Discard all buffered data for this request */
  8283. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  8284. conn->request_len + conn->content_len <
  8285. (int64_t)conn->data_len
  8286. ? (int)(conn->request_len + conn->content_len)
  8287. : conn->data_len;
  8288. /*assert(discard_len >= 0);*/
  8289. if (discard_len < 0)
  8290. break;
  8291. conn->data_len -= discard_len;
  8292. if (conn->data_len > 0)
  8293. memmove(
  8294. conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  8295. /* assert(conn->data_len >= 0); */
  8296. /* assert(conn->data_len <= conn->buf_size); */
  8297. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size))
  8298. break;
  8299. } while (keep_alive);
  8300. }
  8301. }
  8302. /* Worker threads take accepted socket from the queue */
  8303. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  8304. {
  8305. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8306. if (!ctx)
  8307. return 0;
  8308. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8309. DEBUG_TRACE("%s", "going idle");
  8310. /* If the queue is empty, wait. We're idle at this point. */
  8311. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  8312. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  8313. }
  8314. /* If we're stopping, sq_head may be equal to sq_tail. */
  8315. if (ctx->sq_head > ctx->sq_tail) {
  8316. /* Copy socket from the queue and increment tail */
  8317. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  8318. ctx->sq_tail++;
  8319. if (sp)
  8320. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  8321. /* Wrap pointers if needed */
  8322. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  8323. ctx->sq_tail -= QUEUE_SIZE(ctx);
  8324. ctx->sq_head -= QUEUE_SIZE(ctx);
  8325. }
  8326. }
  8327. (void)pthread_cond_signal(&ctx->sq_empty);
  8328. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8329. return !ctx->stop_flag;
  8330. #undef QUEUE_SIZE
  8331. }
  8332. static void *worker_thread_run(void *thread_func_param)
  8333. {
  8334. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8335. struct mg_connection *conn;
  8336. struct mg_workerTLS tls;
  8337. uint32_t addr;
  8338. mg_set_thread_name("worker");
  8339. tls.is_master = 0;
  8340. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8341. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8342. #endif
  8343. conn =
  8344. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  8345. if (conn == NULL) {
  8346. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  8347. } else {
  8348. pthread_setspecific(sTlsKey, &tls);
  8349. conn->buf_size = MAX_REQUEST_SIZE;
  8350. conn->buf = (char *)(conn + 1);
  8351. conn->ctx = ctx;
  8352. conn->request_info.user_data = ctx->user_data;
  8353. /* Allocate a mutex for this connection to allow communication both
  8354. * within the request handler and from elsewhere in the application */
  8355. (void)pthread_mutex_init(&conn->mutex, NULL);
  8356. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  8357. * signal sq_empty condvar to wake up the master waiting in
  8358. * produce_socket() */
  8359. while (consume_socket(ctx, &conn->client)) {
  8360. conn->conn_birth_time = time(NULL);
  8361. /* Fill in IP, port info early so even if SSL setup below fails,
  8362. * error handler would have the corresponding info.
  8363. * Thanks to Johannes Winkelmann for the patch.
  8364. * TODO(lsm, high): Fix IPv6 case */
  8365. conn->request_info.remote_port =
  8366. ntohs(conn->client.rsa.sin.sin_port);
  8367. sockaddr_to_string(conn->request_info.remote_addr,
  8368. sizeof(conn->request_info.remote_addr),
  8369. &conn->client.rsa);
  8370. /* TODO: #if defined(MG_LEGACY_INTERFACE) */
  8371. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  8372. memcpy(&conn->request_info.remote_ip, &addr, 4);
  8373. /* #endif */
  8374. conn->request_info.is_ssl = conn->client.is_ssl;
  8375. if (!conn->client.is_ssl
  8376. #ifndef NO_SSL
  8377. ||
  8378. sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  8379. #endif
  8380. ) {
  8381. process_new_connection(conn);
  8382. }
  8383. close_connection(conn);
  8384. }
  8385. }
  8386. /* Signal master that we're done with connection and exiting */
  8387. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8388. ctx->num_threads--;
  8389. (void)pthread_cond_signal(&ctx->thread_cond);
  8390. /* assert(ctx->num_threads >= 0); */
  8391. if (ctx->num_threads < 0)
  8392. return NULL;
  8393. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8394. pthread_setspecific(sTlsKey, NULL);
  8395. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8396. CloseHandle(tls.pthread_cond_helper_mutex);
  8397. #endif
  8398. mg_free(conn);
  8399. DEBUG_TRACE("%s", "exiting");
  8400. return NULL;
  8401. }
  8402. /* Threads have different return types on Windows and Unix. */
  8403. #ifdef _WIN32
  8404. static unsigned __stdcall worker_thread(void *thread_func_param)
  8405. {
  8406. worker_thread_run(thread_func_param);
  8407. return 0;
  8408. }
  8409. #else
  8410. static void *worker_thread(void *thread_func_param)
  8411. {
  8412. worker_thread_run(thread_func_param);
  8413. return NULL;
  8414. }
  8415. #endif /* _WIN32 */
  8416. /* Master thread adds accepted socket to a queue */
  8417. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  8418. {
  8419. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8420. if (!ctx)
  8421. return;
  8422. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8423. /* If the queue is full, wait */
  8424. while (ctx->stop_flag == 0 &&
  8425. ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  8426. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  8427. }
  8428. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  8429. /* Copy socket to the queue and increment head */
  8430. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  8431. ctx->sq_head++;
  8432. if (sp)
  8433. DEBUG_TRACE("queued socket %d", sp->sock);
  8434. }
  8435. (void)pthread_cond_signal(&ctx->sq_full);
  8436. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8437. #undef QUEUE_SIZE
  8438. }
  8439. static void accept_new_connection(const struct socket *listener,
  8440. struct mg_context *ctx)
  8441. {
  8442. struct socket so;
  8443. char src_addr[IP_ADDR_STR_LEN];
  8444. socklen_t len = sizeof(so.rsa);
  8445. int on = 1;
  8446. int timeout;
  8447. if (!listener)
  8448. return;
  8449. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  8450. INVALID_SOCKET) {
  8451. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  8452. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  8453. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  8454. closesocket(so.sock);
  8455. so.sock = INVALID_SOCKET;
  8456. } else {
  8457. /* Put so socket structure into the queue */
  8458. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  8459. set_close_on_exec(so.sock, fc(ctx));
  8460. so.is_ssl = listener->is_ssl;
  8461. so.ssl_redir = listener->ssl_redir;
  8462. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  8463. mg_cry(fc(ctx),
  8464. "%s: getsockname() failed: %s",
  8465. __func__,
  8466. strerror(ERRNO));
  8467. }
  8468. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  8469. * is enabled, and client resets the connection, server won't get
  8470. * TCP FIN or RST and will keep the connection open forever. With TCP
  8471. * keep-alive, next keep-alive handshake will figure out that the
  8472. * client is down and will close the server end.
  8473. * Thanks to Igor Klopov who suggested the patch. */
  8474. if (setsockopt(so.sock,
  8475. SOL_SOCKET,
  8476. SO_KEEPALIVE,
  8477. (SOCK_OPT_TYPE)&on,
  8478. sizeof(on)) != 0) {
  8479. mg_cry(fc(ctx),
  8480. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  8481. __func__,
  8482. strerror(ERRNO));
  8483. }
  8484. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  8485. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  8486. } else {
  8487. timeout = -1;
  8488. }
  8489. /* Set socket timeout to the given value, but not more than a
  8490. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  8491. * so the server can exit after that time if requested. */
  8492. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  8493. set_sock_timeout(so.sock, timeout);
  8494. } else {
  8495. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  8496. }
  8497. produce_socket(ctx, &so);
  8498. }
  8499. }
  8500. static void master_thread_run(void *thread_func_param)
  8501. {
  8502. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8503. struct mg_workerTLS tls;
  8504. struct pollfd *pfd;
  8505. unsigned int i;
  8506. unsigned int workerthreadcount;
  8507. if (!ctx)
  8508. return;
  8509. mg_set_thread_name("master");
  8510. /* Increase priority of the master thread */
  8511. #if defined(_WIN32)
  8512. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  8513. #elif defined(USE_MASTER_THREAD_PRIORITY)
  8514. int min_prio = sched_get_priority_min(SCHED_RR);
  8515. int max_prio = sched_get_priority_max(SCHED_RR);
  8516. if ((min_prio >= 0) && (max_prio >= 0) &&
  8517. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  8518. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  8519. struct sched_param sched_param = {0};
  8520. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  8521. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  8522. }
  8523. #endif
  8524. /* Initialize thread local storage */
  8525. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8526. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8527. #endif
  8528. tls.is_master = 1;
  8529. pthread_setspecific(sTlsKey, &tls);
  8530. /* Server starts *now* */
  8531. ctx->start_time = (unsigned long)time(NULL);
  8532. /* Allocate memory for the listening sockets, and start the server */
  8533. pfd =
  8534. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  8535. while (pfd != NULL && ctx->stop_flag == 0) {
  8536. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8537. pfd[i].fd = ctx->listening_sockets[i].sock;
  8538. pfd[i].events = POLLIN;
  8539. }
  8540. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  8541. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8542. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  8543. * successful poll, and POLLIN is defined as
  8544. * (POLLRDNORM | POLLRDBAND)
  8545. * Therefore, we're checking pfd[i].revents & POLLIN, not
  8546. * pfd[i].revents == POLLIN. */
  8547. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  8548. accept_new_connection(&ctx->listening_sockets[i], ctx);
  8549. }
  8550. }
  8551. }
  8552. }
  8553. mg_free(pfd);
  8554. DEBUG_TRACE("%s", "stopping workers");
  8555. /* Stop signal received: somebody called mg_stop. Quit. */
  8556. close_all_listening_sockets(ctx);
  8557. /* Wakeup workers that are waiting for connections to handle. */
  8558. pthread_cond_broadcast(&ctx->sq_full);
  8559. /* Wait until all threads finish */
  8560. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8561. while (ctx->num_threads > 0) {
  8562. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  8563. }
  8564. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8565. /* Join all worker threads to avoid leaking threads. */
  8566. workerthreadcount = ctx->workerthreadcount;
  8567. for (i = 0; i < workerthreadcount; i++) {
  8568. mg_join_thread(ctx->workerthreadids[i]);
  8569. }
  8570. #if !defined(NO_SSL)
  8571. if (ctx->ssl_ctx != NULL) {
  8572. uninitialize_ssl(ctx);
  8573. }
  8574. #endif
  8575. DEBUG_TRACE("%s", "exiting");
  8576. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8577. CloseHandle(tls.pthread_cond_helper_mutex);
  8578. #endif
  8579. pthread_setspecific(sTlsKey, NULL);
  8580. /* Signal mg_stop() that we're done.
  8581. * WARNING: This must be the very last thing this
  8582. * thread does, as ctx becomes invalid after this line. */
  8583. ctx->stop_flag = 2;
  8584. }
  8585. /* Threads have different return types on Windows and Unix. */
  8586. #ifdef _WIN32
  8587. static unsigned __stdcall master_thread(void *thread_func_param)
  8588. {
  8589. master_thread_run(thread_func_param);
  8590. return 0;
  8591. }
  8592. #else
  8593. static void *master_thread(void *thread_func_param)
  8594. {
  8595. master_thread_run(thread_func_param);
  8596. return NULL;
  8597. }
  8598. #endif /* _WIN32 */
  8599. static void free_context(struct mg_context *ctx)
  8600. {
  8601. int i;
  8602. struct mg_request_handler_info *tmp_rh;
  8603. if (ctx == NULL)
  8604. return;
  8605. if (ctx->callbacks.exit_context) {
  8606. ctx->callbacks.exit_context(ctx);
  8607. }
  8608. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  8609. */
  8610. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  8611. (void)pthread_cond_destroy(&ctx->thread_cond);
  8612. (void)pthread_cond_destroy(&ctx->sq_empty);
  8613. (void)pthread_cond_destroy(&ctx->sq_full);
  8614. /* Destroy other context global data structures mutex */
  8615. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  8616. #if defined(USE_TIMERS)
  8617. timers_exit(ctx);
  8618. #endif
  8619. /* Deallocate config parameters */
  8620. for (i = 0; i < NUM_OPTIONS; i++) {
  8621. if (ctx->config[i] != NULL)
  8622. #if defined(_MSC_VER)
  8623. #pragma warning(suppress : 6001)
  8624. #endif
  8625. mg_free(ctx->config[i]);
  8626. }
  8627. /* Deallocate request handlers */
  8628. while (ctx->request_handlers) {
  8629. tmp_rh = ctx->request_handlers;
  8630. ctx->request_handlers = tmp_rh->next;
  8631. mg_free(tmp_rh->uri);
  8632. mg_free(tmp_rh);
  8633. }
  8634. #ifndef NO_SSL
  8635. /* Deallocate SSL context */
  8636. if (ctx->ssl_ctx != NULL) {
  8637. SSL_CTX_free(ctx->ssl_ctx);
  8638. }
  8639. if (ssl_mutexes != NULL) {
  8640. mg_free(ssl_mutexes);
  8641. ssl_mutexes = NULL;
  8642. }
  8643. #endif /* !NO_SSL */
  8644. /* Deallocate worker thread ID array */
  8645. if (ctx->workerthreadids != NULL) {
  8646. mg_free(ctx->workerthreadids);
  8647. }
  8648. /* Deallocate the tls variable */
  8649. if (mg_atomic_dec(&sTlsInit) == 0) {
  8650. pthread_key_delete(sTlsKey);
  8651. }
  8652. /* deallocate system name string */
  8653. mg_free(ctx->systemName);
  8654. /* Deallocate context itself */
  8655. mg_free(ctx);
  8656. }
  8657. void mg_stop(struct mg_context *ctx)
  8658. {
  8659. if (!ctx)
  8660. return;
  8661. ctx->stop_flag = 1;
  8662. /* Wait until mg_fini() stops */
  8663. while (ctx->stop_flag != 2) {
  8664. (void)mg_sleep(10);
  8665. }
  8666. mg_join_thread(ctx->masterthreadid);
  8667. free_context(ctx);
  8668. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8669. (void)WSACleanup();
  8670. #endif /* _WIN32 && !__SYMBIAN32__ */
  8671. }
  8672. static void get_system_name(char **sysName)
  8673. {
  8674. #if defined(_WIN32)
  8675. #if !defined(__SYMBIAN32__)
  8676. char name[128];
  8677. DWORD dwVersion = 0;
  8678. DWORD dwMajorVersion = 0;
  8679. DWORD dwMinorVersion = 0;
  8680. DWORD dwBuild = 0;
  8681. #ifdef _MSC_VER
  8682. #pragma warning(push)
  8683. // GetVersion was declared deprecated
  8684. #pragma warning(disable : 4996)
  8685. #endif
  8686. dwVersion = GetVersion();
  8687. #ifdef _MSC_VER
  8688. #pragma warning(pop)
  8689. #endif
  8690. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  8691. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  8692. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  8693. (void)dwBuild;
  8694. sprintf(name,
  8695. "Windows %u.%u",
  8696. (unsigned)dwMajorVersion,
  8697. (unsigned)dwMinorVersion);
  8698. *sysName = mg_strdup(name);
  8699. #else
  8700. *sysName = mg_strdup("Symbian");
  8701. #endif
  8702. #else
  8703. struct utsname name;
  8704. memset(&name, 0, sizeof(name));
  8705. uname(&name);
  8706. *sysName = mg_strdup(name.sysname);
  8707. #endif
  8708. }
  8709. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  8710. void *user_data,
  8711. const char **options)
  8712. {
  8713. struct mg_context *ctx;
  8714. const char *name, *value, *default_value;
  8715. int idx, ok, workerthreadcount;
  8716. unsigned int i;
  8717. void (*exit_callback)(const struct mg_context *ctx) = 0;
  8718. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8719. WSADATA data;
  8720. WSAStartup(MAKEWORD(2, 2), &data);
  8721. #if defined(_MSC_VER)
  8722. #pragma warning(suppress : 28125)
  8723. #endif
  8724. if (!sTlsInit)
  8725. InitializeCriticalSection(&global_log_file_lock);
  8726. #endif /* _WIN32 && !__SYMBIAN32__ */
  8727. /* Allocate context and initialize reasonable general case defaults. */
  8728. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  8729. return NULL;
  8730. }
  8731. if (mg_atomic_inc(&sTlsInit) == 1) {
  8732. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  8733. /* Fatal error - abort start. However, this situation should never
  8734. * occur in practice. */
  8735. mg_atomic_dec(&sTlsInit);
  8736. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  8737. mg_free(ctx);
  8738. return NULL;
  8739. }
  8740. } else {
  8741. /* TODO (low): istead of sleeping, check if sTlsKey is already
  8742. * initialized. */
  8743. mg_sleep(1);
  8744. }
  8745. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  8746. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  8747. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  8748. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  8749. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  8750. if (!ok) {
  8751. /* Fatal error - abort start. However, this situation should never
  8752. * occur in practice. */
  8753. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  8754. mg_free(ctx);
  8755. return NULL;
  8756. }
  8757. if (callbacks) {
  8758. ctx->callbacks = *callbacks;
  8759. exit_callback = callbacks->exit_context;
  8760. ctx->callbacks.exit_context = 0;
  8761. }
  8762. ctx->user_data = user_data;
  8763. ctx->request_handlers = NULL;
  8764. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8765. ctx->shared_lua_websockets = 0;
  8766. #endif
  8767. while (options && (name = *options++) != NULL) {
  8768. if ((idx = get_option_index(name)) == -1) {
  8769. mg_cry(fc(ctx), "Invalid option: %s", name);
  8770. free_context(ctx);
  8771. return NULL;
  8772. } else if ((value = *options++) == NULL) {
  8773. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  8774. free_context(ctx);
  8775. return NULL;
  8776. }
  8777. if (ctx->config[idx] != NULL) {
  8778. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  8779. mg_free(ctx->config[idx]);
  8780. }
  8781. ctx->config[idx] = mg_strdup(value);
  8782. DEBUG_TRACE("[%s] -> [%s]", name, value);
  8783. }
  8784. /* Set default value if needed */
  8785. for (i = 0; config_options[i].name != NULL; i++) {
  8786. default_value = config_options[i].default_value;
  8787. if (ctx->config[i] == NULL && default_value != NULL) {
  8788. ctx->config[i] = mg_strdup(default_value);
  8789. }
  8790. }
  8791. #if defined(NO_FILES)
  8792. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  8793. mg_cry(fc(ctx), "%s", "Document root must not be set");
  8794. free_context(ctx);
  8795. return NULL;
  8796. }
  8797. #endif
  8798. get_system_name(&ctx->systemName);
  8799. /* NOTE(lsm): order is important here. SSL certificates must
  8800. * be initialized before listening ports. UID must be set last. */
  8801. if (!set_gpass_option(ctx) ||
  8802. #if !defined(NO_SSL)
  8803. !set_ssl_option(ctx) ||
  8804. #endif
  8805. !set_ports_option(ctx) ||
  8806. #if !defined(_WIN32)
  8807. !set_uid_option(ctx) ||
  8808. #endif
  8809. !set_acl_option(ctx)) {
  8810. free_context(ctx);
  8811. return NULL;
  8812. }
  8813. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  8814. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  8815. * won't kill the whole process. */
  8816. (void)signal(SIGPIPE, SIG_IGN);
  8817. #endif /* !_WIN32 && !__SYMBIAN32__ */
  8818. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  8819. if (workerthreadcount > MAX_WORKER_THREADS) {
  8820. mg_cry(fc(ctx), "Too many worker threads");
  8821. free_context(ctx);
  8822. return NULL;
  8823. }
  8824. if (workerthreadcount > 0) {
  8825. ctx->workerthreadcount = ((unsigned int)(workerthreadcount));
  8826. ctx->workerthreadids =
  8827. (pthread_t *)mg_calloc(ctx->workerthreadcount, sizeof(pthread_t));
  8828. if (ctx->workerthreadids == NULL) {
  8829. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  8830. free_context(ctx);
  8831. return NULL;
  8832. }
  8833. }
  8834. #if defined(USE_TIMERS)
  8835. if (timers_init(ctx) != 0) {
  8836. mg_cry(fc(ctx), "Error creating timers");
  8837. free_context(ctx);
  8838. return NULL;
  8839. }
  8840. #endif
  8841. /* Context has been created - init user libraries */
  8842. if (ctx->callbacks.init_context) {
  8843. ctx->callbacks.init_context(ctx);
  8844. }
  8845. ctx->callbacks.exit_context = exit_callback;
  8846. ctx->context_type = 1; /* server context */
  8847. /* Start master (listening) thread */
  8848. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  8849. /* Start worker threads */
  8850. for (i = 0; i < ctx->workerthreadcount; i++) {
  8851. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8852. ctx->num_threads++;
  8853. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8854. if (mg_start_thread_with_id(
  8855. worker_thread, ctx, &ctx->workerthreadids[i]) != 0) {
  8856. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8857. ctx->num_threads--;
  8858. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8859. if (i > 0) {
  8860. mg_cry(fc(ctx),
  8861. "Cannot start worker thread %i: error %ld",
  8862. i + 1,
  8863. (long)ERRNO);
  8864. } else {
  8865. mg_cry(
  8866. fc(ctx), "Cannot create threads: error %ld", (long)ERRNO);
  8867. free_context(ctx);
  8868. return NULL;
  8869. }
  8870. break;
  8871. }
  8872. }
  8873. return ctx;
  8874. }